python_code
stringlengths 0
679k
| repo_name
stringlengths 9
41
| file_path
stringlengths 6
149
|
---|---|---|
# 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.
# include parent path
import numpy as np
import warp as wp
from warp.tests.test_base import *
import unittest
wp.init()
@wp.kernel
def mul_1d(a: wp.array1d(dtype=float), s: float):
i = wp.tid()
a[i] = a[i] * s
@wp.kernel
def mul_2d(a: wp.array2d(dtype=float), s: float):
i, j = wp.tid()
a[i, j] = a[i, j] * s
@wp.kernel
def mul_3d(a: wp.array3d(dtype=float), s: float):
i, j, k = wp.tid()
a[i, j, k] = a[i, j, k] * s
@wp.kernel
def mul_4d(a: wp.array4d(dtype=float), s: float):
i, j, k, l = wp.tid()
a[i, j, k, l] = a[i, j, k, l] * s
def test_copy_strided(test, device):
with wp.ScopedDevice(device):
np_data1 = np.arange(10, dtype=np.float32)
np_data2 = np.arange(100, dtype=np.float32).reshape((10, 10))
np_data3 = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))
np_data4 = np.arange(10000, dtype=np.float32).reshape((10, 10, 10, 10))
wp_data1 = wp.array(data=np_data1, copy=True)
wp_data2 = wp.array(data=np_data2, copy=True)
wp_data3 = wp.array(data=np_data3, copy=True)
wp_data4 = wp.array(data=np_data4, copy=True)
expected1 = np_data1[1::2]
expected2 = np_data2[1::2, 1::2]
expected3 = np_data3[1::2, 1::2, 1::2]
expected4 = np_data4[1::2, 1::2, 1::2, 1::2]
a1 = wp_data1[1::2]
a2 = wp_data2[1::2, 1::2]
a3 = wp_data3[1::2, 1::2, 1::2]
a4 = wp_data4[1::2, 1::2, 1::2, 1::2]
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
b1 = wp.zeros_like(a1)
b2 = wp.zeros_like(a2)
b3 = wp.zeros_like(a3)
b4 = wp.zeros_like(a4)
test.assertFalse(a1.is_contiguous)
test.assertFalse(a2.is_contiguous)
test.assertFalse(a3.is_contiguous)
test.assertFalse(a4.is_contiguous)
test.assertTrue(b1.is_contiguous)
test.assertTrue(b2.is_contiguous)
test.assertTrue(b3.is_contiguous)
test.assertTrue(b4.is_contiguous)
# copy non-contiguous to contiguous
wp.copy(b1, a1)
wp.copy(b2, a2)
wp.copy(b3, a3)
wp.copy(b4, a4)
assert_np_equal(a1.numpy(), b1.numpy())
assert_np_equal(a2.numpy(), b2.numpy())
assert_np_equal(a3.numpy(), b3.numpy())
assert_np_equal(a4.numpy(), b4.numpy())
s = 2.0
wp.launch(mul_1d, dim=b1.shape, inputs=[b1, s])
wp.launch(mul_2d, dim=b2.shape, inputs=[b2, s])
wp.launch(mul_3d, dim=b3.shape, inputs=[b3, s])
wp.launch(mul_4d, dim=b4.shape, inputs=[b4, s])
# copy contiguous to non-contiguous
wp.copy(a1, b1)
wp.copy(a2, b2)
wp.copy(a3, b3)
wp.copy(a4, b4)
assert_np_equal(a1.numpy(), b1.numpy())
assert_np_equal(a2.numpy(), b2.numpy())
assert_np_equal(a3.numpy(), b3.numpy())
assert_np_equal(a4.numpy(), b4.numpy())
assert_np_equal(a1.numpy(), expected1 * s)
assert_np_equal(a2.numpy(), expected2 * s)
assert_np_equal(a3.numpy(), expected3 * s)
assert_np_equal(a4.numpy(), expected4 * s)
def test_copy_indexed(test, device):
with wp.ScopedDevice(device):
np_data1 = np.arange(10, dtype=np.float32)
np_data2 = np.arange(100, dtype=np.float32).reshape((10, 10))
np_data3 = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))
np_data4 = np.arange(10000, dtype=np.float32).reshape((10, 10, 10, 10))
wp_data1 = wp.array(data=np_data1, copy=True)
wp_data2 = wp.array(data=np_data2, copy=True)
wp_data3 = wp.array(data=np_data3, copy=True)
wp_data4 = wp.array(data=np_data4, copy=True)
np_indices = np.array([1, 5, 8, 9])
wp_indices = wp.array(data=np_indices, dtype=wp.int32)
# Note: Indexing using multiple index arrays works differently
# in Numpy and Warp, so the syntax is different.
expected1 = np_data1[np_indices]
expected2 = np_data2[np_indices][:, np_indices]
expected3 = np_data3[np_indices][:, np_indices][:, :, np_indices]
expected4 = np_data4[np_indices][:, np_indices][:, :, np_indices][:, :, :, np_indices]
a1 = wp_data1[wp_indices]
a2 = wp_data2[wp_indices, wp_indices]
a3 = wp_data3[wp_indices, wp_indices, wp_indices]
a4 = wp_data4[wp_indices, wp_indices, wp_indices, wp_indices]
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
b1 = wp.zeros_like(a1)
b2 = wp.zeros_like(a2)
b3 = wp.zeros_like(a3)
b4 = wp.zeros_like(a4)
test.assertFalse(a1.is_contiguous)
test.assertFalse(a2.is_contiguous)
test.assertFalse(a3.is_contiguous)
test.assertFalse(a4.is_contiguous)
test.assertTrue(b1.is_contiguous)
test.assertTrue(b2.is_contiguous)
test.assertTrue(b3.is_contiguous)
test.assertTrue(b4.is_contiguous)
# copy non-contiguous to contiguous
wp.copy(b1, a1)
wp.copy(b2, a2)
wp.copy(b3, a3)
wp.copy(b4, a4)
assert_np_equal(a1.numpy(), b1.numpy())
assert_np_equal(a2.numpy(), b2.numpy())
assert_np_equal(a3.numpy(), b3.numpy())
assert_np_equal(a4.numpy(), b4.numpy())
s = 2.0
wp.launch(mul_1d, dim=b1.shape, inputs=[b1, s])
wp.launch(mul_2d, dim=b2.shape, inputs=[b2, s])
wp.launch(mul_3d, dim=b3.shape, inputs=[b3, s])
wp.launch(mul_4d, dim=b4.shape, inputs=[b4, s])
# copy contiguous to non-contiguous
wp.copy(a1, b1)
wp.copy(a2, b2)
wp.copy(a3, b3)
wp.copy(a4, b4)
assert_np_equal(a1.numpy(), b1.numpy())
assert_np_equal(a2.numpy(), b2.numpy())
assert_np_equal(a3.numpy(), b3.numpy())
assert_np_equal(a4.numpy(), b4.numpy())
assert_np_equal(a1.numpy(), expected1 * s)
assert_np_equal(a2.numpy(), expected2 * s)
assert_np_equal(a3.numpy(), expected3 * s)
assert_np_equal(a4.numpy(), expected4 * s)
def register(parent):
devices = get_test_devices()
class TestCopy(parent):
pass
add_function_test(TestCopy, "test_copy_strided", test_copy_strided, devices=devices)
add_function_test(TestCopy, "test_copy_indexed", test_copy_indexed, devices=devices)
return TestCopy
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_copy.py |
import warp as wp
import numpy as np
import unittest
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def test_pow(x: float, e: float, result: float):
tid = wp.tid()
y = wp.pow(-2.0, e)
wp.expect_eq(y, result)
def test_fast_math(test, device):
# on all systems pow() should handle negative base correctly
wp.set_module_options({"fast_math": False})
wp.launch(test_pow, dim=1, inputs=[-2.0, 2.0, 4.0], device=device)
# on CUDA with --fast-math enabled taking the pow()
# of a negative number will result in a NaN
if wp.get_device(device).is_cuda:
wp.set_module_options({"fast_math": True})
with test.assertRaises(Exception):
with CheckOutput():
wp.launch(test_pow, dim=1, inputs=[-2.0, 2.0, 2.0], device=device)
def register(parent):
class TestFastMath(parent):
pass
devices = get_test_devices()
add_function_test(TestFastMath, "test_fast_math", test_fast_math, devices=devices)
return TestFastMath
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_fast_math.py |
import numpy as np
import math
import warp as wp
from warp.tests.test_base import *
wp.init()
np_float_types = [np.float32, np.float64, np.float16]
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 test_spatial_vector_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)]
vec3 = wp.types.vector(length=3, dtype=wptype)
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_vector_component_constructor(
input: wp.array(dtype=wptype),
out: wp.array(dtype=wptype),
):
result = spatial_vector(input[0], input[1], input[2], input[3], input[4], input[5])
# multiply the output by 2 so we've got something to backpropagate:
out[0] = wptype(2) * result[0]
out[1] = wptype(2) * result[1]
out[2] = wptype(2) * result[2]
out[3] = wptype(2) * result[3]
out[4] = wptype(2) * result[4]
out[5] = wptype(2) * result[5]
def check_spatial_vector_vector_constructor(
input: wp.array(dtype=wptype),
out: wp.array(dtype=wptype),
):
result = spatial_vector(vec3(input[0], input[1], input[2]), vec3(input[3], input[4], input[5]))
# multiply the output by 2 so we've got something to backpropagate:
out[0] = wptype(2) * result[0]
out[1] = wptype(2) * result[1]
out[2] = wptype(2) * result[2]
out[3] = wptype(2) * result[3]
out[4] = wptype(2) * result[4]
out[5] = wptype(2) * result[5]
kernel = getkernel(check_spatial_vector_component_constructor, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
vec_kernel = getkernel(check_spatial_vector_vector_constructor, suffix=dtype.__name__)
if register_kernels:
return
input = wp.array(np.random.randn(6).astype(dtype), requires_grad=True, device=device)
output = wp.zeros_like(input)
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol)
for i in range(len(input)):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
input = wp.array(np.random.randn(6).astype(dtype), requires_grad=True, device=device)
output = wp.zeros_like(input)
wp.launch(vec_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol)
for i in range(len(input)):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
def test_spatial_vector_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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_vector_indexing(
input: wp.array(dtype=spatial_vector),
out: wp.array(dtype=wptype),
):
inpt = input[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
out[idx] = wptype(2) * inpt[i]
idx = idx + 1
kernel = getkernel(check_spatial_vector_indexing, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(np.random.randn(1, 6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
outcmps = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device)
assert_np_equal(outcmps.numpy(), 2 * input.numpy().ravel(), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcmps, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(6, dtype=dtype)
expectedresult[i] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
def test_spatial_vector_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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_vector_scalar_mul(
s: wp.array(dtype=wptype),
q: wp.array(dtype=spatial_vector),
outcmps_l: wp.array(dtype=wptype),
outcmps_r: wp.array(dtype=wptype),
):
lresult = s[0] * q[0]
rresult = q[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(6):
outcmps_l[i] = wptype(2) * lresult[i]
outcmps_r[i] = wptype(2) * rresult[i]
kernel = getkernel(check_spatial_vector_scalar_mul, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
s = wp.array(np.random.randn(1).astype(dtype), requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
outcmps_l = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
outcmps_r = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[s, q],
outputs=[
outcmps_l,
outcmps_r,
],
device=device,
)
assert_np_equal(outcmps_l.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol)
assert_np_equal(outcmps_r.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
# test left/right mul gradients:
for wrt in [outcmps_l, outcmps_r]:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s, q], outputs=[outcmps_l, outcmps_r], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[wrt, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(6, dtype=dtype)
expectedresult[i] = 2 * s.numpy()[0]
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * q.numpy()[0, i], tol=tol)
tape.zero()
def test_spatial_vector_add_sub(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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_vector_add_sub(
q: wp.array(dtype=spatial_vector),
v: wp.array(dtype=spatial_vector),
outputs_add: wp.array(dtype=wptype),
outputs_sub: wp.array(dtype=wptype),
):
addresult = q[0] + v[0]
subresult = q[0] - v[0]
for i in range(6):
outputs_add[i] = wptype(2) * addresult[i]
outputs_sub[i] = wptype(2) * subresult[i]
kernel = getkernel(check_spatial_vector_add_sub, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
v = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
outputs_add = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
outputs_sub = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
q,
v,
],
outputs=[outputs_add, outputs_sub],
device=device,
)
assert_np_equal(outputs_add.numpy(), 2 * (q.numpy() + v.numpy()), tol=tol)
assert_np_equal(outputs_sub.numpy(), 2 * (q.numpy() - v.numpy()), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
# test add gradients:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_add, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(6, dtype=dtype)
expectedresult[i] = 2
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=tol)
tape.zero()
# test subtraction gradients:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_sub, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(6, dtype=dtype)
expectedresult[i] = 2
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[v].numpy()[0], -expectedresult, tol=tol)
tape.zero()
def test_spatial_dot(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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_dot(
s: wp.array(dtype=spatial_vector),
v: wp.array(dtype=spatial_vector),
dot: wp.array(dtype=wptype),
):
dot[0] = wptype(2) * wp.spatial_dot(v[0], s[0])
kernel = getkernel(check_spatial_dot, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
v = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
dot = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
v,
],
outputs=[dot],
device=device,
)
assert_np_equal(dot.numpy()[0], 2.0 * (v.numpy() * s.numpy()).sum(), tol=tol)
tape.backward(loss=dot)
sgrads = tape.gradients[s].numpy()[0]
expected_grads = 2.0 * v.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v].numpy()[0]
expected_grads = 2.0 * s.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=tol)
def test_spatial_cross(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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_cross(
s: wp.array(dtype=spatial_vector),
v: wp.array(dtype=spatial_vector),
outputs: wp.array(dtype=wptype),
outputs_dual: wp.array(dtype=wptype),
outputs_wcrossw: wp.array(dtype=wptype),
outputs_vcrossw: wp.array(dtype=wptype),
outputs_wcrossv: wp.array(dtype=wptype),
outputs_vcrossv: wp.array(dtype=wptype),
):
c = wp.spatial_cross(s[0], v[0])
d = wp.spatial_cross_dual(s[0], v[0])
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(6):
outputs[i] = wptype(2) * c[i]
outputs_dual[i] = wptype(2) * d[i]
sw = wp.spatial_top(s[0])
sv = wp.spatial_bottom(s[0])
vw = wp.spatial_top(v[0])
vv = wp.spatial_bottom(v[0])
wcrossw = wp.cross(sw, vw)
vcrossw = wp.cross(sv, vw)
wcrossv = wp.cross(sw, vv)
vcrossv = wp.cross(sv, vv)
for i in range(3):
outputs_wcrossw[i] = wcrossw[i]
outputs_vcrossw[i] = vcrossw[i]
outputs_wcrossv[i] = wcrossv[i]
outputs_vcrossv[i] = vcrossv[i]
kernel = getkernel(check_spatial_cross, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
s = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
v = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
outputs = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
outputs_dual = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
outputs_wcrossw = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_vcrossw = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_wcrossv = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_vcrossv = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s,
v,
],
outputs=[outputs, outputs_dual, outputs_wcrossw, outputs_vcrossw, outputs_wcrossv, outputs_vcrossv],
device=device,
)
sw = s.numpy()[0, :3]
sv = s.numpy()[0, 3:]
vw = v.numpy()[0, :3]
vv = v.numpy()[0, 3:]
wcrossw = np.cross(sw, vw)
vcrossw = np.cross(sv, vw)
wcrossv = np.cross(sw, vv)
vcrossv = np.cross(sv, vv)
assert_np_equal(outputs.numpy()[:3], 2 * wcrossw, tol=tol)
assert_np_equal(outputs.numpy()[3:], 2 * (vcrossw + wcrossv), tol=tol)
assert_np_equal(outputs_dual.numpy()[:3], 2 * (wcrossw + vcrossv), tol=tol)
assert_np_equal(outputs_dual.numpy()[3:], 2 * wcrossv, tol=tol)
for i in range(3):
cmp_w = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_v = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_w_dual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_v_dual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_wcrossw = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_vcrossw = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_wcrossv = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_vcrossv = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
v,
],
outputs=[outputs, outputs_dual, outputs_wcrossw, outputs_vcrossw, outputs_wcrossv, outputs_vcrossv],
device=device,
)
# ith w and v vector components of spatial_cross:
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp_w], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i + 3], outputs=[cmp_v], device=device)
# ith w and v vector components of spatial_cross_dual:
wp.launch(output_select_kernel, dim=1, inputs=[outputs_dual, i], outputs=[cmp_w_dual], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_dual, i + 3], outputs=[cmp_v_dual], device=device)
# ith vector components of some cross products:
wp.launch(output_select_kernel, dim=1, inputs=[outputs_wcrossw, i], outputs=[cmp_wcrossw], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_vcrossw, i], outputs=[cmp_vcrossw], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_wcrossv, i], outputs=[cmp_wcrossv], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_vcrossv, i], outputs=[cmp_vcrossv], device=device)
def getgrads(cmp):
tape.backward(loss=cmp)
sgrads = 1.0 * tape.gradients[s].numpy()
vgrads = 1.0 * tape.gradients[v].numpy()
tape.zero()
return sgrads, vgrads
dcmp_w_ds, dcmp_w_dv = getgrads(cmp_w)
dcmp_v_ds, dcmp_v_dv = getgrads(cmp_v)
dcmp_w_dual_ds, dcmp_w_dual_dv = getgrads(cmp_w_dual)
dcmp_v_dual_ds, dcmp_v_dual_dv = getgrads(cmp_v_dual)
dcmp_wcrossw_ds, dcmp_wcrossw_dv = getgrads(cmp_wcrossw)
dcmp_vcrossw_ds, dcmp_vcrossw_dv = getgrads(cmp_vcrossw)
dcmp_wcrossv_ds, dcmp_wcrossv_dv = getgrads(cmp_wcrossv)
dcmp_vcrossv_ds, dcmp_vcrossv_dv = getgrads(cmp_vcrossv)
assert_np_equal(dcmp_w_ds, 2 * dcmp_wcrossw_ds, tol=tol)
assert_np_equal(dcmp_w_dv, 2 * dcmp_wcrossw_dv, tol=tol)
assert_np_equal(dcmp_v_ds, 2 * (dcmp_vcrossw_ds + dcmp_wcrossv_ds), tol=tol)
assert_np_equal(dcmp_v_dv, 2 * (dcmp_vcrossw_dv + dcmp_wcrossv_dv), tol=tol)
assert_np_equal(dcmp_w_dual_ds, 2 * (dcmp_wcrossw_ds + dcmp_vcrossv_ds), tol=tol)
assert_np_equal(dcmp_w_dual_dv, 2 * (dcmp_wcrossw_dv + dcmp_vcrossv_dv), tol=tol)
assert_np_equal(dcmp_v_dual_ds, 2 * dcmp_wcrossv_ds, tol=tol)
assert_np_equal(dcmp_v_dual_dv, 2 * dcmp_wcrossv_dv, tol=tol)
def test_spatial_top_bottom(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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
def check_spatial_top_bottom(
s: wp.array(dtype=spatial_vector),
outputs: wp.array(dtype=wptype),
):
top = wp.spatial_top(s[0])
bottom = wp.spatial_bottom(s[0])
outputs[0] = wptype(2) * top[0]
outputs[1] = wptype(2) * top[1]
outputs[2] = wptype(2) * top[2]
outputs[3] = wptype(2) * bottom[0]
outputs[4] = wptype(2) * bottom[1]
outputs[5] = wptype(2) * bottom[2]
kernel = getkernel(check_spatial_top_bottom, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
s = wp.array(np.random.randn(6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
outputs = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s,
],
outputs=[outputs],
device=device,
)
assert_np_equal(outputs.numpy(), 2.0 * s.numpy(), tol=tol)
for i in range(6):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
],
outputs=[outputs],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(6)
expectedgrads[i] = 2
assert_np_equal(tape.gradients[s].numpy(), expectedgrads)
tape.zero()
def test_transform_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)]
vec3 = wp.types.vector(length=3, dtype=wptype)
transform = wp.types.transformation(dtype=wptype)
quat = wp.types.quaternion(dtype=wptype)
def check_transform_constructor(
input: wp.array(dtype=wptype),
out: wp.array(dtype=wptype),
):
result = transform(vec3(input[0], input[1], input[2]), quat(input[3], input[4], input[5], input[6]))
# multiply the output by 2 so we've got something to backpropagate:
out[0] = wptype(2) * result[0]
out[1] = wptype(2) * result[1]
out[2] = wptype(2) * result[2]
out[3] = wptype(2) * result[3]
out[4] = wptype(2) * result[4]
out[5] = wptype(2) * result[5]
out[6] = wptype(2) * result[6]
kernel = getkernel(check_transform_constructor, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
p = np.random.randn(3).astype(dtype)
q = np.random.randn(4).astype(dtype)
q /= np.linalg.norm(q)
input = wp.array(np.concatenate((p, q)), requires_grad=True, device=device)
output = wp.zeros_like(input)
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol)
for i in range(len(input)):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
def test_transform_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)]
transform = wp.types.transformation(dtype=wptype)
def check_transform_indexing(
input: wp.array(dtype=transform),
out: wp.array(dtype=wptype),
):
inpt = input[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(7):
out[idx] = wptype(2) * inpt[i]
idx = idx + 1
kernel = getkernel(check_transform_indexing, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(np.random.randn(1, 7).astype(dtype), dtype=transform, requires_grad=True, device=device)
outcmps = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device)
assert_np_equal(outcmps.numpy(), 2 * input.numpy().ravel(), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(7):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcmps, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(7, dtype=dtype)
expectedresult[i] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
def test_transform_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)]
transform = wp.types.transformation(dtype=wptype)
def check_transform_scalar_mul(
s: wp.array(dtype=wptype),
q: wp.array(dtype=transform),
outcmps_l: wp.array(dtype=wptype),
outcmps_r: wp.array(dtype=wptype),
):
lresult = s[0] * q[0]
rresult = q[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(7):
outcmps_l[i] = wptype(2) * lresult[i]
outcmps_r[i] = wptype(2) * rresult[i]
kernel = getkernel(check_transform_scalar_mul, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
s = wp.array(np.random.randn(1).astype(dtype), requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 7).astype(dtype), dtype=transform, requires_grad=True, device=device)
outcmps_l = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
outcmps_r = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[s, q],
outputs=[
outcmps_l,
outcmps_r,
],
device=device,
)
assert_np_equal(outcmps_l.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol)
assert_np_equal(outcmps_r.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(7):
# test left/right mul gradients:
for wrt in [outcmps_l, outcmps_r]:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s, q], outputs=[outcmps_l, outcmps_r], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[wrt, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(7, dtype=dtype)
expectedresult[i] = 2 * s.numpy()[0]
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * q.numpy()[0, i], tol=tol)
tape.zero()
def test_transform_add_sub(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)]
transform = wp.types.transformation(dtype=wptype)
def check_transform_add_sub(
q: wp.array(dtype=transform),
v: wp.array(dtype=transform),
outputs_add: wp.array(dtype=wptype),
outputs_sub: wp.array(dtype=wptype),
):
addresult = q[0] + v[0]
subresult = q[0] - v[0]
for i in range(7):
outputs_add[i] = wptype(2) * addresult[i]
outputs_sub[i] = wptype(2) * subresult[i]
kernel = getkernel(check_transform_add_sub, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = wp.array(np.random.randn(7).astype(dtype), dtype=transform, requires_grad=True, device=device)
v = wp.array(np.random.randn(7).astype(dtype), dtype=transform, requires_grad=True, device=device)
outputs_add = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
outputs_sub = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
q,
v,
],
outputs=[outputs_add, outputs_sub],
device=device,
)
assert_np_equal(outputs_add.numpy(), 2 * (q.numpy() + v.numpy()), tol=tol)
assert_np_equal(outputs_sub.numpy(), 2 * (q.numpy() - v.numpy()), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(7):
# test add gradients:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_add, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(7, dtype=dtype)
expectedresult[i] = 2
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=tol)
tape.zero()
# test subtraction gradients:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_sub, i], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(7, dtype=dtype)
expectedresult[i] = 2
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[v].numpy()[0], -expectedresult, tol=tol)
tape.zero()
def test_transform_get_trans_rot(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)]
transform = wp.types.transformation(dtype=wptype)
def check_transform_get_trans_rot(
s: wp.array(dtype=transform),
outputs: wp.array(dtype=wptype),
):
trans = wp.transform_get_translation(s[0])
q = wp.transform_get_rotation(s[0])
outputs[0] = wptype(2) * trans[0]
outputs[1] = wptype(2) * trans[1]
outputs[2] = wptype(2) * trans[2]
outputs[3] = wptype(2) * q[0]
outputs[4] = wptype(2) * q[1]
outputs[5] = wptype(2) * q[2]
outputs[6] = wptype(2) * q[3]
kernel = getkernel(check_transform_get_trans_rot, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
s = wp.array(np.random.randn(7).astype(dtype), dtype=transform, requires_grad=True, device=device)
outputs = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s,
],
outputs=[outputs],
device=device,
)
assert_np_equal(outputs.numpy(), 2.0 * s.numpy(), tol=tol)
for i in range(7):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
],
outputs=[outputs],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(7)
expectedgrads[i] = 2
assert_np_equal(tape.gradients[s].numpy(), expectedgrads)
tape.zero()
def test_transform_multiply(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)]
transform = wp.types.transformation(dtype=wptype)
def check_transform_multiply(
a: wp.array(dtype=transform),
b: wp.array(dtype=transform),
outputs: wp.array(dtype=wptype),
outputs_fn: wp.array(dtype=wptype),
outputs_manual: wp.array(dtype=wptype),
):
result = a[0] * b[0]
result_fn = wp.transform_multiply(a[0], b[0])
# let's just work out the transform multiplication manually
# and compare value/gradients with that:
atrans = wp.transform_get_translation(a[0])
arot = wp.transform_get_rotation(a[0])
btrans = wp.transform_get_translation(b[0])
brot = wp.transform_get_rotation(b[0])
trans = wp.quat_rotate(arot, btrans) + atrans
rot = arot * brot
result_manual = transform(trans, rot)
for i in range(7):
outputs[i] = wptype(2) * result[i]
outputs_fn[i] = wptype(2) * result_fn[i]
outputs_manual[i] = wptype(2) * result_manual[i]
kernel = getkernel(check_transform_multiply, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = np.random.randn(7)
s = np.random.randn(7)
q[3:] /= np.linalg.norm(q[3:])
s[3:] /= np.linalg.norm(s[3:])
q = wp.array(q.astype(dtype), dtype=transform, requires_grad=True, device=device)
s = wp.array(s.astype(dtype), dtype=transform, requires_grad=True, device=device)
outputs = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
outputs_fn = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
outputs_manual = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
q,
s,
],
outputs=[outputs, outputs_fn, outputs_manual],
device=device,
)
assert_np_equal(outputs.numpy(), outputs_fn.numpy(), tol=tol)
assert_np_equal(outputs.numpy(), outputs_manual.numpy(), tol=tol)
for i in range(7):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_fn = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
q,
s,
],
outputs=[outputs, outputs_fn, outputs_manual],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_fn, i], outputs=[cmp_fn], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_manual, i], outputs=[cmp_manual], device=device)
tape.backward(loss=cmp)
qgrads = 1.0 * tape.gradients[q].numpy()
sgrads = 1.0 * tape.gradients[s].numpy()
tape.zero()
tape.backward(loss=cmp_fn)
qgrads_fn = 1.0 * tape.gradients[q].numpy()
sgrads_fn = 1.0 * tape.gradients[s].numpy()
tape.zero()
tape.backward(loss=cmp_manual)
qgrads_manual = 1.0 * tape.gradients[q].numpy()
sgrads_manual = 1.0 * tape.gradients[s].numpy()
tape.zero()
assert_np_equal(qgrads, qgrads_fn, tol=tol)
assert_np_equal(sgrads, sgrads_fn, tol=tol)
assert_np_equal(qgrads, qgrads_manual, tol=tol)
assert_np_equal(sgrads, sgrads_manual, tol=tol)
def test_transform_inverse(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)]
transform = wp.types.transformation(dtype=wptype)
def check_transform_inverse(
a: wp.array(dtype=transform),
outputs: wp.array(dtype=wptype),
outputs_shouldbeidentity: wp.array(dtype=wptype),
outputs_manual: wp.array(dtype=wptype),
):
result = wp.transform_inverse(a[0])
idt = result * a[0]
# let's just work out the transform inverse manually
# and compare value/gradients with that:
atrans = wp.transform_get_translation(a[0])
arot = wp.transform_get_rotation(a[0])
rotinv = wp.quat_inverse(arot)
result_manual = transform(-wp.quat_rotate(rotinv, atrans), rotinv)
for i in range(7):
outputs[i] = wptype(2) * result[i]
outputs_shouldbeidentity[i] = wptype(2) * idt[i]
outputs_manual[i] = wptype(2) * result_manual[i]
kernel = getkernel(check_transform_inverse, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = np.random.randn(7)
s = np.random.randn(7)
q[3:] /= np.linalg.norm(q[3:])
s[3:] /= np.linalg.norm(s[3:])
q = wp.array(q.astype(dtype), dtype=transform, requires_grad=True, device=device)
outputs = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
outputs_shouldbeidentity = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
outputs_manual = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
q,
],
outputs=[outputs, outputs_shouldbeidentity, outputs_manual],
device=device,
)
# check inverse:
assert_np_equal(outputs_shouldbeidentity.numpy(), np.array([0, 0, 0, 0, 0, 0, 2]), tol=tol)
# same as manual result:
assert_np_equal(outputs.numpy(), outputs_manual.numpy(), tol=tol)
for i in range(7):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
q,
],
outputs=[outputs, outputs_shouldbeidentity, outputs_manual],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_manual, i], outputs=[cmp_manual], device=device)
tape.backward(loss=cmp)
qgrads = 1.0 * tape.gradients[q].numpy()
tape.zero()
tape.backward(loss=cmp_manual)
qgrads_manual = 1.0 * tape.gradients[q].numpy()
tape.zero()
# check gradients against manual result:
assert_np_equal(qgrads, qgrads_manual, tol=tol)
def test_transform_point_vector(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)]
transform = wp.types.transformation(dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
def check_transform_point_vector(
t: wp.array(dtype=transform),
v: wp.array(dtype=vec3),
outputs_pt: wp.array(dtype=wptype),
outputs_pt_manual: wp.array(dtype=wptype),
outputs_vec: wp.array(dtype=wptype),
outputs_vec_manual: wp.array(dtype=wptype),
):
result_pt = wp.transform_point(t[0], v[0])
result_pt_manual = wp.transform_get_translation(t[0]) + wp.quat_rotate(wp.transform_get_rotation(t[0]), v[0])
result_vec = wp.transform_vector(t[0], v[0])
result_vec_manual = wp.quat_rotate(wp.transform_get_rotation(t[0]), v[0])
for i in range(3):
outputs_pt[i] = wptype(2) * result_pt[i]
outputs_pt_manual[i] = wptype(2) * result_pt_manual[i]
outputs_vec[i] = wptype(2) * result_vec[i]
outputs_vec_manual[i] = wptype(2) * result_vec_manual[i]
kernel = getkernel(check_transform_point_vector, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = np.random.randn(7)
q[3:] /= np.linalg.norm(q[3:])
t = wp.array(q.astype(dtype), dtype=transform, requires_grad=True, device=device)
v = wp.array(np.random.randn(3), dtype=vec3, requires_grad=True, device=device)
outputs_pt = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_pt_manual = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_vec = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_vec_manual = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[t, v],
outputs=[outputs_pt, outputs_pt_manual, outputs_vec, outputs_vec_manual],
device=device,
)
# same as manual results:
assert_np_equal(outputs_pt.numpy(), outputs_pt_manual.numpy(), tol=tol)
assert_np_equal(outputs_vec.numpy(), outputs_vec_manual.numpy(), tol=tol)
for i in range(3):
cmp_pt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_pt_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_vec = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_vec_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[t, v],
outputs=[outputs_pt, outputs_pt_manual, outputs_vec, outputs_vec_manual],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_pt, i], outputs=[cmp_pt], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outputs_pt_manual, i], outputs=[cmp_pt_manual], device=device
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_vec, i], outputs=[cmp_vec], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outputs_vec_manual, i], outputs=[cmp_vec_manual], device=device
)
tape.backward(loss=cmp_pt)
tgrads_pt = 1.0 * tape.gradients[t].numpy()
vgrads_pt = 1.0 * tape.gradients[v].numpy()
tape.zero()
tape.backward(loss=cmp_pt_manual)
tgrads_pt_manual = 1.0 * tape.gradients[t].numpy()
vgrads_pt_manual = 1.0 * tape.gradients[v].numpy()
tape.zero()
tape.backward(loss=cmp_vec)
tgrads_vec = 1.0 * tape.gradients[t].numpy()
vgrads_vec = 1.0 * tape.gradients[v].numpy()
tape.zero()
tape.backward(loss=cmp_vec_manual)
tgrads_vec_manual = 1.0 * tape.gradients[t].numpy()
vgrads_vec_manual = 1.0 * tape.gradients[v].numpy()
tape.zero()
# check gradients against manual result:
assert_np_equal(tgrads_pt, tgrads_pt_manual, tol=tol)
assert_np_equal(vgrads_pt, vgrads_pt_manual, tol=tol)
assert_np_equal(tgrads_vec, tgrads_vec_manual, tol=tol)
assert_np_equal(vgrads_vec, vgrads_vec_manual, tol=tol)
def test_spatial_matrix_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)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
def check_spatial_matrix_constructor(
input: wp.array(dtype=wptype),
out: wp.array(dtype=wptype),
):
# multiply the output by 2 so we've got something to backpropagate:
result0 = spatial_matrix(
input[0],
input[1],
input[2],
input[3],
input[4],
input[5],
input[6],
input[7],
input[8],
input[9],
input[10],
input[11],
input[12],
input[13],
input[14],
input[15],
input[16],
input[17],
input[18],
input[19],
input[20],
input[21],
input[22],
input[23],
input[24],
input[25],
input[26],
input[27],
input[28],
input[29],
input[30],
input[31],
input[32],
input[33],
input[34],
input[35],
)
result1 = spatial_matrix()
idx = 0
for i in range(6):
for j in range(6):
out[idx] = wptype(2) * result0[i, j]
idx = idx + 1
for i in range(6):
for j in range(6):
out[idx] = result1[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_matrix_constructor, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(np.random.randn(6 * 6).astype(dtype), requires_grad=True, device=device)
output = wp.zeros(2 * 6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy()[: 6 * 6], 2 * input.numpy(), tol=tol)
assert_np_equal(output.numpy()[6 * 6 :], np.zeros_like(input.numpy()), tol=tol)
for i in range(len(input)):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
break
def test_spatial_matrix_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)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
def check_spatial_matrix_indexing(
input: wp.array(dtype=spatial_matrix),
out: wp.array(dtype=wptype),
):
inpt = input[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
for j in range(6):
out[idx] = wptype(2) * inpt[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_matrix_indexing, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
outcmps = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device)
assert_np_equal(outcmps.numpy(), 2 * input.numpy().ravel(), tol=tol)
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
for j in range(6):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcmps], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcmps, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros((6, 6), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
def test_spatial_matrix_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)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
def check_spatial_matrix_scalar_mul(
s: wp.array(dtype=wptype),
q: wp.array(dtype=spatial_matrix),
outcmps_l: wp.array(dtype=wptype),
outcmps_r: wp.array(dtype=wptype),
):
lresult = s[0] * q[0]
rresult = q[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
for j in range(6):
outcmps_l[idx] = wptype(2) * lresult[i, j]
outcmps_r[idx] = wptype(2) * rresult[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_matrix_scalar_mul, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
s = wp.array(np.random.randn(1).astype(dtype), requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
outcmps_l = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
outcmps_r = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[s, q],
outputs=[
outcmps_l,
outcmps_r,
],
device=device,
)
assert_np_equal(outcmps_l.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol)
assert_np_equal(outcmps_r.numpy(), 2 * s.numpy()[0] * q.numpy(), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
idx = 0
for i in range(6):
for j in range(6):
# test left/right mul gradients:
for wrt in [outcmps_l, outcmps_r]:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s, q], outputs=[outcmps_l, outcmps_r], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[wrt, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros((6, 6), dtype=dtype)
expectedresult[i, j] = 2 * s.numpy()[0]
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * q.numpy()[0, i, j], tol=tol)
tape.zero()
idx = idx + 1
def test_spatial_matrix_add_sub(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)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
def check_spatial_matrix_add_sub(
q: wp.array(dtype=spatial_matrix),
v: wp.array(dtype=spatial_matrix),
outputs_add: wp.array(dtype=wptype),
outputs_sub: wp.array(dtype=wptype),
):
addresult = q[0] + v[0]
subresult = q[0] - v[0]
idx = 0
for i in range(6):
for j in range(6):
outputs_add[idx] = wptype(2) * addresult[i, j]
outputs_sub[idx] = wptype(2) * subresult[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_matrix_add_sub, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
v = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
outputs_add = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
outputs_sub = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
q,
v,
],
outputs=[outputs_add, outputs_sub],
device=device,
)
assert_np_equal(outputs_add.numpy(), 2 * (q.numpy() + v.numpy()), tol=tol)
assert_np_equal(outputs_sub.numpy(), 2 * (q.numpy() - v.numpy()), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
idx = 0
for i in range(6):
for j in range(6):
# test add gradients:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_add, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros((6, 6), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=tol)
tape.zero()
# test subtraction gradients:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q, v], outputs=[outputs_add, outputs_sub], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_sub, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros((6, 6), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[q].numpy()[0], expectedresult, tol=tol)
assert_np_equal(tape.gradients[v].numpy()[0], -expectedresult, tol=tol)
tape.zero()
idx = idx + 1
def test_spatial_matvec_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
spatial_vector = wp.types.vector(length=6, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_spatial_mat_vec_mul(
v: wp.array(dtype=spatial_vector),
m: wp.array(dtype=spatial_matrix),
outcomponents: wp.array(dtype=wptype),
):
result = m[0] * v[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
outcomponents[idx] = wptype(2) * result[i]
idx = idx + 1
kernel = getkernel(check_spatial_mat_vec_mul, suffix=dtype.__name__)
if register_kernels:
return
v = wp.array(np.random.randn(1, 6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
m = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
outcomponents = wp.zeros(6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m.numpy()[0], v.numpy()[0]), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, i], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(tape.gradients[v].numpy()[0], 2 * m.numpy()[0, i, :], tol=tol)
expectedresult = np.zeros((6, 6), dtype=dtype)
expectedresult[i, :] = 2 * v.numpy()[0]
assert_np_equal(tape.gradients[m].numpy()[0], expectedresult, tol=tol)
tape.zero()
def test_spatial_matmat_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_mat_mul(
v: wp.array(dtype=spatial_matrix),
m: wp.array(dtype=spatial_matrix),
outcomponents: wp.array(dtype=wptype),
):
result = m[0] * v[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
for j in range(6):
outcomponents[idx] = wptype(2) * result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_mat_mul, suffix=dtype.__name__)
if register_kernels:
return
v = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
m = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m.numpy()[0], v.numpy()[0]), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
idx = 0
for i in range(6):
for j in range(6):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[v, m], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros((6, 6), dtype=dtype)
expected[:, j] = 2 * m.numpy()[0, i, :]
assert_np_equal(tape.gradients[v].numpy()[0], expected, tol=10 * tol)
expected = np.zeros((6, 6), dtype=dtype)
expected[i, :] = 2 * v.numpy()[0, :, j]
assert_np_equal(tape.gradients[m].numpy()[0], expected, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_spatial_mat_transpose(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)]
spatial_matrix = wp.types.matrix(shape=(6, 6), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_spatial_mat_transpose(
m: wp.array(dtype=spatial_matrix),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
mat = wptype(2) * wp.transpose(m[0])
idx = 0
for i in range(6):
for j in range(6):
outcomponents[idx] = mat[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_mat_transpose, suffix=dtype.__name__)
if register_kernels:
return
m = wp.array(np.random.randn(1, 6, 6).astype(dtype), dtype=spatial_matrix, requires_grad=True, device=device)
outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy(), 2 * m.numpy()[0].T, tol=tol)
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
for j in range(6):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros((6, 6), dtype=dtype)
expectedresult[j, i] = 2
assert_np_equal(tape.gradients[m].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
def test_spatial_outer_product(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)]
spatial_vector = wp.types.vector(length=6, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_spatial_outer_product(
s: wp.array(dtype=spatial_vector),
v: wp.array(dtype=spatial_vector),
outcomponents: wp.array(dtype=wptype),
):
mresult = wptype(2) * wp.outer(s[0], v[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
for j in range(6):
outcomponents[idx] = mresult[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_outer_product, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(1, 6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
v = wp.array(np.random.randn(1, 6).astype(dtype), dtype=spatial_vector, requires_grad=True, device=device)
outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s, v], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy(), 2 * s.numpy()[0, :, None] * v.numpy()[0, None, :], tol=tol)
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
for j in range(6):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s,
v,
],
outputs=[outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
# this component's gonna be s_i * v_j, so its s gradient is gonna be nozero
# at the ith component and its v gradient will be nonzero at the jth component:
expectedresult = np.zeros((6), dtype=dtype)
expectedresult[i] = 2 * v.numpy()[0, j]
assert_np_equal(tape.gradients[s].numpy()[0], expectedresult, tol=10 * tol)
expectedresult = np.zeros((6), dtype=dtype)
expectedresult[j] = 2 * s.numpy()[0, i]
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_spatial_adjoint(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)]
mat3 = wp.types.matrix(shape=(3, 3), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_spatial_adjoint(
R: wp.array(dtype=mat3),
S: wp.array(dtype=mat3),
outcomponents: wp.array(dtype=wptype),
):
mresult = wptype(2) * wp.spatial_adjoint(R[0], S[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(6):
for j in range(6):
outcomponents[idx] = mresult[i, j]
idx = idx + 1
kernel = getkernel(check_spatial_adjoint, suffix=dtype.__name__)
if register_kernels:
return
R = wp.array(np.random.randn(1, 3, 3).astype(dtype), dtype=mat3, requires_grad=True, device=device)
S = wp.array(np.random.randn(1, 3, 3).astype(dtype), dtype=mat3, requires_grad=True, device=device)
outcomponents = wp.zeros(6 * 6, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[R, S], outputs=[outcomponents], device=device)
result = outcomponents.numpy().reshape(6, 6)
expected = np.zeros_like(result)
expected[:3, :3] = R.numpy()
expected[3:, 3:] = R.numpy()
expected[3:, :3] = S.numpy()
assert_np_equal(result, 2 * expected, tol=tol)
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(6):
for j in range(6):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
R,
S,
],
outputs=[outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
# this component's gonna be s_i * v_j, so its s gradient is gonna be nozero
# at the ith component and its v gradient will be nonzero at the jth component:
expectedresult = np.zeros((3, 3), dtype=dtype)
if (i // 3 == 0 and j // 3 == 0) or (i // 3 == 1 and j // 3 == 1):
expectedresult[i % 3, j % 3] = 2
assert_np_equal(tape.gradients[R].numpy()[0], expectedresult, tol=10 * tol)
expectedresult = np.zeros((3, 3), dtype=dtype)
if i // 3 == 1 and j // 3 == 0:
expectedresult[i % 3, j % 3] = 2
assert_np_equal(tape.gradients[S].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_transform_identity(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def transform_identity_test(output: wp.array(dtype=wptype)):
t = wp.transform_identity(dtype=wptype)
for i in range(7):
output[i] = t[i]
def transform_identity_test_default(output: wp.array(dtype=wp.float32)):
t = wp.transform_identity()
for i in range(7):
output[i] = t[i]
quat_identity_kernel = getkernel(transform_identity_test, suffix=dtype.__name__)
quat_identity_default_kernel = getkernel(transform_identity_test_default, suffix=np.float32.__name__)
if register_kernels:
return
output = wp.zeros(7, dtype=wptype, device=device)
wp.launch(quat_identity_kernel, dim=1, inputs=[], outputs=[output], device=device)
expected = np.zeros_like(output.numpy())
expected[-1] = 1
assert_np_equal(output.numpy(), expected)
# let's just test that it defaults to float32:
output = wp.zeros(7, dtype=wp.float32, device=device)
wp.launch(quat_identity_default_kernel, dim=1, inputs=[], outputs=[output], device=device)
expected = np.zeros_like(output.numpy())
expected[-1] = 1
assert_np_equal(output.numpy(), expected)
def test_transform_anon_type_instance(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def transform_create_test(input: wp.array(dtype=wptype), output: wp.array(dtype=wptype)):
t = wp.transformation(
wp.vector(input[0], input[1], input[2]), wp.quaternion(input[3], input[4], input[5], input[6])
)
for i in range(7):
output[i] = wptype(2) * t[i]
transform_create_kernel = getkernel(transform_create_test, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(np.random.randn(7).astype(dtype), requires_grad=True, device=device)
output = wp.zeros(7, dtype=wptype, requires_grad=True, device=device)
wp.launch(transform_create_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy())
for i in range(len(input)):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(transform_create_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
def register(parent):
devices = get_test_devices()
class TestSpatial(parent):
pass
for dtype in np_float_types:
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_vector_constructors_{dtype.__name__}",
test_spatial_vector_constructors,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_vector_indexing_{dtype.__name__}",
test_spatial_vector_indexing,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_vector_scalar_multiplication_{dtype.__name__}",
test_spatial_vector_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_vector_add_sub_{dtype.__name__}",
test_spatial_vector_add_sub,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial, f"test_spatial_dot_{dtype.__name__}", test_spatial_dot, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestSpatial, f"test_spatial_cross_{dtype.__name__}", test_spatial_cross, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_top_bottom_{dtype.__name__}",
test_spatial_top_bottom,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_constructors_{dtype.__name__}",
test_transform_constructors,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_anon_type_instance_{dtype.__name__}",
test_transform_anon_type_instance,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_identity_{dtype.__name__}",
test_transform_identity,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_indexing_{dtype.__name__}",
test_transform_indexing,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_get_trans_rot_{dtype.__name__}",
test_transform_get_trans_rot,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_multiply_{dtype.__name__}",
test_transform_multiply,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_inverse_{dtype.__name__}",
test_transform_inverse,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_point_vector_{dtype.__name__}",
test_transform_point_vector,
devices=devices,
dtype=dtype,
)
# are these two valid? They don't seem to be doing things you'd want to do,
# maybe they should be removed
add_function_test_register_kernel(
TestSpatial,
f"test_transform_scalar_multiplication_{dtype.__name__}",
test_transform_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_transform_add_sub_{dtype.__name__}",
test_transform_add_sub,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_matrix_constructors_{dtype.__name__}",
test_spatial_matrix_constructors,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_matrix_indexing_{dtype.__name__}",
test_spatial_matrix_indexing,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_matrix_scalar_multiplication_{dtype.__name__}",
test_spatial_matrix_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_matrix_add_sub_{dtype.__name__}",
test_spatial_matrix_add_sub,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_matvec_multiplication_{dtype.__name__}",
test_spatial_matvec_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_matmat_multiplication_{dtype.__name__}",
test_spatial_matmat_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial,
f"test_spatial_outer_product_{dtype.__name__}",
test_spatial_outer_product,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestSpatial, f"test_spatial_adjoint_{dtype.__name__}", test_spatial_adjoint, devices=devices, dtype=dtype
)
# \TODO: test spatial_mass and spatial_jacobian
return TestSpatial
if __name__ == "__main__":
wp.build.clear_kernel_cache()
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_spatial.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()
# triangulate a list of polygon face indices
def triangulate(face_counts, face_indices):
num_tris = np.sum(np.subtract(face_counts, 2))
num_tri_vtx = num_tris * 3
tri_indices = np.zeros(num_tri_vtx, dtype=int)
ctr = 0
wedgeIdx = 0
for nb in face_counts:
for i in range(nb - 2):
tri_indices[ctr] = face_indices[wedgeIdx]
tri_indices[ctr + 1] = face_indices[wedgeIdx + i + 1]
tri_indices[ctr + 2] = face_indices[wedgeIdx + i + 2]
ctr += 3
wedgeIdx += nb
return tri_indices
@wp.kernel
def mesh_query_ray_loss(
mesh: wp.uint64,
query_points: wp.array(dtype=wp.vec3),
query_dirs: wp.array(dtype=wp.vec3),
intersection_points: wp.array(dtype=wp.vec3),
loss: wp.array(dtype=float),
):
tid = wp.tid()
p = query_points[tid]
D = query_dirs[tid]
max_t = 10012.0
t = float(0.0)
bary_u = float(0.0)
bary_v = float(0.0)
sign = float(0.0)
normal = wp.vec3()
face_index = int(0)
q = wp.vec3()
if wp.mesh_query_ray(mesh, p, D, max_t, t, bary_u, bary_v, sign, normal, face_index):
q = wp.mesh_eval_position(mesh, face_index, bary_u, bary_v)
intersection_points[tid] = q
l = q[0]
loss[tid] = l
def test_mesh_query_ray_grad(test, device):
from pxr import Usd, UsdGeom, Gf, Sdf
# test tri
# print("Testing Single Triangle")
# mesh_points = wp.array(np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]), dtype=wp.vec3, device=device)
# mesh_indices = wp.array(np.array([0,1,2]), dtype=int, device=device)
mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/torus.usda")))
mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/World/Torus"))
mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get()
mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get()
tri_indices = triangulate(mesh_counts, mesh_indices)
mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device)
mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device)
p = wp.vec3(50.0, 50.0, 0.0)
D = wp.vec3(0.0, -1.0, 0.0)
# create mesh
mesh = wp.Mesh(points=mesh_points, velocities=None, indices=mesh_indices)
tape = wp.Tape()
# analytic gradients
with tape:
query_points = wp.array(p, dtype=wp.vec3, device=device, requires_grad=True)
query_dirs = wp.array(D, dtype=wp.vec3, device=device, requires_grad=True)
intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device)
loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True)
wp.launch(
kernel=mesh_query_ray_loss,
dim=1,
inputs=[mesh.id, query_points, query_dirs, intersection_points, loss],
device=device,
)
tape.backward(loss=loss)
q = intersection_points.numpy().flatten()
analytic_p = tape.gradients[query_points].numpy().flatten()
analytic_D = tape.gradients[query_dirs].numpy().flatten()
# numeric gradients
# ray origin
eps = 1.0e-3
loss_values_p = []
numeric_p = np.zeros(3)
offset_query_points = [
wp.vec3(p[0] - eps, p[1], p[2]),
wp.vec3(p[0] + eps, p[1], p[2]),
wp.vec3(p[0], p[1] - eps, p[2]),
wp.vec3(p[0], p[1] + eps, p[2]),
wp.vec3(p[0], p[1], p[2] - eps),
wp.vec3(p[0], p[1], p[2] + eps),
]
for i in range(6):
q = offset_query_points[i]
query_points = wp.array(q, dtype=wp.vec3, device=device)
query_dirs = wp.array(D, dtype=wp.vec3, device=device)
intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device)
loss = wp.zeros(n=1, dtype=float, device=device)
wp.launch(
kernel=mesh_query_ray_loss,
dim=1,
inputs=[mesh.id, query_points, query_dirs, intersection_points, loss],
device=device,
)
loss_values_p.append(loss.numpy()[0])
for i in range(3):
l_0 = loss_values_p[i * 2]
l_1 = loss_values_p[i * 2 + 1]
gradient = (l_1 - l_0) / (2.0 * eps)
numeric_p[i] = gradient
# ray dir
loss_values_D = []
numeric_D = np.zeros(3)
offset_query_dirs = [
wp.vec3(D[0] - eps, D[1], D[2]),
wp.vec3(D[0] + eps, D[1], D[2]),
wp.vec3(D[0], D[1] - eps, D[2]),
wp.vec3(D[0], D[1] + eps, D[2]),
wp.vec3(D[0], D[1], D[2] - eps),
wp.vec3(D[0], D[1], D[2] + eps),
]
for i in range(6):
q = offset_query_dirs[i]
query_points = wp.array(p, dtype=wp.vec3, device=device)
query_dirs = wp.array(q, dtype=wp.vec3, device=device)
intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device)
loss = wp.zeros(n=1, dtype=float, device=device)
wp.launch(
kernel=mesh_query_ray_loss,
dim=1,
inputs=[mesh.id, query_points, query_dirs, intersection_points, loss],
device=device,
)
loss_values_D.append(loss.numpy()[0])
for i in range(3):
l_0 = loss_values_D[i * 2]
l_1 = loss_values_D[i * 2 + 1]
gradient = (l_1 - l_0) / (2.0 * eps)
numeric_D[i] = gradient
error_p = ((analytic_p - numeric_p) * (analytic_p - numeric_p)).sum(axis=0)
error_D = ((analytic_D - numeric_D) * (analytic_D - numeric_D)).sum(axis=0)
tolerance = 1.0e-3
test.assertTrue(error_p < tolerance, f"error is {error_p} which is >= {tolerance}")
test.assertTrue(error_D < tolerance, f"error is {error_D} which is >= {tolerance}")
@wp.kernel
def raycast_kernel(
mesh: wp.uint64,
ray_starts: wp.array(dtype=wp.vec3),
ray_directions: wp.array(dtype=wp.vec3),
ray_hits: wp.array(dtype=wp.vec3),
count: wp.array(dtype=int),
):
t = float(0.0) # hit distance along ray
u = float(0.0) # hit face barycentric u
v = float(0.0) # hit face barycentric v
sign = float(0.0) # hit face sign
n = wp.vec3() # hit face normal
f = int(0) # hit face index
max_dist = 1e6 # max raycast disance
# ray cast against the mesh
tid = wp.tid()
if wp.mesh_query_ray(mesh, ray_starts[tid], ray_directions[tid], max_dist, t, u, v, sign, n, f):
wp.atomic_add(count, 0, 1)
# tests rays against a quad of two connected triangles
# with rays exactly falling on the edge, tests that
# there are no leaks
def test_mesh_query_ray_edge(test, device):
# Create raycast starts and directions
xx, yy = np.meshgrid(np.arange(0.1, 0.4, 0.01), np.arange(0.1, 0.4, 0.01))
xx = xx.flatten().reshape(-1, 1)
yy = yy.flatten().reshape(-1, 1)
zz = np.ones_like(xx)
ray_starts = np.concatenate((xx, yy, zz), axis=1)
ray_dirs = np.zeros_like(ray_starts)
ray_dirs[:, 2] = -1.0
# Create simple square mesh
vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.5, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0]], dtype=np.float32)
triangles = np.array([[1, 0, 2], [1, 2, 3]], dtype=np.int32)
mesh = wp.Mesh(
points=wp.array(vertices, dtype=wp.vec3, device=device),
indices=wp.array(triangles.flatten(), dtype=int, device=device),
)
counts = wp.zeros(1, dtype=int, device=device)
n = len(ray_starts)
ray_starts = wp.array(ray_starts, shape=(n,), dtype=wp.vec3, device=device)
ray_dirs = wp.array(ray_dirs, shape=(n,), dtype=wp.vec3, device=device)
ray_hits = wp.zeros((n,), dtype=wp.vec3, device=device)
wp.launch(kernel=raycast_kernel, dim=n, inputs=[mesh.id, ray_starts, ray_dirs, ray_hits, counts], device=device)
wp.synchronize()
test.assertEqual(counts.numpy()[0], n)
def register(parent):
devices = get_test_devices()
class TestMeshQueryRay(parent):
pass
add_function_test(TestMeshQueryRay, "test_mesh_query_ray_edge", test_mesh_query_ray_edge, devices=devices)
# USD import failures should not count as a test failure
try:
from pxr import Usd, UsdGeom
have_usd = True
except:
have_usd = False
if have_usd:
add_function_test(TestMeshQueryRay, "test_mesh_query_ray_grad", test_mesh_query_ray_grad, devices=devices)
return TestMeshQueryRay
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_mesh_query_ray.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 *
np.random.seed(532)
wp.init()
num_points = 4096
dim_x = 128
dim_y = 128
dim_z = 128
scale = 150.0
cell_radius = 8.0
query_radius = 8.0
num_runs = 4
print_enabled = False
@wp.kernel
def count_neighbors(grid: wp.uint64, radius: float, points: wp.array(dtype=wp.vec3), counts: wp.array(dtype=int)):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
# query point
p = points[i]
count = int(0)
# construct query around point p
for index in wp.hash_grid_query(grid, p, radius):
# compute distance to point
d = wp.length(p - points[index])
if d <= radius:
count += 1
counts[i] = count
@wp.kernel
def count_neighbors_reference(
radius: float, points: wp.array(dtype=wp.vec3), counts: wp.array(dtype=int), num_points: int
):
tid = wp.tid()
i = tid % num_points
j = tid // num_points
# query point
p = points[i]
q = points[j]
# compute distance to point
d = wp.length(p - q)
if d <= radius:
wp.atomic_add(counts, i, 1)
def test_hashgrid_query(test, device):
grid = wp.HashGrid(dim_x, dim_y, dim_z, device)
for i in range(num_runs):
if print_enabled:
print(f"Run: {i+1}")
print("---------")
np.random.seed(532)
points = np.random.rand(num_points, 3) * scale - np.array((scale, scale, scale)) * 0.5
def particle_grid(dim_x, dim_y, dim_z, lower, radius, jitter):
points = np.meshgrid(
np.linspace(0, dim_x, dim_x), np.linspace(0, dim_y, dim_y), np.linspace(0, dim_z, dim_z)
)
points_t = np.array((points[0], points[1], points[2])).T * radius * 2.0 + np.array(lower)
points_t = points_t + np.random.rand(*points_t.shape) * radius * jitter
return points_t.reshape((-1, 3))
points = particle_grid(16, 32, 16, (0.0, 0.3, 0.0), cell_radius * 0.25, 0.1)
points_arr = wp.array(points, dtype=wp.vec3, device=device)
counts_arr = wp.zeros(len(points), dtype=int, device=device)
counts_arr_ref = wp.zeros(len(points), dtype=int, device=device)
with wp.ScopedTimer("brute", active=print_enabled):
wp.launch(
kernel=count_neighbors_reference,
dim=len(points) * len(points),
inputs=[query_radius, points_arr, counts_arr_ref, len(points)],
device=device,
)
wp.synchronize()
with wp.ScopedTimer("grid build", active=print_enabled):
grid.build(points_arr, cell_radius)
wp.synchronize()
with wp.ScopedTimer("grid query", active=print_enabled):
wp.launch(
kernel=count_neighbors,
dim=len(points),
inputs=[grid.id, query_radius, points_arr, counts_arr],
device=device,
)
wp.synchronize()
counts = counts_arr.numpy()
counts_ref = counts_arr_ref.numpy()
if print_enabled:
print(f"Grid min: {np.min(counts)} max: {np.max(counts)} avg: {np.mean(counts)}")
print(f"Ref min: {np.min(counts_ref)} max: {np.max(counts_ref)} avg: {np.mean(counts_ref)}")
print(f"Passed: {np.array_equal(counts, counts_ref)}")
test.assertTrue(np.array_equal(counts, counts_ref))
def register(parent):
devices = get_test_devices()
class TestHashGrid(parent):
pass
add_function_test(TestHashGrid, "test_hashgrid_query", test_hashgrid_query, devices=devices)
return TestHashGrid
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_hash_grid.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 math
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def test_operators_scalar_float():
a = 1.0
b = 2.0
c = a * b
d = a + b
e = a / b
f = a - b
g = b**8.0
h = 10.0 // 3.0
expect_eq(c, 2.0)
expect_eq(d, 3.0)
expect_eq(e, 0.5)
expect_eq(f, -1.0)
expect_eq(g, 256.0)
expect_eq(h, 3.0)
@wp.kernel
def test_operators_scalar_int():
a = 1
b = 2
c = a * b
d = a + b
e = a / b
f = a - b
# g = b**8 # integer pow not implemented
h = 10 // 3
i = 10 % 3
j = 2 << 3
k = 16 >> 1
expect_eq(c, 2)
expect_eq(d, 3)
expect_eq(e, 0)
expect_eq(f, -1)
# expect_eq(g, 256)
expect_eq(h, 3)
expect_eq(i, 1)
expect_eq(j, 16)
expect_eq(k, 8)
f0 = wp.uint32(1 << 0)
f1 = wp.uint32(1 << 3)
expect_eq(f0 | f1, f0 + f1)
expect_eq(f0 & f1, wp.uint32(0))
l = wp.uint8(0)
for n in range(8):
l |= wp.uint8(1 << n)
expect_eq(l, ~wp.uint8(0))
@wp.kernel
def test_operators_vector_index():
v = wp.vec4(1.0, 2.0, 3.0, 4.0)
expect_eq(v[0], 1.0)
expect_eq(v[1], 2.0)
expect_eq(v[2], 3.0)
expect_eq(v[3], 4.0)
@wp.kernel
def test_operators_matrix_index():
m22 = wp.mat22(1.0, 2.0, 3.0, 4.0)
expect_eq(m22[0, 0], 1.0)
expect_eq(m22[0, 1], 2.0)
expect_eq(m22[1, 0], 3.0)
expect_eq(m22[1, 1], 4.0)
@wp.kernel
def test_operators_vec3():
v = vec3(1.0, 2.0, 3.0)
r0 = v * 3.0
r1 = 3.0 * v
expect_eq(r0, vec3(3.0, 6.0, 9.0))
expect_eq(r1, vec3(3.0, 6.0, 9.0))
col0 = vec3(1.0, 0.0, 0.0)
col1 = vec3(0.0, 2.0, 0.0)
col2 = vec3(0.0, 0.0, 3.0)
m = mat33(col0, col1, col2)
expect_eq(m * vec3(1.0, 0.0, 0.0), col0)
expect_eq(m * vec3(0.0, 1.0, 0.0), col1)
expect_eq(m * vec3(0.0, 0.0, 1.0), col2)
two = vec3(1.0) * 2.0
expect_eq(two, vec3(2.0, 2.0, 2.0))
@wp.kernel
def test_operators_vec4():
v = vec4(1.0, 2.0, 3.0, 4.0)
r0 = v * 3.0
r1 = 3.0 * v
expect_eq(r0, vec4(3.0, 6.0, 9.0, 12.0))
expect_eq(r1, vec4(3.0, 6.0, 9.0, 12.0))
col0 = vec4(1.0, 0.0, 0.0, 0.0)
col1 = vec4(0.0, 2.0, 0.0, 0.0)
col2 = vec4(0.0, 0.0, 3.0, 0.0)
col3 = vec4(0.0, 0.0, 0.0, 4.0)
m = mat44(col0, col1, col2, col3)
expect_eq(m * vec4(1.0, 0.0, 0.0, 0.0), col0)
expect_eq(m * vec4(0.0, 1.0, 0.0, 0.0), col1)
expect_eq(m * vec4(0.0, 0.0, 1.0, 0.0), col2)
expect_eq(m * vec4(0.0, 0.0, 0.0, 1.0), col3)
two = vec4(1.0) * 2.0
expect_eq(two, vec4(2.0, 2.0, 2.0, 2.0))
@wp.kernel
def test_operators_mat22():
m = mat22(1.0, 2.0, 3.0, 4.0)
r = mat22(3.0, 6.0, 9.0, 12.0)
r0 = m * 3.0
r1 = 3.0 * m
expect_eq(r0, r)
expect_eq(r1, r)
expect_eq(r0[0, 0], 3.0)
expect_eq(r0[0, 1], 6.0)
expect_eq(r0[1, 0], 9.0)
expect_eq(r0[1, 1], 12.0)
expect_eq(r0[0], wp.vec2(3.0, 6.0))
expect_eq(r0[1], wp.vec2(9.0, 12.0))
@wp.kernel
def test_operators_mat33():
m = mat33(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)
r = mat33(3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0)
r0 = m * 3.0
r1 = 3.0 * m
expect_eq(r0, r)
expect_eq(r1, r)
expect_eq(r0[0, 0], 3.0)
expect_eq(r0[0, 1], 6.0)
expect_eq(r0[0, 2], 9.0)
expect_eq(r0[1, 0], 12.0)
expect_eq(r0[1, 1], 15.0)
expect_eq(r0[1, 2], 18.0)
expect_eq(r0[2, 0], 21.0)
expect_eq(r0[2, 1], 24.0)
expect_eq(r0[2, 2], 27.0)
expect_eq(r0[0], wp.vec3(3.0, 6.0, 9.0))
expect_eq(r0[1], wp.vec3(12.0, 15.0, 18.0))
expect_eq(r0[2], wp.vec3(21.0, 24.0, 27.0))
@wp.kernel
def test_operators_mat44():
m = mat44(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0)
r = mat44(3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0, 30.0, 33.0, 36.0, 39.0, 42.0, 45.0, 48.0)
r0 = m * 3.0
r1 = 3.0 * m
expect_eq(r0, r)
expect_eq(r1, r)
expect_eq(r0[0, 0], 3.0)
expect_eq(r0[0, 1], 6.0)
expect_eq(r0[0, 2], 9.0)
expect_eq(r0[0, 3], 12.0)
expect_eq(r0[1, 0], 15.0)
expect_eq(r0[1, 1], 18.0)
expect_eq(r0[1, 2], 21.0)
expect_eq(r0[1, 3], 24.0)
expect_eq(r0[2, 0], 27.0)
expect_eq(r0[2, 1], 30.0)
expect_eq(r0[2, 2], 33.0)
expect_eq(r0[2, 3], 36.0)
expect_eq(r0[3, 0], 39.0)
expect_eq(r0[3, 1], 42.0)
expect_eq(r0[3, 2], 45.0)
expect_eq(r0[3, 3], 48.0)
expect_eq(r0[0], wp.vec4(3.0, 6.0, 9.0, 12.0))
expect_eq(r0[1], wp.vec4(15.0, 18.0, 21.0, 24.0))
expect_eq(r0[2], wp.vec4(27.0, 30.0, 33.0, 36.0))
expect_eq(r0[3], wp.vec4(39.0, 42.0, 45.0, 48.0))
def register(parent):
devices = get_test_devices()
class TestOperators(parent):
pass
add_kernel_test(TestOperators, test_operators_scalar_float, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_scalar_int, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_matrix_index, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_vector_index, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_vec3, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_vec4, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_mat22, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_mat33, dim=1, devices=devices)
add_kernel_test(TestOperators, test_operators_mat44, dim=1, devices=devices)
return TestOperators
if __name__ == "__main__":
wp.force_load()
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_operators.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.kernel
def mul_constant(x: wp.array(dtype=float), y: wp.array(dtype=float)):
tid = wp.tid()
y[tid] = x[tid] * 2.0
@wp.kernel
def mul_variable(x: wp.array(dtype=float), y: wp.array(dtype=float), z: wp.array(dtype=float)):
tid = wp.tid()
z[tid] = x[tid] * y[tid]
@wp.kernel
def dot_product(x: wp.array(dtype=float), y: wp.array(dtype=float), z: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(z, 0, x[tid] * y[tid])
def test_tape_mul_constant(test, device):
dim = 8
iters = 16
tape = wp.Tape()
# record onto tape
with tape:
# input data
x0 = wp.array(np.zeros(dim), dtype=wp.float32, device=device, requires_grad=True)
x = x0
for i in range(iters):
y = wp.empty_like(x, requires_grad=True)
wp.launch(kernel=mul_constant, dim=dim, inputs=[x], outputs=[y], device=device)
x = y
# loss = wp.sum(x)
x.grad = wp.array(np.ones(dim), device=device, dtype=wp.float32)
# run backward
tape.backward()
# grad = 2.0^iters
assert_np_equal(tape.gradients[x0].numpy(), np.ones(dim) * (2**iters))
def test_tape_mul_variable(test, device):
dim = 8
tape = wp.Tape()
# record onto tape
with tape:
# input data
x = wp.array(np.ones(dim) * 16.0, dtype=wp.float32, device=device, requires_grad=True)
y = wp.array(np.ones(dim) * 32.0, dtype=wp.float32, device=device, requires_grad=True)
z = wp.zeros_like(x)
wp.launch(kernel=mul_variable, dim=dim, inputs=[x, y], outputs=[z], device=device)
# loss = wp.sum(x)
z.grad = wp.array(np.ones(dim), device=device, dtype=wp.float32)
# run backward
tape.backward()
# grad_x=y, grad_y=x
assert_np_equal(tape.gradients[x].numpy(), y.numpy())
assert_np_equal(tape.gradients[y].numpy(), x.numpy())
# run backward again with different incoming gradient
# should accumulate the same gradients again onto output
# so gradients = 2.0*prev
tape.backward()
assert_np_equal(tape.gradients[x].numpy(), y.numpy() * 2.0)
assert_np_equal(tape.gradients[y].numpy(), x.numpy() * 2.0)
def test_tape_dot_product(test, device):
dim = 8
tape = wp.Tape()
# record onto tape
with tape:
# input data
x = wp.array(np.ones(dim) * 16.0, dtype=wp.float32, device=device, requires_grad=True)
y = wp.array(np.ones(dim) * 32.0, dtype=wp.float32, device=device, requires_grad=True)
z = wp.zeros(n=1, dtype=wp.float32, device=device, requires_grad=True)
wp.launch(kernel=dot_product, dim=dim, inputs=[x, y], outputs=[z], device=device)
# scalar loss
tape.backward(loss=z)
# grad_x=y, grad_y=x
assert_np_equal(tape.gradients[x].numpy(), y.numpy())
assert_np_equal(tape.gradients[y].numpy(), x.numpy())
def register(parent):
devices = get_test_devices()
class TestTape(parent):
pass
add_function_test(TestTape, "test_tape_mul_constant", test_tape_mul_constant, devices=devices)
add_function_test(TestTape, "test_tape_mul_variable", test_tape_mul_variable, devices=devices)
add_function_test(TestTape, "test_tape_dot_product", test_tape_dot_product, devices=devices)
return TestTape
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_tape.py |
warp-main | warp/tests/__init__.py |
|
import numpy as np
import warp as wp
from warp.utils import runlength_encode
from warp.tests.test_base import *
wp.init()
def test_runlength_encode_int(test, device):
n = 1000
values_np = np.sort(np.random.randint(-10, 10, n, dtype=int))
unique_values_np, unique_counts_np = np.unique(values_np, return_counts=True)
values = wp.array(values_np, device=device, dtype=int)
unique_values = wp.empty_like(values)
unique_counts = wp.empty_like(values)
run_count = runlength_encode(values, unique_values, unique_counts)
assert run_count == len(unique_values_np)
assert (unique_values.numpy()[:run_count] == unique_values_np[:run_count]).all()
assert (unique_counts.numpy()[:run_count] == unique_counts_np[:run_count]).all()
def register(parent):
devices = get_test_devices()
class TestRunlengthEncode(parent):
pass
add_function_test(TestRunlengthEncode, "test_runlength_encode_int", test_runlength_encode_int, devices=devices)
return TestRunlengthEncode
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_runlength_encode.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.struct
class Model:
dt: float
gravity: wp.vec3
m: wp.array(dtype=float)
@wp.struct
class State:
x: wp.array(dtype=wp.vec3)
v: wp.array(dtype=wp.vec3)
@wp.kernel
def kernel_step(state_in: State, state_out: State, model: Model):
i = wp.tid()
state_out.v[i] = state_in.v[i] + model.gravity / model.m[i] * model.dt
state_out.x[i] = state_in.x[i] + state_out.v[i] * model.dt
@wp.kernel
def kernel_step_with_copy(state_in: State, state_out: State, model: Model):
i = wp.tid()
model_rescaled = Model(1.0, model.gravity / model.m[i] * model.dt, model.m)
state_out_copy = State(state_out.x, state_out.v)
state_out_copy.v[i] = state_in.v[i] + model_rescaled.gravity
state_out_copy.x[i] = state_in.x[i] + state_out_copy.v[i] * model.dt
def test_step(test, device):
dim = 5
dt = 0.01
gravity = np.array([0, 0, -9.81])
m = np.ones(dim)
m_model = wp.array(m, dtype=float, device=device)
model = Model()
model.m = m_model
model.dt = dt
model.gravity = wp.vec3(0, 0, -9.81)
np.random.seed(0)
x = np.random.normal(size=(dim, 3))
v = np.random.normal(size=(dim, 3))
x_expected = x + (v + gravity / m[:, None] * dt) * dt
x_in = wp.array(x, dtype=wp.vec3, device=device)
v_in = wp.array(v, dtype=wp.vec3, device=device)
state_in = State()
state_in.x = x_in
state_in.v = v_in
state_out = State()
state_out.x = wp.empty_like(x_in)
state_out.v = wp.empty_like(v_in)
for step_kernel in [kernel_step, kernel_step_with_copy]:
with CheckOutput(test):
wp.launch(step_kernel, dim=dim, inputs=[state_in, state_out, model], device=device)
assert_np_equal(state_out.x.numpy(), x_expected, tol=1e-6)
@wp.kernel
def kernel_loss(x: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float)):
i = wp.tid()
wp.atomic_add(loss, 0, x[i][0] * x[i][0] + x[i][1] * x[i][1] + x[i][2] * x[i][2])
def test_step_grad(test, device):
dim = 5
dt = 0.01
gravity = np.array([0, 0, -9.81])
np.random.seed(0)
m = np.random.rand(dim) + 0.1
m_model = wp.array(m, dtype=float, device=device, requires_grad=True)
model = Model()
model.m = m_model
model.dt = dt
model.gravity = wp.vec3(0, 0, -9.81)
x = np.random.normal(size=(dim, 3))
v = np.random.normal(size=(dim, 3))
x_in = wp.array(x, dtype=wp.vec3, device=device, requires_grad=True)
v_in = wp.array(v, dtype=wp.vec3, device=device, requires_grad=True)
state_in = State()
state_in.x = x_in
state_in.v = v_in
state_out = State()
state_out.x = wp.empty_like(x_in, requires_grad=True)
state_out.v = wp.empty_like(v_in, requires_grad=True)
loss = wp.empty(1, dtype=float, device=device, requires_grad=True)
for step_kernel in [kernel_step, kernel_step_with_copy]:
tape = wp.Tape()
with tape:
wp.launch(step_kernel, dim=dim, inputs=[state_in, state_out, model], device=device)
wp.launch(kernel_loss, dim=dim, inputs=[state_out.x, loss], device=device)
tape.backward(loss)
dl_dx = 2 * state_out.x.numpy()
dl_dv = dl_dx * dt
dv_dm = -gravity * dt / m[:, None] ** 2
dl_dm = (dl_dv * dv_dm).sum(-1)
assert_np_equal(state_out.x.grad.numpy(), dl_dx, tol=1e-6)
assert_np_equal(state_in.x.grad.numpy(), dl_dx, tol=1e-6)
assert_np_equal(state_out.v.grad.numpy(), dl_dv, tol=1e-6)
assert_np_equal(state_in.v.grad.numpy(), dl_dv, tol=1e-6)
assert_np_equal(model.m.grad.numpy(), dl_dm, tol=1e-6)
tape.zero()
assert state_out.x.grad.numpy().sum() == 0.0
assert state_in.x.grad.numpy().sum() == 0.0
assert state_out.v.grad.numpy().sum() == 0.0
assert state_in.v.grad.numpy().sum() == 0.0
assert model.m.grad.numpy().sum() == 0.0
@wp.struct
class Empty:
pass
@wp.kernel
def test_empty(input: Empty):
tid = wp.tid()
@wp.struct
class Uninitialized:
data: wp.array(dtype=int)
@wp.kernel
def test_uninitialized(input: Uninitialized):
tid = wp.tid()
@wp.struct
class Baz:
data: wp.array(dtype=int)
z: wp.vec3
@wp.struct
class Bar:
baz: Baz
y: float
@wp.struct
class Foo:
bar: Bar
x: int
@wp.kernel
def kernel_nested_struct(foo: Foo):
tid = wp.tid()
foo.bar.baz.data[tid] = (
foo.bar.baz.data[tid] + foo.x + int(foo.bar.y * 100.0) + int(wp.length_sq(foo.bar.baz.z)) + tid * 2
)
def test_nested_struct(test, device):
dim = 3
foo = Foo()
foo.bar = Bar()
foo.bar.baz = Baz()
foo.bar.baz.data = wp.zeros(dim, dtype=int, device=device)
foo.bar.baz.z = wp.vec3(1, 2, 3)
foo.bar.y = 1.23
foo.x = 123
wp.launch(kernel_nested_struct, dim=dim, inputs=[foo], device=device)
assert_array_equal(
foo.bar.baz.data,
wp.array((260, 262, 264), dtype=int, device=device),
)
@wp.kernel
def test_struct_instantiate(data: wp.array(dtype=int)):
baz = Baz(data, wp.vec3(0.0, 0.0, 26.0))
bar = Bar(baz, 25.0)
foo = Foo(bar, 24)
wp.expect_eq(foo.x, 24)
wp.expect_eq(foo.bar.y, 25.0)
wp.expect_eq(foo.bar.baz.z[2], 26.0)
wp.expect_eq(foo.bar.baz.data[0], 1)
@wp.struct
class MathThings:
v1: wp.vec3
v2: wp.vec3
v3: wp.vec3
m1: wp.mat22
m2: wp.mat22
m3: wp.mat22
m4: wp.mat22
m5: wp.mat22
m6: wp.mat22
@wp.kernel
def check_math_conversions(s: MathThings):
wp.expect_eq(s.v1, wp.vec3(1.0, 2.0, 3.0))
wp.expect_eq(s.v2, wp.vec3(10.0, 20.0, 30.0))
wp.expect_eq(s.v3, wp.vec3(100.0, 200.0, 300.0))
wp.expect_eq(s.m1, wp.mat22(1.0, 2.0, 3.0, 4.0))
wp.expect_eq(s.m2, wp.mat22(10.0, 20.0, 30.0, 40.0))
wp.expect_eq(s.m3, wp.mat22(100.0, 200.0, 300.0, 400.0))
wp.expect_eq(s.m4, wp.mat22(1.0, 2.0, 3.0, 4.0))
wp.expect_eq(s.m5, wp.mat22(10.0, 20.0, 30.0, 40.0))
wp.expect_eq(s.m6, wp.mat22(100.0, 200.0, 300.0, 400.0))
def test_struct_math_conversions(test, device):
s = MathThings()
# test assigning various containers to vector and matrix attributes
s.v1 = (1, 2, 3)
s.v2 = [10, 20, 30]
s.v3 = np.array([100, 200, 300])
# 2d containers for matrices
s.m1 = ((1, 2), (3, 4))
s.m2 = [[10, 20], [30, 40]]
s.m3 = np.array([[100, 200], [300, 400]])
# 1d containers for matrices
s.m4 = (1, 2, 3, 4)
s.m5 = [10, 20, 30, 40]
s.m6 = np.array([100, 200, 300, 400])
wp.launch(check_math_conversions, dim=1, inputs=[s])
@wp.struct
class TestData:
value: wp.int32
@wp.func
def GetTestData(value: wp.int32):
return TestData(value * 2)
@wp.kernel
def test_return_struct(data: wp.array(dtype=wp.int32)):
tid = wp.tid()
data[tid] = GetTestData(tid).value
wp.expect_eq(data[tid], tid * 2)
@wp.struct
class ReturnStruct:
a: int
b: int
@wp.func
def test_return_func():
a = ReturnStruct(1, 2)
return a
@wp.kernel
def test_return():
t = test_return_func()
wp.expect_eq(t.a, 1)
wp.expect_eq(t.b, 2)
@wp.struct
class DefaultAttribNested:
f: float
@wp.struct
class DefaultAttribStruct:
i: int
d: wp.float64
v: wp.vec3
m: wp.mat22
a: wp.array(dtype=wp.int32)
s: DefaultAttribNested
@wp.func
def check_default_attributes_func(data: DefaultAttribStruct):
wp.expect_eq(data.i, wp.int32(0))
wp.expect_eq(data.d, wp.float64(0))
wp.expect_eq(data.v, wp.vec3(0.0, 0.0, 0.0))
wp.expect_eq(data.m, wp.mat22(0.0, 0.0, 0.0, 0.0))
wp.expect_eq(data.a.shape[0], 0)
wp.expect_eq(data.s.f, wp.float32(0.0))
@wp.kernel
def check_default_attributes_kernel(data: DefaultAttribStruct):
check_default_attributes_func(data)
# check structs default initialized in Python correctly
def test_struct_default_attributes_python(test, device):
s = DefaultAttribStruct()
wp.launch(check_default_attributes_kernel, dim=1, inputs=[s])
# check structs default initialized in kernels correctly
@wp.kernel
def test_struct_default_attributes_kernel():
s = DefaultAttribStruct()
check_default_attributes_func(s)
@wp.struct
class MutableStruct:
param1: int
param2: float
@wp.kernel
def test_struct_mutate_attributes_kernel():
t = MutableStruct()
t.param1 = 1
t.param2 = 1.1
wp.expect_eq(t.param1, 1)
wp.expect_eq(t.param2, 1.1)
@wp.struct
class InnerStruct:
i: int
@wp.struct
class ArrayStruct:
array: wp.array(dtype=InnerStruct)
@wp.kernel
def struct2_reader(test: ArrayStruct):
k = wp.tid()
wp.expect_eq(k + 1, test.array[k].i)
def test_nested_array_struct(test, device):
var1 = InnerStruct()
var1.i = 1
var2 = InnerStruct()
var2.i = 2
struct = ArrayStruct()
struct.array = wp.array([var1, var2], dtype=InnerStruct)
wp.launch(struct2_reader, dim=2, inputs=[struct])
def register(parent):
devices = get_test_devices()
class TestStruct(parent):
pass
add_function_test(TestStruct, "test_step", test_step, devices=devices)
add_function_test(TestStruct, "test_step_grad", test_step_grad, devices=devices)
add_kernel_test(TestStruct, kernel=test_empty, name="test_empty", dim=1, inputs=[Empty()], devices=devices)
add_kernel_test(
TestStruct,
kernel=test_uninitialized,
name="test_uninitialized",
dim=1,
inputs=[Uninitialized()],
devices=devices,
)
add_kernel_test(TestStruct, kernel=test_return, name="test_return", dim=1, inputs=[], devices=devices)
add_function_test(TestStruct, "test_nested_struct", test_nested_struct, devices=devices)
add_function_test(TestStruct, "test_nested_array_struct", test_nested_array_struct, devices=devices)
add_function_test(TestStruct, "test_struct_math_conversions", test_struct_math_conversions, devices=devices)
add_function_test(
TestStruct, "test_struct_default_attributes_python", test_struct_default_attributes_python, devices=devices
)
add_kernel_test(
TestStruct,
name="test_struct_default_attributes",
kernel=test_struct_default_attributes_kernel,
dim=1,
inputs=[],
devices=devices,
)
add_kernel_test(
TestStruct,
name="test_struct_mutate_attributes",
kernel=test_struct_mutate_attributes_kernel,
dim=1,
inputs=[],
devices=devices,
)
for device in devices:
add_kernel_test(
TestStruct,
kernel=test_struct_instantiate,
name="test_struct_instantiate",
dim=1,
inputs=[wp.array([1], dtype=int, device=device)],
devices=[device],
)
add_kernel_test(
TestStruct,
kernel=test_return_struct,
name="test_return_struct",
dim=1,
inputs=[wp.zeros(10, dtype=int, device=device)],
devices=[device],
)
return TestStruct
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_struct.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 add_vec2(dest: wp.array(dtype=wp.vec2), c: wp.vec2):
tid = wp.tid()
dest[tid] = c
@wp.kernel
def transform_vec2(dest: wp.array(dtype=wp.vec2), m: wp.mat22, v: wp.vec2):
tid = wp.tid()
p = wp.mul(m, v)
dest[tid] = p
@wp.kernel
def add_vec3(dest: wp.array(dtype=wp.vec3), c: wp.vec3):
tid = wp.tid()
dest[tid] = c
@wp.kernel
def transform_vec3(dest: wp.array(dtype=wp.vec3), m: wp.mat33, v: wp.vec3):
tid = wp.tid()
p = wp.mul(m, v)
dest[tid] = p
@wp.kernel
def transform_multiply(xforms: wp.array(dtype=wp.transform), a: wp.transform):
tid = wp.tid()
xforms[tid] = wp.transform_multiply(xforms[tid], a)
def test_vec2_arg(test, device, n):
dest = wp.zeros(n=n, dtype=wp.vec2, device=device)
c = np.array((1.0, 2.0))
wp.launch(add_vec2, dim=n, inputs=[dest, c], device=device)
# ensure type can round-trip from Python->GPU->Python
test.assertTrue(np.array_equal(dest.numpy(), np.tile(c, (n, 1))))
def test_vec2_transform(test, device, n):
dest = wp.zeros(n=n, dtype=wp.vec2, device=device)
c = np.array((1.0, 2.0))
m = np.array(((3.0, -1.0), (2.5, 4.0)))
wp.launch(transform_vec2, dim=n, inputs=[dest, m, c], device=device)
test.assertTrue(np.array_equal(dest.numpy(), np.tile(m @ c, (n, 1))))
def test_vec3_arg(test, device, n):
dest = wp.zeros(n=n, dtype=wp.vec3, device=device)
c = np.array((1.0, 2.0, 3.0))
wp.launch(add_vec3, dim=n, inputs=[dest, c], device=device)
test.assertTrue(np.array_equal(dest.numpy(), np.tile(c, (n, 1))))
def test_vec3_transform(test, device, n):
dest = wp.zeros(n=n, dtype=wp.vec3, device=device)
c = np.array((1.0, 2.0, 3.0))
m = np.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0)))
wp.launch(transform_vec3, dim=n, inputs=[dest, m, c], device=device)
test.assertTrue(np.array_equal(dest.numpy(), np.tile(m @ c, (n, 1))))
def test_transform_multiply(test, device, n):
a = wp.transform((0.0, 1.0, 0.0), wp.utils.quat_identity())
x = []
for i in range(10):
x.append(wp.utils.transform_identity())
xforms = wp.array(x, dtype=wp.transform, device=device)
wp.launch(transform_multiply, dim=n, inputs=[xforms, a], device=device)
# construct kernel + test harness for given matrix / vector types
def make_matrix_test(dim, matrix, vector):
def test_matrix_kernel(
a: wp.array(dtype=matrix),
b: wp.array(dtype=matrix),
c: wp.array(dtype=matrix),
x: wp.array(dtype=vector),
result_m: wp.array(dtype=matrix),
result_i: wp.array(dtype=matrix),
result_d: wp.array(dtype=float),
result_x: wp.array(dtype=vector),
):
tid = wp.tid()
m = a[tid] * b[tid] + c[tid] * 2.0
result_m[tid] = m
result_x[tid] = m * x[tid]
result_d[tid] = wp.determinant(m)
invm = wp.inverse(m)
result_i[tid] = m * invm
# 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_matrix_kernel.__module__)
kernel = wp.Kernel(func=test_matrix_kernel, key=f"test_mat{dim}{dim}_kernel", module=module)
def test_matrix(test, device):
rng = np.random.default_rng(42)
n = 1024
a = rng.random(size=(n, dim, dim), dtype=float)
b = rng.random(size=(n, dim, dim), dtype=float)
c = rng.random(size=(n, dim, dim), dtype=float)
x = rng.random(size=(n, dim, 1), dtype=float)
a_array = wp.array(a, dtype=matrix, device=device)
b_array = wp.array(b, dtype=matrix, device=device)
c_array = wp.array(c, dtype=matrix, device=device)
x_array = wp.array(x, dtype=vector, device=device)
result_m_array = wp.zeros_like(a_array)
result_i_array = wp.zeros_like(a_array)
result_x_array = wp.zeros_like(x_array)
result_d_array = wp.zeros(n, dtype=float, device=device)
wp.launch(
kernel,
n,
inputs=[a_array, b_array, c_array, x_array, result_m_array, result_i_array, result_d_array, result_x_array],
device=device,
)
# numpy reference result
result_m = np.matmul(a, b) + c * 2.0
result_x = np.matmul(result_m, x)
result_i = np.array([np.eye(dim)] * n)
result_d = np.linalg.det(result_m)
assert_np_equal(result_m_array.numpy(), result_m, tol=1.0e-5)
assert_np_equal(result_i_array.numpy(), result_i, tol=1.0e-3)
assert_np_equal(result_d_array.numpy(), result_d, tol=1.0e-3)
assert_np_equal(result_x_array.numpy(), result_x, tol=1.0e-5)
return test_matrix
# generate test functions for matrix types
test_mat22 = make_matrix_test(2, wp.mat22, wp.vec2)
test_mat33 = make_matrix_test(3, wp.mat33, wp.vec3)
test_mat44 = make_matrix_test(4, wp.mat44, wp.vec4)
def test_scalar_array(test, device):
scalar_list = (0.0, 1.0, 2.0)
scalar_array = wp.array(scalar_list, device=device)
assert_np_equal(np.array(scalar_list), scalar_array.numpy())
def test_vector_array(test, device):
vector_list = [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (2.0, 2.0, 2.0)]
vector_array = wp.array(vector_list, dtype=wp.vec3, device=device)
assert_np_equal(np.array(vector_list), vector_array.numpy())
@wp.kernel
def test_vector_arg_types(v2: wp.vec2, v3: wp.vec3, v4: wp.vec4, m22: wp.mat22, m33: wp.mat33, m44: wp.mat44):
wp.expect_eq(v2, wp.vec2(1.0, 2.0))
wp.expect_eq(v3, wp.vec3(1.0, 2.0, 3.0))
wp.expect_eq(v4, wp.vec4(1.0, 2.0, 3.0, 4.0))
wp.expect_eq(m22, wp.mat22(1.0, 2.0, 3.0, 4.0))
wp.expect_eq(m33, wp.mat33(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0))
wp.expect_eq(m44, wp.mat44(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0))
@wp.kernel
def test_scalar_arg_types(
i8: wp.int8,
u8: wp.uint8,
i16: wp.int16,
u16: wp.uint16,
i32: wp.int32,
u32: wp.uint32,
i64: wp.int64,
u64: wp.uint64,
f32: wp.float32,
f64: wp.float64,
):
wp.expect_eq(int(i8), -64)
wp.expect_eq(int(u8), 255)
wp.expect_eq(int(i16), -64)
wp.expect_eq(int(u16), 255)
wp.expect_eq(int(i32), -64)
wp.expect_eq(int(u32), 255)
wp.expect_eq(int(i64), -64)
wp.expect_eq(int(u64), 255)
wp.expect_eq(int(f32), 3)
wp.expect_eq(int(f64), 3)
wp.expect_eq(float(f32), 3.14159)
wp.expect_eq(float(f64), 3.14159)
@wp.kernel
def test_scalar_array_types_load(
i8: wp.array(dtype=wp.int8),
u8: wp.array(dtype=wp.uint8),
i16: wp.array(dtype=wp.int16),
u16: wp.array(dtype=wp.uint16),
i32: wp.array(dtype=wp.int32),
u32: wp.array(dtype=wp.uint32),
i64: wp.array(dtype=wp.int64),
u64: wp.array(dtype=wp.uint64),
f32: wp.array(dtype=wp.float32),
f64: wp.array(dtype=wp.float64),
):
tid = wp.tid()
wp.expect_eq(int(i8[tid]), tid)
wp.expect_eq(int(u8[tid]), tid)
wp.expect_eq(int(i16[tid]), tid)
wp.expect_eq(int(u16[tid]), tid)
wp.expect_eq(int(i32[tid]), tid)
wp.expect_eq(int(u32[tid]), tid)
wp.expect_eq(int(i64[tid]), tid)
wp.expect_eq(int(u64[tid]), tid)
wp.expect_eq(float(f32[tid]), float(tid))
wp.expect_eq(float(f64[tid]), float(tid))
@wp.kernel
def test_scalar_array_types_store(
i8: wp.array(dtype=wp.int8),
u8: wp.array(dtype=wp.uint8),
i16: wp.array(dtype=wp.int16),
u16: wp.array(dtype=wp.uint16),
i32: wp.array(dtype=wp.int32),
u32: wp.array(dtype=wp.uint32),
i64: wp.array(dtype=wp.int64),
u64: wp.array(dtype=wp.uint64),
f32: wp.array(dtype=wp.float32),
f64: wp.array(dtype=wp.float64),
):
tid = wp.tid()
i8[tid] = wp.int8(tid)
u8[tid] = wp.uint8(tid)
i16[tid] = wp.int16(tid)
u16[tid] = wp.uint16(tid)
i32[tid] = wp.int32(tid)
u32[tid] = wp.uint32(tid)
i64[tid] = wp.int64(tid)
u64[tid] = wp.uint64(tid)
f32[tid] = wp.float32(tid)
f64[tid] = wp.float64(tid)
# check round-trip
wp.expect_eq(int(i8[tid]), tid)
wp.expect_eq(int(u8[tid]), tid)
wp.expect_eq(int(i16[tid]), tid)
wp.expect_eq(int(u16[tid]), tid)
wp.expect_eq(int(i32[tid]), tid)
wp.expect_eq(int(u32[tid]), tid)
wp.expect_eq(int(i64[tid]), tid)
wp.expect_eq(int(u64[tid]), tid)
wp.expect_eq(float(f32[tid]), float(tid))
wp.expect_eq(float(f64[tid]), float(tid))
@wp.kernel
def test_type_conversions():
# below tests auto-generated by the following snippet:
# scalar_types_all = [*wp.types.scalar_types, int, float]
# for t in scalar_types_all:
# for u in scalar_types_all:
# def prefix(t):
# if t == int or t == float:
# return t.__name__
# else:
# return "wp." + t.__name__
# print(f"wp.expect_eq({prefix(t)}(2.0), {prefix(t)}({prefix(u)}(2.0)))")
wp.expect_eq(wp.int8(2.0), wp.int8(wp.int8(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint8(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.int16(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint16(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.int32(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint32(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.int64(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.uint64(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.float16(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.float32(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(wp.float64(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(int(2.0)))
wp.expect_eq(wp.int8(2.0), wp.int8(float(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int8(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint8(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int16(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint16(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int32(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint32(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.int64(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.uint64(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.float16(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.float32(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(wp.float64(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(int(2.0)))
wp.expect_eq(wp.uint8(2.0), wp.uint8(float(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.int8(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint8(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.int16(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint16(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.int32(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint32(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.int64(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.uint64(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.float16(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.float32(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(wp.float64(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(int(2.0)))
wp.expect_eq(wp.int16(2.0), wp.int16(float(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int8(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint8(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int16(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint16(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int32(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint32(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.int64(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.uint64(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.float16(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.float32(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(wp.float64(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(int(2.0)))
wp.expect_eq(wp.uint16(2.0), wp.uint16(float(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.int8(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint8(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.int16(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint16(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.int32(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint32(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.int64(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.uint64(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.float16(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.float32(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(wp.float64(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(int(2.0)))
wp.expect_eq(wp.int32(2.0), wp.int32(float(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int8(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint8(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int16(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint16(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int32(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint32(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.int64(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.uint64(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.float16(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.float32(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(wp.float64(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(int(2.0)))
wp.expect_eq(wp.uint32(2.0), wp.uint32(float(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.int8(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint8(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.int16(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint16(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.int32(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint32(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.int64(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.uint64(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.float16(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.float32(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(wp.float64(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(int(2.0)))
wp.expect_eq(wp.int64(2.0), wp.int64(float(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int8(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint8(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int16(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint16(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int32(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint32(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.int64(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.uint64(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.float16(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.float32(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(wp.float64(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(int(2.0)))
wp.expect_eq(wp.uint64(2.0), wp.uint64(float(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.int8(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint8(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.int16(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint16(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.int32(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint32(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.int64(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.uint64(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.float16(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.float32(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(wp.float64(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(int(2.0)))
wp.expect_eq(wp.float16(2.0), wp.float16(float(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.int8(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint8(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.int16(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint16(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.int32(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint32(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.int64(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.uint64(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.float16(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.float32(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(wp.float64(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(int(2.0)))
wp.expect_eq(wp.float32(2.0), wp.float32(float(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.int8(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint8(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.int16(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint16(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.int32(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint32(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.int64(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.uint64(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.float16(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.float32(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(wp.float64(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(int(2.0)))
wp.expect_eq(wp.float64(2.0), wp.float64(float(2.0)))
wp.expect_eq(int(2.0), int(wp.int8(2.0)))
wp.expect_eq(int(2.0), int(wp.uint8(2.0)))
wp.expect_eq(int(2.0), int(wp.int16(2.0)))
wp.expect_eq(int(2.0), int(wp.uint16(2.0)))
wp.expect_eq(int(2.0), int(wp.int32(2.0)))
wp.expect_eq(int(2.0), int(wp.uint32(2.0)))
wp.expect_eq(int(2.0), int(wp.int64(2.0)))
wp.expect_eq(int(2.0), int(wp.uint64(2.0)))
wp.expect_eq(int(2.0), int(wp.float16(2.0)))
wp.expect_eq(int(2.0), int(wp.float32(2.0)))
wp.expect_eq(int(2.0), int(wp.float64(2.0)))
wp.expect_eq(int(2.0), int(int(2.0)))
wp.expect_eq(int(2.0), int(float(2.0)))
wp.expect_eq(float(2.0), float(wp.int8(2.0)))
wp.expect_eq(float(2.0), float(wp.uint8(2.0)))
wp.expect_eq(float(2.0), float(wp.int16(2.0)))
wp.expect_eq(float(2.0), float(wp.uint16(2.0)))
wp.expect_eq(float(2.0), float(wp.int32(2.0)))
wp.expect_eq(float(2.0), float(wp.uint32(2.0)))
wp.expect_eq(float(2.0), float(wp.int64(2.0)))
wp.expect_eq(float(2.0), float(wp.uint64(2.0)))
wp.expect_eq(float(2.0), float(wp.float16(2.0)))
wp.expect_eq(float(2.0), float(wp.float32(2.0)))
wp.expect_eq(float(2.0), float(wp.float64(2.0)))
wp.expect_eq(float(2.0), float(int(2.0)))
wp.expect_eq(float(2.0), float(float(2.0)))
def test_scalar_array_types(test, device, load, store):
dim = 64
i8 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int8), device=device)
u8 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint8), device=device)
i16 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int16), device=device)
u16 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint16), device=device)
i32 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int32), device=device)
u32 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint32), device=device)
i64 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.int64), device=device)
u64 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.uint64), device=device)
f32 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.float32), device=device)
f64 = wp.array(np.linspace(0, dim, dim, endpoint=False, dtype=np.float64), device=device)
if load:
wp.launch(
test_scalar_array_types_load,
dim=dim,
inputs=[i8, u8, i16, u16, i32, u32, i64, u64, f32, f64],
device=device,
)
if store:
wp.launch(
test_scalar_array_types_store,
dim=dim,
inputs=[i8, u8, i16, u16, i32, u32, i64, u64, f32, f64],
device=device,
)
@wp.kernel
def test_transform_matrix():
r = wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), 0.5)
t = wp.vec3(0.25, 0.5, -0.75)
s = wp.vec3(2.0, 0.5, 0.75)
m = wp.mat44(t, r, s)
p = wp.vec3(1.0, 2.0, 3.0)
r_0 = wp.quat_rotate(r, wp.cw_mul(s, p)) + t
r_1 = wp.transform_point(m, p)
r_2 = wp.transform_vector(m, p)
wp.expect_near(r_0, r_1, 1.0e-4)
wp.expect_near(r_2, r_0 - t, 1.0e-4)
def register(parent):
devices = get_test_devices()
class TestCTypes(parent):
pass
inputs = [
wp.vec2(1.0, 2.0),
wp.vec3(1.0, 2.0, 3.0),
wp.vec4(1.0, 2.0, 3.0, 4.0),
wp.mat22(1.0, 2.0, 3.0, 4.0),
wp.mat33(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0),
wp.mat44(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0),
]
add_function_test(TestCTypes, "test_mat22", test_mat22, devices=devices)
add_function_test(TestCTypes, "test_mat33", test_mat33, devices=devices)
add_function_test(TestCTypes, "test_mat44", test_mat44, devices=devices)
add_kernel_test(
TestCTypes,
name="test_scalar_arg_types",
kernel=test_scalar_arg_types,
dim=1,
inputs=[-64, 255, -64, 255, -64, 255, -64, 255, 3.14159, 3.14159],
devices=devices,
)
add_kernel_test(
TestCTypes,
name="test_scalar_arg_types_explicit",
kernel=test_scalar_arg_types,
dim=1,
inputs=[
wp.int8(-64),
wp.uint8(255),
wp.int16(-64),
wp.uint16(255),
wp.int32(-64),
wp.uint32(255),
wp.int64(-64),
wp.uint64(255),
wp.float32(3.14159),
wp.float64(3.14159),
],
devices=devices,
)
add_kernel_test(
TestCTypes, name="test_vector_arg_types", kernel=test_vector_arg_types, dim=1, inputs=inputs, devices=devices
)
add_kernel_test(TestCTypes, name="test_type_convesrions", kernel=test_type_conversions, dim=1, devices=devices)
add_function_test(
TestCTypes, "test_scalar_array_load", test_scalar_array_types, devices=devices, load=True, store=False
)
add_function_test(
TestCTypes, "test_scalar_array_store", test_scalar_array_types, devices=devices, load=False, store=True
)
add_function_test(TestCTypes, "test_vec2_arg", test_vec2_arg, devices=devices, n=8)
add_function_test(TestCTypes, "test_vec2_transform", test_vec2_transform, devices=devices, n=8)
add_function_test(TestCTypes, "test_vec3_arg", test_vec3_arg, devices=devices, n=8)
add_function_test(TestCTypes, "test_vec3_transform", test_vec3_transform, devices=devices, n=8)
add_function_test(TestCTypes, "test_transform_multiply", test_transform_multiply, devices=devices, n=8)
add_kernel_test(TestCTypes, name="test_transform_matrix", kernel=test_transform_matrix, dim=1, devices=devices)
add_function_test(TestCTypes, "test_scalar_array", test_scalar_array, devices=devices)
add_function_test(TestCTypes, "test_vector_array", test_vector_array, devices=devices)
return TestCTypes
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_ctypes.py |
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
TRUE_CONSTANT = wp.constant(True)
@wp.func
def identity_function(input_bool: wp.bool, plain_bool: bool):
return input_bool and plain_bool
@wp.kernel
def identity_test(data: wp.array(dtype=wp.bool)):
i = wp.tid()
data[i] = data[i] and True
data[i] = data[i] and wp.bool(True)
data[i] = data[i] and not False
data[i] = data[i] and not wp.bool(False)
data[i] = identity_function(data[i], True)
if data[i]:
data[i] = True
else:
data[i] = False
if not data[i]:
data[i] = False
else:
data[i] = True
if data[i] and True:
data[i] = True
else:
data[i] = False
if data[i] or False:
data[i] = True
else:
data[i] = False
def test_bool_identity_ops(test, device):
dim_x = 10
rand_np = np.random.rand(dim_x) > 0.5
data_array = wp.array(data=rand_np, device=device)
test.assertEqual(data_array.dtype, wp.bool)
wp.launch(identity_test, dim=data_array.shape, inputs=[data_array], device=device)
assert_np_equal(data_array.numpy(), rand_np)
@wp.kernel
def check_compile_constant(result: wp.array(dtype=wp.bool)):
if TRUE_CONSTANT:
result[0] = TRUE_CONSTANT
else:
result[0] = False
def test_bool_constant(test, device):
compile_constant_value = wp.zeros(1, dtype=wp.bool)
wp.launch(check_compile_constant, 1, inputs=[compile_constant_value])
test.assertTrue(compile_constant_value.numpy()[0])
def register(parent):
devices = get_test_devices()
class TestBool(parent):
pass
add_function_test(TestBool, "test_bool_identity_ops", test_bool_identity_ops, devices=devices)
add_function_test(TestBool, "test_bool_constant", test_bool_constant, devices=devices)
return TestBool
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_bool.py |
import unittest
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def load_store_half(f32: wp.array(dtype=wp.float32), f16: wp.array(dtype=wp.float16)):
tid = wp.tid()
# check conversion from f32->f16
a = wp.float16(f32[tid])
b = f16[tid]
wp.expect_eq(a, b)
# check stores
f16[tid] = a
def test_fp16_conversion(test, device):
s = [1.0, 2.0, 3.0, -3.14159]
np_f32 = np.array(s, dtype=np.float32)
np_f16 = np.array(s, dtype=np.float16)
wp_f32 = wp.array(s, dtype=wp.float32, device=device)
wp_f16 = wp.array(s, dtype=wp.float16, device=device)
assert_np_equal(np_f32, wp_f32.numpy())
assert_np_equal(np_f16, wp_f16.numpy())
wp.launch(load_store_half, dim=len(s), inputs=[wp_f32, wp_f16], device=device)
# check that stores worked
assert_np_equal(np_f16, wp_f16.numpy())
@wp.kernel
def value_load_store_half(f16_value: wp.float16, f16_array: wp.array(dtype=wp.float16)):
wp.expect_eq(f16_value, f16_array[0])
# check stores
f16_array[0] = f16_value
def test_fp16_kernel_parameter(test, device):
"""Test the ability to pass in fp16 into kernels as parameters"""
s = [1.0, 2.0, 3.0, -3.14159]
for test_val in s:
np_f16 = np.array([test_val], dtype=np.float16)
wp_f16 = wp.array([test_val], dtype=wp.float16, device=device)
wp.launch(value_load_store_half, (1,), inputs=[wp.float16(test_val), wp_f16], device=device)
# check that stores worked
assert_np_equal(np_f16, wp_f16.numpy())
# Do the same thing but pass in test_val as a Python float to test automatic conversion
wp_f16 = wp.array([test_val], dtype=wp.float16, device=device)
wp.launch(value_load_store_half, (1,), inputs=[test_val, wp_f16], device=device)
assert_np_equal(np_f16, wp_f16.numpy())
@wp.kernel
def mul_half(input: wp.array(dtype=wp.float16), output: wp.array(dtype=wp.float16)):
tid = wp.tid()
# convert to compute type fp32
x = wp.float(input[tid]) * 2.0
# store back as fp16
output[tid] = wp.float16(x)
def test_fp16_grad(test, device):
# checks that gradients are correctly propagated for
# fp16 arrays, even when intermediate calculations
# are performed in e.g.: fp32
s = np.random.rand(15).astype(np.float16)
input = wp.array(s, dtype=wp.float16, device=device, requires_grad=True)
output = wp.zeros_like(input)
tape = wp.Tape()
with tape:
wp.launch(mul_half, dim=len(s), inputs=[input, output], device=device)
ones = wp.array(np.ones(len(output)), dtype=wp.float16, device=device)
tape.backward(grads={output: ones})
assert_np_equal(input.grad.numpy(), np.ones(len(s)) * 2.0)
def register(parent):
class TestFp16(parent):
pass
devices = []
if wp.is_cpu_available():
devices.append("cpu")
for cuda_device in wp.get_cuda_devices():
if cuda_device.arch >= 70:
devices.append(cuda_device)
add_function_test(TestFp16, "test_fp16_conversion", test_fp16_conversion, devices=devices)
add_function_test(TestFp16, "test_fp16_grad", test_fp16_grad, devices=devices)
add_function_test(TestFp16, "test_fp16_kernel_parameter", test_fp16_kernel_parameter, devices=devices)
return TestFp16
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_fp16.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 os
import sys
import unittest
from warp.tests.test_base import *
import warp.tests.test_compile_consts_dummy
import warp as wp
wp.init()
LOCAL_ONE = wp.constant(1)
SQRT3_OVER_3 = wp.constant(0.57735026919)
UNIT_VEC = wp.constant(wp.vec3(SQRT3_OVER_3, SQRT3_OVER_3, SQRT3_OVER_3))
class Foobar:
ONE = wp.constant(1)
TWO = wp.constant(2)
@wp.kernel
def test_constants_int(a: int):
if Foobar.ONE > 0:
a = 123 + Foobar.TWO + warp.tests.test_compile_consts_dummy.MINUS_ONE
else:
a = 456 + LOCAL_ONE
expect_eq(a, 124)
@wp.kernel
def test_constants_float(x: float):
x = SQRT3_OVER_3
for i in range(3):
expect_eq(UNIT_VEC[i], x)
approx_one = wp.dot(UNIT_VEC, UNIT_VEC)
expect_near(approx_one, 1.0, 1e-6)
def test_constant_math(test, device):
# test doing math with Python defined constants in *Python* scope
twopi = wp.pi * 2.0
import math
test.assertEqual(twopi, math.pi * 2.0)
def test_constant_closure_capture(test, device):
def make_closure_kernel(cst):
def closure_kernel_fn(expected: int):
wp.expect_eq(cst, expected)
key = f"test_constant_closure_capture_{cst}"
return wp.Kernel(func=closure_kernel_fn, key=key, module=wp.get_module(closure_kernel_fn.__module__))
one_closure = make_closure_kernel(Foobar.ONE)
two_closure = make_closure_kernel(Foobar.TWO)
wp.launch(one_closure, dim=(1), inputs=[1], device=device)
wp.launch(two_closure, dim=(1), inputs=[2], device=device)
def register(parent):
class TestConstants(parent):
pass
a = 0
x = 0.0
devices = get_test_devices()
add_kernel_test(TestConstants, test_constants_int, dim=1, inputs=[a], devices=devices)
add_kernel_test(TestConstants, test_constants_float, dim=1, inputs=[x], devices=devices)
add_function_test(TestConstants, "test_constant_math", test_constant_math, devices=devices)
add_function_test(TestConstants, "test_constant_closure_capture", test_constant_closure_capture, devices=devices)
return TestConstants
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_compile_consts.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()
# from test_func import sqr
import warp.tests.test_func as test_func
@wp.kernel
def test_import_func():
# test a cross-module function reference is resolved correctly
x = test_func.sqr(2.0)
y = test_func.cube(2.0)
wp.expect_eq(x, 4.0)
wp.expect_eq(y, 8.0)
def register(parent):
devices = get_test_devices()
class TestImport(parent):
pass
add_kernel_test(TestImport, kernel=test_import_func, name="test_import_func", dim=1, devices=devices)
return TestImport
if __name__ == "__main__":
c = register(unittest.TestCase)
# unittest.main(verbosity=2)
wp.force_load()
loader = unittest.defaultTestLoader
testSuite = loader.loadTestsFromTestCase(c)
testSuite.debug()
| warp-main | warp/tests/test_import.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 os
import sys
import numpy as np
import math
import ctypes
import warp as wp
from warp.tests.test_base import *
import unittest
wp.init()
@wp.kernel
def test_conditional_if_else():
a = 0.5
b = 2.0
if a > b:
c = 1.0
else:
c = -1.0
wp.expect_eq(c, -1.0)
@wp.kernel
def test_conditional_if_else_nested():
a = 1.0
b = 2.0
if a > b:
c = 3.0
d = 4.0
if c > d:
e = 1.0
else:
e = -1.0
else:
c = 6.0
d = 7.0
if c > d:
e = 2.0
else:
e = -2.0
wp.expect_eq(e, -2.0)
@wp.kernel
def test_boolean_and():
a = 1.0
b = 2.0
c = 1.0
if a > 0.0 and b > 0.0:
c = -1.0
wp.expect_eq(c, -1.0)
@wp.kernel
def test_boolean_or():
a = 1.0
b = 2.0
c = 1.0
if a > 0.0 and b > 0.0:
c = -1.0
wp.expect_eq(c, -1.0)
@wp.kernel
def test_boolean_compound():
a = 1.0
b = 2.0
c = 3.0
d = 1.0
if a > 0.0 and b > 0.0 or c > a:
d = -1.0
wp.expect_eq(d, -1.0)
@wp.kernel
def test_boolean_literal():
t = True
f = False
r = 1.0
if t == (not f):
r = -1.0
wp.expect_eq(r, -1.0)
@wp.kernel
def test_int_logical_not():
x = 0
if not 123:
x = 123
wp.expect_eq(x, 0)
@wp.kernel
def test_int_conditional_assign_overload():
if 123:
x = 123
if 234:
x = 234
wp.expect_eq(x, 234)
@wp.kernel
def test_bool_param_conditional(foo: bool):
if foo:
x = 123
wp.expect_eq(x, 123)
def register(parent):
devices = get_test_devices()
class TestConditional(parent):
pass
add_kernel_test(TestConditional, kernel=test_conditional_if_else, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_conditional_if_else_nested, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_boolean_and, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_boolean_or, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_boolean_compound, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_boolean_literal, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_int_logical_not, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_int_conditional_assign_overload, dim=1, devices=devices)
add_kernel_test(TestConditional, kernel=test_bool_param_conditional, dim=1, inputs=[True], devices=devices)
return TestConditional
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_conditional.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
import warp.optim
import warp.sim
wp.init()
@wp.kernel
def objective(params: wp.array(dtype=float), score: wp.array(dtype=float)):
tid = wp.tid()
U = params[tid] * params[tid]
wp.atomic_add(score, 0, U)
# This test inspired by https://machinelearningmastery.com/adam-optimization-from-scratch/
def test_adam_solve_float(test, device):
wp.set_device(device)
params_start = np.array([0.1, 0.2], dtype=float)
score = wp.zeros(1, dtype=float, requires_grad=True)
params = wp.array(params_start, dtype=float, requires_grad=True)
tape = wp.Tape()
opt = warp.optim.Adam([params], lr=0.02, betas=(0.8, 0.999))
def gradient_func():
tape.reset()
score.zero_()
with tape:
wp.launch(kernel=objective, dim=len(params), inputs=[params, score])
tape.backward(score)
return [tape.gradients[params]]
niters = 100
opt.reset_internal_state()
for _ in range(niters):
opt.step(gradient_func())
result = params.numpy()
# optimum is at the origin, so the result should be close to it in all N dimensions.
tol = 1e-5
for r in result:
test.assertLessEqual(r, tol)
@wp.kernel
def objective_vec3(params: wp.array(dtype=wp.vec3), score: wp.array(dtype=float)):
tid = wp.tid()
U = wp.dot(params[tid], params[tid])
wp.atomic_add(score, 0, U)
# This test inspired by https://machinelearningmastery.com/adam-optimization-from-scratch/
def test_adam_solve_vec3(test, device):
wp.set_device(device)
params_start = np.array([[0.1, 0.2, -0.1]], dtype=float)
score = wp.zeros(1, dtype=float, requires_grad=True)
params = wp.array(params_start, dtype=wp.vec3, requires_grad=True)
tape = wp.Tape()
opt = warp.optim.Adam([params], lr=0.02, betas=(0.8, 0.999))
def gradient_func():
tape.reset()
score.zero_()
with tape:
wp.launch(kernel=objective_vec3, dim=len(params), inputs=[params, score])
tape.backward(score)
return [tape.gradients[params]]
niters = 100
opt.reset_internal_state()
for _ in range(niters):
opt.step(gradient_func())
result = params.numpy()
tol = 1e-5
# optimum is at the origin, so the result should be close to it in all N dimensions.
for r in result:
for v in r:
test.assertLessEqual(v, tol)
@wp.kernel
def objective_two_inputs_vec3(
params1: wp.array(dtype=wp.vec3), params2: wp.array(dtype=wp.vec3), score: wp.array(dtype=float)
):
tid = wp.tid()
U = wp.dot(params1[tid], params1[tid])
V = wp.dot(params2[tid], params2[tid])
wp.atomic_add(score, 0, U + V)
# This test inspired by https://machinelearningmastery.com/adam-optimization-from-scratch/
def test_adam_solve_two_inputs(test, device):
wp.set_device(device)
params_start1 = np.array([[0.1, 0.2, -0.1]], dtype=float)
params_start2 = np.array([[0.2, 0.1, 0.1]], dtype=float)
score = wp.zeros(1, dtype=float, requires_grad=True)
params1 = wp.array(params_start1, dtype=wp.vec3, requires_grad=True)
params2 = wp.array(params_start2, dtype=wp.vec3, requires_grad=True)
tape = wp.Tape()
opt = warp.optim.Adam([params1, params2], lr=0.02, betas=(0.8, 0.999))
def gradient_func():
tape.reset()
score.zero_()
with tape:
wp.launch(kernel=objective_two_inputs_vec3, dim=len(params1), inputs=[params1, params2, score])
tape.backward(score)
return [tape.gradients[params1], tape.gradients[params2]]
niters = 100
opt.reset_internal_state()
for _ in range(niters):
opt.step(gradient_func())
result = params1.numpy()
tol = 1e-5
# optimum is at the origin, so the result should be close to it in all N dimensions.
for r in result:
for v in r:
test.assertLessEqual(v, tol)
result = params2.numpy()
tol = 1e-5
# optimum is at the origin, so the result should be close to it in all N dimensions.
for r in result:
for v in r:
test.assertLessEqual(v, tol)
def register(parent):
devices = get_test_devices()
class TestArray(parent):
pass
add_function_test(TestArray, "test_adam_solve_float", test_adam_solve_float, devices=devices)
add_function_test(TestArray, "test_adam_solve_vec3", test_adam_solve_vec3, devices=devices)
add_function_test(TestArray, "test_adam_solve_two_inputs", test_adam_solve_two_inputs, devices=devices)
return TestArray
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_adam.py |
import warp as wp
@wp.kernel
def unresolved_func_kernel():
# this should trigger an exception due to unresolved function
x = wp.missing_func(42)
| warp-main | warp/tests/test_unresolved_func.py |
import numpy as np
import unittest
import warp as wp
from warp.tests.test_base import *
np.random.seed(0)
wp.init()
wp.config.mode = "debug"
class GemmTestbedRunner:
def __init__(self, dtype, device):
self.dtype = dtype
self.device = device
def alloc(self, m, n, k, batch_count):
low = -4.5
high = 3.5
if batch_count == 1:
A = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(m, k))), dtype=self.dtype, device=self.device
)
B = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(k, n))), dtype=self.dtype, device=self.device
)
C = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(m, n))), dtype=self.dtype, device=self.device
)
D = wp.array2d(np.zeros((m, n)), dtype=self.dtype, device=self.device)
adj_A = wp.array2d(np.zeros((m, k)), dtype=self.dtype, device=self.device)
adj_B = wp.array2d(np.zeros((k, n)), dtype=self.dtype, device=self.device)
adj_C = wp.array2d(np.zeros((m, n)), dtype=self.dtype, device=self.device)
adj_D = wp.array2d(np.ones((m, n)), dtype=self.dtype, device=self.device)
else:
A = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(batch_count, m, k))),
dtype=self.dtype,
device=self.device,
)
B = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(batch_count, k, n))),
dtype=self.dtype,
device=self.device,
)
C = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(batch_count, m, n))),
dtype=self.dtype,
device=self.device,
)
D = wp.array2d(np.zeros((batch_count, m, n)), dtype=self.dtype, device=self.device)
adj_A = wp.array2d(np.zeros((batch_count, m, k)), dtype=self.dtype, device=self.device)
adj_B = wp.array2d(np.zeros((batch_count, k, n)), dtype=self.dtype, device=self.device)
adj_C = wp.array2d(np.zeros((batch_count, m, n)), dtype=self.dtype, device=self.device)
adj_D = wp.array2d(np.ones((batch_count, m, n)), dtype=self.dtype, device=self.device)
return A, B, C, D, adj_A, adj_B, adj_C, adj_D
def run_and_verify(self, m, n, k, batch_count, alpha, beta):
A, B, C, D, adj_A, adj_B, adj_C, adj_D = self.alloc(m, n, k, batch_count)
if batch_count == 1:
wp.matmul(A, B, C, D, alpha, beta, False, self.device)
D_np = alpha * (A.numpy() @ B.numpy()) + beta * C.numpy()
assert np.array_equal(D_np, D.numpy())
wp.adj_matmul(A, B, C, adj_A, adj_B, adj_C, adj_D, alpha, beta, False, self.device)
adj_A_np = alpha * np.matmul(adj_D.numpy(), B.numpy().transpose())
adj_B_np = alpha * (A.numpy().transpose() @ adj_D.numpy())
adj_C_np = beta * adj_D.numpy()
assert np.array_equal(adj_A_np, adj_A.numpy())
assert np.array_equal(adj_B_np, adj_B.numpy())
assert np.array_equal(adj_C_np, adj_C.numpy())
else:
wp.batched_matmul(A, B, C, D, alpha, beta, False, self.device)
D_np = alpha * np.matmul(A.numpy(), B.numpy()) + beta * C.numpy()
assert np.array_equal(D_np, D.numpy())
wp.adj_batched_matmul(A, B, C, adj_A, adj_B, adj_C, adj_D, alpha, beta, False, self.device)
adj_A_np = alpha * np.matmul(adj_D.numpy(), B.numpy().transpose((0, 2, 1)))
adj_B_np = alpha * np.matmul(A.numpy().transpose((0, 2, 1)), adj_D.numpy())
adj_C_np = beta * adj_D.numpy()
assert np.array_equal(adj_A_np, adj_A.numpy())
assert np.array_equal(adj_B_np, adj_B.numpy())
assert np.array_equal(adj_C_np, adj_C.numpy())
def run(self):
Ms = [64, 128, 512]
Ns = [64, 128, 512]
Ks = [64, 128, 512]
batch_counts = [1, 4]
betas = [0.0, 1.0]
alpha = 1.0
for batch_count in batch_counts:
for m in Ms:
for n in Ns:
for k in Ks:
for beta in betas:
self.run_and_verify(m, n, k, batch_count, alpha, beta)
# NOTE: F16 tests are slow due to the performance of the reference numpy F16 matmuls performed on CPU.
def test_f16(test, device):
GemmTestbedRunner(wp.float16, device).run()
def test_f32(test, device):
GemmTestbedRunner(wp.float32, device).run()
def test_f64(test, device):
GemmTestbedRunner(wp.float64, device).run()
@wp.kernel
def matrix_sum_kernel(arr: wp.array2d(dtype=float), loss: wp.array(dtype=float)):
i, j = wp.tid()
wp.atomic_add(loss, 0, arr[i, j])
def test_tape(test, device):
low = -4.5
high = 3.5
m = 64
n = 128
k = 256
A = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(m, k))), dtype=float, device=device, requires_grad=True
)
B = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(k, n))), dtype=float, device=device, requires_grad=True
)
C = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(m, n))), dtype=float, device=device, requires_grad=True
)
D = wp.array2d(np.zeros((m, n)), dtype=float, device=device, requires_grad=True)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
# test tape
tape = wp.Tape()
with tape:
wp.matmul(A, B, C, D, device=device)
wp.launch(matrix_sum_kernel, dim=(m, n), inputs=[D, loss], device=device)
tape.backward(loss=loss)
A_grad = A.grad.numpy()
# test adjoint
D.grad = wp.array2d(np.ones((m, n)), dtype=float, device=device)
wp.adj_matmul(A, B, C, A.grad, B.grad, C.grad, D.grad, device=device)
assert_np_equal(A_grad, A.grad.numpy())
# test zero
tape.zero()
assert_array_equal(A.grad, wp.zeros_like(A))
def test_operator(test, device):
low = -4.5
high = 3.5
m = 64
n = 128
k = 256
A = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(m, k))), dtype=float, device=device, requires_grad=True
)
B = wp.array2d(
np.ceil(np.random.uniform(low=low, high=high, size=(k, n))), dtype=float, device=device, requires_grad=True
)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
# test tape
tape = wp.Tape()
with tape:
D = A @ B
wp.launch(matrix_sum_kernel, dim=(m, n), inputs=[D, loss], device=device)
tape.backward(loss=loss)
# test adjoint
D.grad = wp.array2d(np.ones((m, n)), dtype=float, device=device)
# deep copy, needed because transpose data is not contiguous
B_transpose = wp.array2d(B.transpose().numpy(), dtype=float, device=device)
adj_A = D.grad @ B_transpose
assert_array_equal(adj_A, A.grad)
# test zero
tape.zero()
assert_array_equal(A.grad, wp.zeros_like(A))
def register(parent):
devices = [d for d in get_test_devices()]
class TestMatmul(parent):
pass
if devices:
# check if CUTLASS is available
from warp.context import runtime
if runtime.core.is_cutlass_enabled():
# add_function_test(TestMatmul, "test_f16", test_f16, devices=devices)
add_function_test(TestMatmul, "test_f32", test_f32, devices=devices)
add_function_test(TestMatmul, "test_f64", test_f64, devices=devices)
add_function_test(TestMatmul, "test_tape", test_tape, devices=devices)
add_function_test(TestMatmul, "test_operator", test_operator, devices=devices)
else:
print("Skipping matmul tests because CUTLASS is not supported in this build")
return TestMatmul
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_matmul.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
import math
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 arange(start: int, step: int, a: wp.array(dtype=int)):
tid = wp.tid()
a[tid] = start + step * tid
def test_multigpu_set_device(test, device):
assert len(wp.get_cuda_devices()) > 1, "At least two CUDA devices are required"
# save default device
saved_device = wp.get_device()
n = 32
wp.set_device("cuda:0")
a0 = wp.empty(n, dtype=int)
wp.launch(arange, dim=a0.size, inputs=[0, 1, a0])
wp.set_device("cuda:1")
a1 = wp.empty(n, dtype=int)
wp.launch(arange, dim=a1.size, inputs=[0, 1, a1])
# restore default device
wp.set_device(saved_device)
assert a0.device == "cuda:0"
assert a1.device == "cuda:1"
expected = np.arange(n, dtype=int)
assert_np_equal(a0.numpy(), expected)
assert_np_equal(a1.numpy(), expected)
def test_multigpu_scoped_device(test, device):
assert len(wp.get_cuda_devices()) > 1, "At least two CUDA devices are required"
n = 32
with wp.ScopedDevice("cuda:0"):
a0 = wp.empty(n, dtype=int)
wp.launch(arange, dim=a0.size, inputs=[0, 1, a0])
with wp.ScopedDevice("cuda:1"):
a1 = wp.empty(n, dtype=int)
wp.launch(arange, dim=a1.size, inputs=[0, 1, a1])
assert a0.device == "cuda:0"
assert a1.device == "cuda:1"
expected = np.arange(n, dtype=int)
assert_np_equal(a0.numpy(), expected)
assert_np_equal(a1.numpy(), expected)
def test_multigpu_nesting(test, device):
assert len(wp.get_cuda_devices()) > 1, "At least two CUDA devices are required"
initial_device = wp.get_device()
initial_cuda_device = wp.get_cuda_device()
with wp.ScopedDevice("cuda:1"):
assert wp.get_device() == "cuda:1"
assert wp.get_cuda_device() == "cuda:1"
with wp.ScopedDevice("cuda:0"):
assert wp.get_device() == "cuda:0"
assert wp.get_cuda_device() == "cuda:0"
with wp.ScopedDevice("cpu"):
assert wp.get_device() == "cpu"
assert wp.get_cuda_device() == "cuda:0"
wp.set_device("cuda:1")
assert wp.get_device() == "cuda:1"
assert wp.get_cuda_device() == "cuda:1"
assert wp.get_device() == "cuda:0"
assert wp.get_cuda_device() == "cuda:0"
assert wp.get_device() == "cuda:1"
assert wp.get_cuda_device() == "cuda:1"
assert wp.get_device() == initial_device
assert wp.get_cuda_device() == initial_cuda_device
def test_multigpu_pingpong(test, device):
assert len(wp.get_cuda_devices()) > 1, "At least two CUDA devices are required"
n = 1024 * 1024
a0 = wp.zeros(n, dtype=float, device="cuda:0")
a1 = wp.zeros(n, dtype=float, device="cuda:1")
iters = 10
for _ in range(iters):
wp.launch(inc, dim=a0.size, inputs=[a0], device=a0.device)
wp.synchronize_device(a0.device)
wp.copy(a1, a0)
wp.launch(inc, dim=a1.size, inputs=[a1], device=a1.device)
wp.synchronize_device(a1.device)
wp.copy(a0, a1)
expected = np.full(n, iters * 2, dtype=np.float32)
assert_np_equal(a0.numpy(), expected)
assert_np_equal(a1.numpy(), expected)
def test_multigpu_pingpong_streams(test, device):
assert len(wp.get_cuda_devices()) > 1, "At least two CUDA devices are required"
n = 1024 * 1024
a0 = wp.zeros(n, dtype=float, device="cuda:0")
a1 = wp.zeros(n, dtype=float, device="cuda:1")
stream0 = wp.get_stream("cuda:0")
stream1 = wp.get_stream("cuda:1")
iters = 10
for _ in range(iters):
wp.launch(inc, dim=a0.size, inputs=[a0], stream=stream0)
stream1.wait_stream(stream0)
wp.copy(a1, a0, stream=stream1)
wp.launch(inc, dim=a1.size, inputs=[a1], stream=stream1)
stream0.wait_stream(stream1)
wp.copy(a0, a1, stream=stream0)
expected = np.full(n, iters * 2, dtype=np.float32)
assert_np_equal(a0.numpy(), expected)
assert_np_equal(a1.numpy(), expected)
def register(parent):
class TestMultigpu(parent):
pass
if wp.get_cuda_device_count() > 1:
add_function_test(TestMultigpu, "test_multigpu_set_device", test_multigpu_set_device)
add_function_test(TestMultigpu, "test_multigpu_scoped_device", test_multigpu_scoped_device)
add_function_test(TestMultigpu, "test_multigpu_nesting", test_multigpu_nesting)
add_function_test(TestMultigpu, "test_multigpu_pingpong", test_multigpu_pingpong)
add_function_test(TestMultigpu, "test_multigpu_pingpong_streams", test_multigpu_pingpong_streams)
return TestMultigpu
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_multigpu.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.
# This file is used to test reloading module references.
import warp as wp
import warp.tests.test_reference as ref
wp.init()
@wp.kernel
def kern(expect: float):
wp.expect_eq(ref.magic(), expect)
def run(expect, device):
wp.launch(kern, dim=1, inputs=[expect], device=device)
| warp-main | warp/tests/test_dependent.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 numpy as np
import unittest
from typing import Any
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.func
def generic_adder(a: Any, b: Any):
return a + b
@wp.kernel
def test_generic_adder():
wp.expect_eq(generic_adder(17, 25), 42)
wp.expect_eq(generic_adder(7.0, 10.0), 17.0)
v1 = wp.vec3(1.0, 2.0, 3.0)
v2 = wp.vec3(10.0, 20.0, 30.0)
wp.expect_eq(generic_adder(v1, v2), wp.vec3(11.0, 22.0, 33.0))
# regular functions for floats
@wp.func
def specialized_func(a: float, b: float):
return a * b
@wp.func
def specialized_func(a: float, b: float, c: float):
return a * b * c
# generic forms
@wp.func
def specialized_func(a: Any, b: Any):
return a + b
@wp.func
def specialized_func(a: Any, b: Any, c: Any):
return a + b + c
# specializations for ints
@wp.func
def specialized_func(a: int, b: int):
return a - b
@wp.func
def specialized_func(a: int, b: int, c: int):
return a - b - c
@wp.kernel
def test_specialized_func():
# subtraction with int args
wp.expect_eq(specialized_func(17, 25), -8)
wp.expect_eq(specialized_func(17, 25, 10), -18)
# multiplication with float args
wp.expect_eq(specialized_func(7.0, 10.0), 70.0)
wp.expect_eq(specialized_func(7.0, 10.0, 2.0), 140.0)
# addition with vector args
v1 = wp.vec3(1.0, 2.0, 3.0)
v2 = wp.vec3(10.0, 20.0, 30.0)
v3 = wp.vec3(100.0, 200.0, 300.0)
wp.expect_eq(specialized_func(v1, v2), wp.vec3(11.0, 22.0, 33.0))
wp.expect_eq(specialized_func(v1, v2, v3), wp.vec3(111.0, 222.0, 333.0))
# generic array kernel, version 1 (Any)
@wp.kernel
def generic_array_kernel_v1(a: Any, b: Any, c: Any):
tid = wp.tid()
sum = a[tid] + b[tid] # test direct access
c[tid] = generic_adder(sum, sum) # test generic function
wp.overload(generic_array_kernel_v1, [wp.array(dtype=int), wp.array(dtype=int), wp.array(dtype=int)])
wp.overload(generic_array_kernel_v1, [wp.array(dtype=float), wp.array(dtype=float), wp.array(dtype=float)])
wp.overload(generic_array_kernel_v1, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3)])
# generic array kernel, version 2 (generic dtype)
@wp.kernel
def generic_array_kernel_v2(a: wp.array(dtype=Any), b: wp.array(dtype=Any), c: wp.array(dtype=Any)):
tid = wp.tid()
sum = a[tid] + b[tid] # test direct access
c[tid] = generic_adder(sum, sum) # test generic function
wp.overload(generic_array_kernel_v2, [wp.array(dtype=int), wp.array(dtype=int), wp.array(dtype=int)])
wp.overload(generic_array_kernel_v2, [wp.array(dtype=float), wp.array(dtype=float), wp.array(dtype=float)])
wp.overload(generic_array_kernel_v2, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3)])
# generic array kernel, version 3 (unspecified dtype)
@wp.kernel
def generic_array_kernel_v3(a: wp.array(), b: wp.array(), c: wp.array()):
tid = wp.tid()
sum = a[tid] + b[tid] # test direct access
c[tid] = generic_adder(sum, sum) # test generic function
wp.overload(generic_array_kernel_v3, [wp.array(dtype=int), wp.array(dtype=int), wp.array(dtype=int)])
wp.overload(generic_array_kernel_v3, [wp.array(dtype=float), wp.array(dtype=float), wp.array(dtype=float)])
wp.overload(generic_array_kernel_v3, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3)])
def test_generic_array_kernel(test, device):
with wp.ScopedDevice(device):
n = 10
ai = wp.array(data=np.ones(n, dtype=np.int32))
ci = wp.empty(10, dtype=int)
af = wp.array(data=np.ones(n, dtype=np.float32))
cf = wp.empty(10, dtype=float)
a3 = wp.array(data=np.ones((n, 3), dtype=np.float32), dtype=wp.vec3)
c3 = wp.empty(n, dtype=wp.vec3)
wp.launch(generic_array_kernel_v1, dim=n, inputs=[af, af, cf])
wp.launch(generic_array_kernel_v1, dim=n, inputs=[ai, ai, ci])
wp.launch(generic_array_kernel_v1, dim=n, inputs=[a3, a3, c3])
assert_np_equal(ci.numpy(), np.full((n,), 4, dtype=np.int32))
assert_np_equal(cf.numpy(), np.full((n,), 4.0, dtype=np.float32))
assert_np_equal(c3.numpy(), np.full((n, 3), 4.0, dtype=np.float32))
wp.launch(generic_array_kernel_v2, dim=n, inputs=[af, af, cf])
wp.launch(generic_array_kernel_v2, dim=n, inputs=[ai, ai, ci])
wp.launch(generic_array_kernel_v2, dim=n, inputs=[a3, a3, c3])
assert_np_equal(ci.numpy(), np.full((n,), 4, dtype=np.int32))
assert_np_equal(cf.numpy(), np.full((n,), 4.0, dtype=np.float32))
assert_np_equal(c3.numpy(), np.full((n, 3), 4.0, dtype=np.float32))
wp.launch(generic_array_kernel_v3, dim=n, inputs=[af, af, cf])
wp.launch(generic_array_kernel_v3, dim=n, inputs=[ai, ai, ci])
wp.launch(generic_array_kernel_v3, dim=n, inputs=[a3, a3, c3])
assert_np_equal(ci.numpy(), np.full((n,), 4, dtype=np.int32))
assert_np_equal(cf.numpy(), np.full((n,), 4.0, dtype=np.float32))
assert_np_equal(c3.numpy(), np.full((n, 3), 4.0, dtype=np.float32))
# kernel that adds any scalar value to an array
@wp.kernel
def generic_accumulator_kernel(a: wp.array(dtype=wp.float64), value: Any):
tid = wp.tid()
a[tid] = a[tid] + wp.float64(value)
# overload named args
wp.overload(generic_accumulator_kernel, {"value": int})
wp.overload(generic_accumulator_kernel, {"value": float})
wp.overload(generic_accumulator_kernel, {"value": wp.float64})
def test_generic_accumulator_kernel(test, device):
with wp.ScopedDevice(device):
n = 10
a = wp.zeros(n, dtype=wp.float64)
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, 25])
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, 17.0])
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, wp.float64(8.0)])
assert_np_equal(a.numpy(), np.full((n,), 50.0, dtype=np.float64))
# generic kernel used to automatically generate overloads from launch args
@wp.kernel
def generic_fill(a: wp.array(dtype=Any), value: Any):
tid = wp.tid()
a[tid] = value
def test_generic_fill(test, device):
with wp.ScopedDevice(device):
n = 10
ai = wp.zeros(n, dtype=int)
af = wp.zeros(n, dtype=float)
a3 = wp.zeros(n, dtype=wp.vec3)
wp.launch(generic_fill, dim=ai.size, inputs=[ai, 42])
wp.launch(generic_fill, dim=af.size, inputs=[af, 17.0])
wp.launch(generic_fill, dim=a3.size, inputs=[a3, wp.vec3(5.0, 5.0, 5.0)])
assert_np_equal(ai.numpy(), np.full((n,), 42, dtype=np.int32))
assert_np_equal(af.numpy(), np.full((n,), 17.0, dtype=np.float32))
assert_np_equal(a3.numpy(), np.full((n, 3), 5.0, dtype=np.float32))
# generic kernel used to create and launch explicit overloads
@wp.kernel
def generic_fill_v2(a: wp.array(dtype=Any), value: Any):
tid = wp.tid()
a[tid] = value
# create explicit overloads to be launched directly
fill_int = wp.overload(generic_fill_v2, [wp.array(dtype=int), int])
fill_float = wp.overload(generic_fill_v2, [wp.array(dtype=float), float])
fill_vec3 = wp.overload(generic_fill_v2, [wp.array(dtype=wp.vec3), wp.vec3])
def test_generic_fill_overloads(test, device):
with wp.ScopedDevice(device):
n = 10
ai = wp.zeros(n, dtype=int)
af = wp.zeros(n, dtype=float)
a3 = wp.zeros(n, dtype=wp.vec3)
wp.launch(fill_int, dim=ai.size, inputs=[ai, 42])
wp.launch(fill_float, dim=af.size, inputs=[af, 17.0])
wp.launch(fill_vec3, dim=a3.size, inputs=[a3, wp.vec3(5.0, 5.0, 5.0)])
assert_np_equal(ai.numpy(), np.full((n,), 42, dtype=np.int32))
assert_np_equal(af.numpy(), np.full((n,), 17.0, dtype=np.float32))
assert_np_equal(a3.numpy(), np.full((n, 3), 5.0, dtype=np.float32))
# custom vector/matrix types
my_vec5 = wp.types.vector(length=5, dtype=wp.float32)
my_mat55 = wp.types.matrix(shape=(5, 5), dtype=wp.float32)
@wp.kernel
def generic_transform(v: Any, m: Any, expected: Any):
result = wp.mul(m, v)
wp.expect_eq(result, expected)
# use overload decorator syntax
@wp.overload
def generic_transform(v: wp.vec2, m: wp.mat22, expected: wp.vec2):
...
@wp.overload
def generic_transform(v: wp.vec3, m: wp.mat33, expected: wp.vec3):
...
@wp.overload
def generic_transform(v: wp.vec4, m: wp.mat44, expected: wp.vec4):
...
@wp.overload
def generic_transform(v: my_vec5, m: my_mat55, expected: my_vec5):
...
def test_generic_transform_kernel(test, device):
with wp.ScopedDevice(device):
v2 = wp.vec2(1, 2)
m22 = wp.mat22(2, 0, 0, 2)
e2 = wp.vec2(2, 4)
v3 = wp.vec3(1, 2, 3)
m33 = wp.mat33(2, 0, 0, 0, 2, 0, 0, 0, 2)
e3 = wp.vec3(2, 4, 6)
v4 = wp.vec4(1, 2, 3, 4)
m44 = wp.mat44(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2)
e4 = wp.vec4(2, 4, 6, 8)
v5 = my_vec5(1, 2, 3, 4, 5)
m55 = my_mat55(2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2)
e5 = my_vec5(2, 4, 6, 8, 10)
wp.launch(generic_transform, dim=1, inputs=[v2, m22, e2])
wp.launch(generic_transform, dim=1, inputs=[v3, m33, e3])
wp.launch(generic_transform, dim=1, inputs=[v4, m44, e4])
wp.launch(generic_transform, dim=1, inputs=[v5, m55, e5])
wp.synchronize()
@wp.kernel
def generic_transform_array(v: wp.array(), m: wp.array(), result: wp.array()):
tid = wp.tid()
result[tid] = wp.mul(m[tid], v[tid])
wp.overload(generic_transform_array, [wp.array(dtype=wp.vec2), wp.array(dtype=wp.mat22), wp.array(dtype=wp.vec2)])
wp.overload(generic_transform_array, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.mat33), wp.array(dtype=wp.vec3)])
wp.overload(generic_transform_array, [wp.array(dtype=wp.vec4), wp.array(dtype=wp.mat44), wp.array(dtype=wp.vec4)])
wp.overload(generic_transform_array, [wp.array(dtype=my_vec5), wp.array(dtype=my_mat55), wp.array(dtype=my_vec5)])
def test_generic_transform_array_kernel(test, device):
with wp.ScopedDevice(device):
n = 10
a2_data = np.tile(np.arange(2, dtype=np.float32), (n, 1))
a3_data = np.tile(np.arange(3, dtype=np.float32), (n, 1))
a4_data = np.tile(np.arange(4, dtype=np.float32), (n, 1))
a5_data = np.tile(np.arange(5, dtype=np.float32), (n, 1))
m22_data = np.tile((np.identity(2, dtype=np.float32) * 2), (n, 1, 1))
m33_data = np.tile((np.identity(3, dtype=np.float32) * 2), (n, 1, 1))
m44_data = np.tile((np.identity(4, dtype=np.float32) * 2), (n, 1, 1))
m55_data = np.tile((np.identity(5, dtype=np.float32) * 2), (n, 1, 1))
a2 = wp.array(data=a2_data, dtype=wp.vec2)
a3 = wp.array(data=a3_data, dtype=wp.vec3)
a4 = wp.array(data=a4_data, dtype=wp.vec4)
a5 = wp.array(data=a5_data, dtype=my_vec5)
m22 = wp.array(data=m22_data, dtype=wp.mat22)
m33 = wp.array(data=m33_data, dtype=wp.mat33)
m44 = wp.array(data=m44_data, dtype=wp.mat44)
m55 = wp.array(data=m55_data, dtype=my_mat55)
b2 = wp.zeros_like(a2)
b3 = wp.zeros_like(a3)
b4 = wp.zeros_like(a4)
b5 = wp.zeros_like(a5)
wp.launch(generic_transform_array, dim=n, inputs=[a2, m22, b2])
wp.launch(generic_transform_array, dim=n, inputs=[a3, m33, b3])
wp.launch(generic_transform_array, dim=n, inputs=[a4, m44, b4])
wp.launch(generic_transform_array, dim=n, inputs=[a5, m55, b5])
assert_np_equal(b2.numpy(), a2_data * 2)
assert_np_equal(b3.numpy(), a3_data * 2)
assert_np_equal(b4.numpy(), a4_data * 2)
assert_np_equal(b5.numpy(), a5_data * 2)
@wp.struct
class Foo:
x: float
y: float
z: float
@wp.struct
class Bar:
x: wp.vec3
y: wp.vec3
z: wp.vec3
@wp.kernel
def test_generic_struct_kernel(s: Any):
# test member access for generic structs
wp.expect_eq(s.x + s.y, s.z)
wp.overload(test_generic_struct_kernel, [Foo])
wp.overload(test_generic_struct_kernel, [Bar])
def register(parent):
class TestGenerics(parent):
pass
devices = get_test_devices()
add_kernel_test(TestGenerics, name="test_generic_adder", kernel=test_generic_adder, dim=1, devices=devices)
add_kernel_test(TestGenerics, name="test_specialized_func", kernel=test_specialized_func, dim=1, devices=devices)
add_function_test(TestGenerics, "test_generic_array_kernel", test_generic_array_kernel, devices=devices)
add_function_test(TestGenerics, "test_generic_accumulator_kernel", test_generic_accumulator_kernel, devices=devices)
add_function_test(TestGenerics, "test_generic_fill", test_generic_fill, devices=devices)
add_function_test(TestGenerics, "test_generic_fill_overloads", test_generic_fill_overloads, devices=devices)
add_function_test(TestGenerics, "test_generic_transform_kernel", test_generic_transform_kernel, devices=devices)
add_function_test(
TestGenerics, "test_generic_transform_array_kernel", test_generic_transform_array_kernel, devices=devices
)
foo = Foo()
foo.x = 17.0
foo.y = 25.0
foo.z = 42.0
bar = Bar()
bar.x = wp.vec3(1, 2, 3)
bar.y = wp.vec3(10, 20, 30)
bar.z = wp.vec3(11, 22, 33)
add_kernel_test(
TestGenerics,
name="test_generic_struct_kernel",
kernel=test_generic_struct_kernel,
dim=1,
inputs=[foo],
devices=devices,
)
add_kernel_test(
TestGenerics,
name="test_generic_struct_kernel",
kernel=test_generic_struct_kernel,
dim=1,
inputs=[bar],
devices=devices,
)
return TestGenerics
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_generics.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 *
from warp.fem.types import *
from warp.fem.geometry import Grid2D, Trimesh2D, Tetmesh
from warp.fem.geometry.closest_point import project_on_tri_at_origin, project_on_tet_at_origin
from warp.fem.space import make_polynomial_space, SymmetricTensorMapper
from warp.fem.field import make_test
from warp.fem.domain import Cells
from warp.fem.integrate import integrate
from warp.fem.operator import integrand
from warp.fem.quadrature import RegularQuadrature
from warp.fem.utils import unit_element
wp.init()
wp.config.mode = "debug"
wp.config.verify_cuda = True
@integrand
def linear_form(s: Sample, u: Field):
return u(s)
def test_integrate_gradient(test_case, device):
with wp.ScopedDevice(device):
# Grid geometry
geo = Grid2D(res=vec2i(5))
# Domain and function spaces
domain = Cells(geometry=geo)
quadrature = RegularQuadrature(domain=domain, order=3)
scalar_space = make_polynomial_space(geo, degree=3)
u = scalar_space.make_field()
u.dof_values = wp.zeros_like(u.dof_values, requires_grad=True)
result = wp.empty(dtype=wp.float64, shape=(1), requires_grad=True)
tape = wp.Tape()
# forward pass
with tape:
integrate(linear_form, quadrature=quadrature, fields={"u": u}, output=result)
tape.backward(result)
test = make_test(space=scalar_space, domain=domain)
rhs = integrate(linear_form, quadrature=quadrature, fields={"u": test})
err = np.linalg.norm(rhs.numpy() - u.dof_values.grad.numpy())
test_case.assertLess(err, 1.0e-8)
def _gen_trimesh(N):
x = np.linspace(0.0, 1.0, N + 1)
y = np.linspace(0.0, 1.0, N + 1)
positions = np.transpose(np.meshgrid(x, y, indexing="ij")).reshape(-1, 2)
cx, cy = np.meshgrid(np.arange(N, dtype=int), np.arange(N, dtype=int), indexing="ij")
vidx = np.transpose(
np.array(
[
(N + 1) * cx + cy,
(N + 1) * (cx + 1) + cy,
(N + 1) * (cx + 1) + (cy + 1),
(N + 1) * cx + cy,
(N + 1) * (cx + 1) + (cy + 1),
(N + 1) * (cx) + (cy + 1),
]
)
).reshape((-1, 3))
return wp.array(positions, dtype=wp.vec2), wp.array(vidx, dtype=int)
def _gen_tetmesh(N):
x = np.linspace(0.0, 1.0, N + 1)
y = np.linspace(0.0, 1.0, N + 1)
z = np.linspace(0.0, 1.0, N + 1)
positions = np.transpose(np.meshgrid(x, y, z, indexing="ij")).reshape(-1, 3)
# Global node indices for each cell
cx, cy, cz = np.meshgrid(np.arange(N, dtype=int), np.arange(N, dtype=int), np.arange(N, dtype=int), indexing="ij")
grid_vidx = np.array(
[
(N + 1) ** 2 * cx + (N + 1) * cy + cz,
(N + 1) ** 2 * cx + (N + 1) * cy + cz + 1,
(N + 1) ** 2 * cx + (N + 1) * (cy + 1) + cz,
(N + 1) ** 2 * cx + (N + 1) * (cy + 1) + cz + 1,
(N + 1) ** 2 * (cx + 1) + (N + 1) * cy + cz,
(N + 1) ** 2 * (cx + 1) + (N + 1) * cy + cz + 1,
(N + 1) ** 2 * (cx + 1) + (N + 1) * (cy + 1) + cz,
(N + 1) ** 2 * (cx + 1) + (N + 1) * (cy + 1) + cz + 1,
]
)
# decompose grid cells into 5 tets
tet_vidx = np.array(
[
[0, 1, 2, 4],
[3, 2, 1, 7],
[5, 1, 7, 4],
[6, 7, 4, 2],
[4, 1, 2, 7],
]
)
# Convert to 3d index coordinates
vidx_coords = np.array(
[
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
]
)
tet_coords = vidx_coords[tet_vidx]
# Symmetry bits for each cell
ox, oy, oz = np.meshgrid(
np.arange(N, dtype=int) % 2, np.arange(N, dtype=int) % 2, np.arange(N, dtype=int) % 2, indexing="ij"
)
tet_coords = np.broadcast_to(tet_coords, shape=(*ox.shape, *tet_coords.shape))
# Flip coordinates according to symmetry
ox_bk = np.broadcast_to(ox.reshape(*ox.shape, 1, 1), tet_coords.shape[:-1])
oy_bk = np.broadcast_to(oy.reshape(*ox.shape, 1, 1), tet_coords.shape[:-1])
oz_bk = np.broadcast_to(oz.reshape(*ox.shape, 1, 1), tet_coords.shape[:-1])
tet_coords_x = tet_coords[..., 0] ^ ox_bk
tet_coords_y = tet_coords[..., 1] ^ oy_bk
tet_coords_z = tet_coords[..., 2] ^ oz_bk
# Back to local vertex indices
corner_indices = 4 * tet_coords_x + 2 * tet_coords_y + tet_coords_z
# Now go from cell-local to global node indices
# There must be a nicer way than this, but for example purposes this works
corner_indices = corner_indices.reshape(-1, 4)
grid_vidx = grid_vidx.reshape((8, -1, 1))
grid_vidx = np.broadcast_to(grid_vidx, shape=(8, grid_vidx.shape[1], 5))
grid_vidx = grid_vidx.reshape((8, -1))
node_indices = np.arange(corner_indices.shape[0])
tet_grid_vidx = np.transpose(
[
grid_vidx[corner_indices[:, 0], node_indices],
grid_vidx[corner_indices[:, 1], node_indices],
grid_vidx[corner_indices[:, 2], node_indices],
grid_vidx[corner_indices[:, 3], node_indices],
]
)
return wp.array(positions, dtype=wp.vec3), wp.array(tet_grid_vidx, dtype=int)
def test_triangle_mesh(test_case, device):
N = 3
with wp.ScopedDevice(device):
positions, tri_vidx = _gen_trimesh(N)
geo = Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
test_case.assertEqual(geo.cell_count(), 2 * (N) ** 2)
test_case.assertEqual(geo.vertex_count(), (N + 1) ** 2)
test_case.assertEqual(geo.side_count(), 2 * (N + 1) * N + (N**2))
test_case.assertEqual(geo.boundary_side_count(), 4 * N)
def test_tet_mesh(test_case, device):
N = 3
with wp.ScopedDevice(device):
positions, tet_vidx = _gen_tetmesh(N)
geo = Tetmesh(tet_vertex_indices=tet_vidx, positions=positions)
test_case.assertEqual(geo.cell_count(), 5 * (N) ** 3)
test_case.assertEqual(geo.vertex_count(), (N + 1) ** 3)
test_case.assertEqual(geo.side_count(), 6 * (N + 1) * N**2 + (N**3) * 4)
test_case.assertEqual(geo.boundary_side_count(), 12 * N * N)
@wp.kernel
def _test_closest_point_on_tri_kernel(
e0: wp.vec2,
e1: wp.vec2,
points: wp.array(dtype=wp.vec2),
sq_dist: wp.array(dtype=float),
coords: wp.array(dtype=Coords),
):
i = wp.tid()
d2, c = project_on_tri_at_origin(points[i], e0, e1)
sq_dist[i] = d2
coords[i] = c
@wp.kernel
def _test_closest_point_on_tet_kernel(
e0: wp.vec3,
e1: wp.vec3,
e2: wp.vec3,
points: wp.array(dtype=wp.vec3),
sq_dist: wp.array(dtype=float),
coords: wp.array(dtype=Coords),
):
i = wp.tid()
d2, c = project_on_tet_at_origin(points[i], e0, e1, e2)
sq_dist[i] = d2
coords[i] = c
def test_closest_point_queries(test_case, device):
# Test some simple lookup queries
e0 = wp.vec2(2.0, 0.0)
e1 = wp.vec2(0.0, 2.0)
points = wp.array(
(
[-1.0, -1.0],
[0.5, 0.5],
[1.0, 1.0],
[2.0, 2.0],
),
dtype=wp.vec2,
device=device,
)
expected_sq_dist = np.array([2.0, 0.0, 0.0, 2.0])
expected_coords = np.array([[1.0, 0.0, 0.0], [0.5, 0.25, 0.25], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5]])
sq_dist = wp.empty(shape=points.shape, dtype=float, device=device)
coords = wp.empty(shape=points.shape, dtype=Coords, device=device)
wp.launch(
_test_closest_point_on_tri_kernel, dim=points.shape, device=device, inputs=[e0, e1, points, sq_dist, coords]
)
assert_np_equal(coords.numpy(), expected_coords)
assert_np_equal(sq_dist.numpy(), expected_sq_dist)
# Tet
e0 = wp.vec3(3.0, 0.0, 0.0)
e1 = wp.vec3(0.0, 3.0, 0.0)
e2 = wp.vec3(0.0, 0.0, 3.0)
points = wp.array(
(
[-1.0, -1.0, -1.0],
[0.5, 0.5, 0.5],
[1.0, 1.0, 1.0],
[2.0, 2.0, 2.0],
),
dtype=wp.vec3,
device=device,
)
expected_sq_dist = np.array([3.0, 0.0, 0.0, 3.0])
expected_coords = np.array([[0.0, 0.0, 0.0], [1.0/6.0, 1.0/6.0, 1.0/6.0], [1.0/3.0, 1.0/3.0, 1.0/3.0], [1.0/3.0, 1.0/3.0, 1.0/3.0]])
sq_dist = wp.empty(shape=points.shape, dtype=float, device=device)
coords = wp.empty(shape=points.shape, dtype=Coords, device=device)
wp.launch(
_test_closest_point_on_tet_kernel, dim=points.shape, device=device, inputs=[e0, e1, e2, points, sq_dist, coords]
)
assert_np_equal(coords.numpy(), expected_coords, tol = 1.e-4)
assert_np_equal(sq_dist.numpy(), expected_sq_dist, tol = 1.e-4)
def test_regular_quadrature(test_case, device):
from warp.fem.geometry.element import LinearEdge, Triangle, Polynomial
for family in Polynomial:
# test integrating monomials
for degree in range(8):
coords, weights = LinearEdge().instantiate_quadrature(degree, family=family)
res = sum(w * pow(c[0], degree) for w, c in zip(weights, coords))
ref = 1.0 / (degree + 1)
test_case.assertAlmostEqual(ref, res, places=4)
# test integrating y^k1 (1 - x)^k2 on triangle using transformation to square
for x_degree in range(4):
for y_degree in range(4):
coords, weights = Triangle().instantiate_quadrature(x_degree + y_degree, family=family)
res = 0.5 * sum(w * pow(1.0 - c[1], x_degree) * pow(c[2], y_degree) for w, c in zip(weights, coords))
ref = 1.0 / ((x_degree + y_degree + 2) * (y_degree + 1))
# print(x_degree, y_degree, family, len(coords), res, ref)
test_case.assertAlmostEqual(ref, res, places=4)
# test integrating y^k1 (1 - x)^k2 on triangle using direct formulas
for x_degree in range(5):
for y_degree in range(5):
coords, weights = Triangle().instantiate_quadrature(x_degree + y_degree, family=None)
res = 0.5 * sum(w * pow(1.0 - c[1], x_degree) * pow(c[2], y_degree) for w, c in zip(weights, coords))
ref = 1.0 / ((x_degree + y_degree + 2) * (y_degree + 1))
test_case.assertAlmostEqual(ref, res, places=4)
def test_dof_mapper(test_case, device):
matrix_types = [wp.mat22, wp.mat33]
for mapping in SymmetricTensorMapper.Mapping:
for dtype in matrix_types:
mapper = SymmetricTensorMapper(dtype, mapping=mapping)
dof_dtype = mapper.dof_dtype
for k in range(dof_dtype._length_):
elem = np.array(dof_dtype(0.0))
elem[k] = 1.0
dof_vec = dof_dtype(elem)
mat = mapper.dof_to_value(dof_vec)
dof_round_trip = mapper.value_to_dof(mat)
# Check that value_to_dof(dof_to_value) is idempotent
assert_np_equal(np.array(dof_round_trip), np.array(dof_vec))
# Check that value is unitary for Frobenius norm 0.5 * |tau:tau|
frob_norm2 = 0.5 * wp.ddot(mat, mat)
test_case.assertAlmostEqual(frob_norm2, 1.0, places=6)
def register(parent):
devices = get_test_devices()
class TestFem(parent):
pass
add_function_test(TestFem, "test_regular_quadrature", test_regular_quadrature)
add_function_test(TestFem, "test_closest_point_queries", test_closest_point_queries)
add_function_test(TestFem, "test_integrate_gradient", test_integrate_gradient, devices=devices)
add_function_test(TestFem, "test_triangle_mesh", test_triangle_mesh, devices=devices)
add_function_test(TestFem, "test_tet_mesh", test_tet_mesh, devices=devices)
add_function_test(TestFem, "test_dof_mapper", test_dof_mapper)
return TestFem
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_fem.py |
import numpy as np
import os
import warp as wp
from warp.tests.test_base import *
wp.init()
np_float_types = [np.float32, np.float64, np.float16]
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 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)]
vec3 = wp.types.vector(length=3, dtype=wptype)
quat = wp.types.quaternion(dtype=wptype)
def check_component_constructor(
input: wp.array(dtype=wptype),
q: wp.array(dtype=wptype),
):
qresult = quat(input[0], input[1], input[2], input[3])
# multiply the output by 2 so we've got something to backpropagate:
q[0] = wptype(2) * qresult[0]
q[1] = wptype(2) * qresult[1]
q[2] = wptype(2) * qresult[2]
q[3] = wptype(2) * qresult[3]
def check_vector_constructor(
input: wp.array(dtype=wptype),
q: wp.array(dtype=wptype),
):
qresult = quat(vec3(input[0], input[1], input[2]), input[3])
# multiply the output by 2 so we've got something to backpropagate:
q[0] = wptype(2) * qresult[0]
q[1] = wptype(2) * qresult[1]
q[2] = wptype(2) * qresult[2]
q[3] = wptype(2) * qresult[3]
kernel = getkernel(check_component_constructor, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
vec_kernel = getkernel(check_vector_constructor, suffix=dtype.__name__)
if register_kernels:
return
input = wp.array(np.random.randn(4).astype(dtype), requires_grad=True, device=device)
output = wp.zeros_like(input)
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol)
for i in range(4):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
input = wp.array(np.random.randn(4).astype(dtype), requires_grad=True, device=device)
output = wp.zeros_like(input)
wp.launch(vec_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=tol)
for i in range(4):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(vec_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
def test_inverse(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.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)]
quat = wp.types.quaternion(dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_quat_inverse(
input: wp.array(dtype=wptype),
shouldbeidentity: wp.array(dtype=quat),
q: wp.array(dtype=wptype),
):
qread = quat(input[0], input[1], input[2], input[3])
qresult = wp.quat_inverse(qread)
# this inverse should work for normalized quaternions:
shouldbeidentity[0] = wp.normalize(qread) * wp.quat_inverse(wp.normalize(qread))
# multiply the output by 2 so we've got something to backpropagate:
q[0] = wptype(2) * qresult[0]
q[1] = wptype(2) * qresult[1]
q[2] = wptype(2) * qresult[2]
q[3] = wptype(2) * qresult[3]
kernel = getkernel(check_quat_inverse, suffix=dtype.__name__)
if register_kernels:
return
input = wp.array(np.random.randn(4).astype(dtype), requires_grad=True, device=device)
shouldbeidentity = wp.array(np.zeros((1, 4)), dtype=quat, requires_grad=True, device=device)
output = wp.zeros_like(input)
wp.launch(kernel, dim=1, inputs=[input], outputs=[shouldbeidentity, output], device=device)
assert_np_equal(shouldbeidentity.numpy(), np.array([0, 0, 0, 1]), tol=tol)
for i in range(4):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[shouldbeidentity, output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = -2 if i != 3 else 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_dot(
s: wp.array(dtype=quat),
v: wp.array(dtype=quat),
dot: wp.array(dtype=wptype),
):
dot[0] = wptype(2) * wp.dot(v[0], s[0])
dotkernel = getkernel(check_quat_dot, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
v = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
dot = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
dotkernel,
dim=1,
inputs=[
s,
v,
],
outputs=[dot],
device=device,
)
assert_np_equal(dot.numpy()[0], 2.0 * (v.numpy() * s.numpy()).sum(), tol=tol)
tape.backward(loss=dot)
sgrads = tape.gradients[s].numpy()[0]
expected_grads = 2.0 * v.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v].numpy()[0]
expected_grads = 2.0 * s.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=tol)
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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_length(
q: wp.array(dtype=quat),
l: wp.array(dtype=wptype),
l2: wp.array(dtype=wptype),
):
l[0] = wptype(2) * wp.length(q[0])
l2[0] = wptype(2) * wp.length_sq(q[0])
kernel = getkernel(check_quat_length, suffix=dtype.__name__)
if register_kernels:
return
q = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
l = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
q,
],
outputs=[l, l2],
device=device,
)
assert_np_equal(l.numpy()[0], 2 * np.linalg.norm(q.numpy()), tol=10 * tol)
assert_np_equal(l2.numpy()[0], 2 * np.linalg.norm(q.numpy()) ** 2, tol=10 * tol)
tape.backward(loss=l)
grad = tape.gradients[q].numpy()[0]
expected_grad = 2 * q.numpy()[0] / np.linalg.norm(q.numpy())
assert_np_equal(grad, expected_grad, tol=10 * tol)
tape.zero()
tape.backward(loss=l2)
grad = tape.gradients[q].numpy()[0]
expected_grad = 4 * q.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)]
quat = wp.types.quaternion(dtype=wptype)
def check_normalize(
q: wp.array(dtype=quat),
n0: wp.array(dtype=wptype),
n1: wp.array(dtype=wptype),
n2: wp.array(dtype=wptype),
n3: wp.array(dtype=wptype),
):
n = wptype(2) * (wp.normalize(q[0]))
n0[0] = n[0]
n1[0] = n[1]
n2[0] = n[2]
n3[0] = n[3]
def check_normalize_alt(
q: wp.array(dtype=quat),
n0: wp.array(dtype=wptype),
n1: wp.array(dtype=wptype),
n2: wp.array(dtype=wptype),
n3: wp.array(dtype=wptype),
):
n = wptype(2) * (q[0] / wp.length(q[0]))
n0[0] = n[0]
n1[0] = n[1]
n2[0] = n[2]
n3[0] = n[3]
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
q = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
n0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n0_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n1_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n2_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
n3_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
outputs0 = [
n0,
n1,
n2,
n3,
]
tape0 = wp.Tape()
with tape0:
wp.launch(normalize_kernel, dim=1, inputs=[q], outputs=outputs0, device=device)
outputs1 = [
n0_alt,
n1_alt,
n2_alt,
n3_alt,
]
tape1 = wp.Tape()
with tape1:
wp.launch(
normalize_alt_kernel,
dim=1,
inputs=[
q,
],
outputs=outputs1,
device=device,
)
assert_np_equal(n0.numpy()[0], n0_alt.numpy()[0], tol=tol)
assert_np_equal(n1.numpy()[0], n1_alt.numpy()[0], tol=tol)
assert_np_equal(n2.numpy()[0], n2_alt.numpy()[0], tol=tol)
assert_np_equal(n3.numpy()[0], n3_alt.numpy()[0], tol=tol)
for ncmp, ncmpalt in zip(outputs0, outputs1):
tape0.backward(loss=ncmp)
tape1.backward(loss=ncmpalt)
assert_np_equal(tape0.gradients[q].numpy()[0], tape1.gradients[q].numpy()[0], tol=tol)
tape0.zero()
tape1.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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_add(
q: wp.array(dtype=quat),
v: wp.array(dtype=quat),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
result = q[0] + v[0]
r0[0] = wptype(2) * result[0]
r1[0] = wptype(2) * result[1]
r2[0] = wptype(2) * result[2]
r3[0] = wptype(2) * result[3]
kernel = getkernel(check_quat_add, suffix=dtype.__name__)
if register_kernels:
return
q = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
v = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
q,
v,
],
outputs=[r0, r1, r2, r3],
device=device,
)
assert_np_equal(r0.numpy()[0], 2 * (v.numpy()[0, 0] + q.numpy()[0, 0]), tol=tol)
assert_np_equal(r1.numpy()[0], 2 * (v.numpy()[0, 1] + q.numpy()[0, 1]), tol=tol)
assert_np_equal(r2.numpy()[0], 2 * (v.numpy()[0, 2] + q.numpy()[0, 2]), tol=tol)
assert_np_equal(r3.numpy()[0], 2 * (v.numpy()[0, 3] + q.numpy()[0, 3]), tol=tol)
for i, l in enumerate([r0, r1, r2, r3]):
tape.backward(loss=l)
qgrads = tape.gradients[q].numpy()[0]
expected_grads = np.zeros_like(qgrads)
expected_grads[i] = 2
assert_np_equal(qgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v].numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=tol)
tape.zero()
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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_sub(
q: wp.array(dtype=quat),
v: wp.array(dtype=quat),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
result = v[0] - q[0]
r0[0] = wptype(2) * result[0]
r1[0] = wptype(2) * result[1]
r2[0] = wptype(2) * result[2]
r3[0] = wptype(2) * result[3]
kernel = getkernel(check_quat_sub, suffix=dtype.__name__)
if register_kernels:
return
q = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
v = wp.array(np.random.randn(4).astype(dtype), dtype=quat, requires_grad=True, device=device)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
q,
v,
],
outputs=[r0, r1, r2, r3],
device=device,
)
assert_np_equal(r0.numpy()[0], 2 * (v.numpy()[0, 0] - q.numpy()[0, 0]), tol=tol)
assert_np_equal(r1.numpy()[0], 2 * (v.numpy()[0, 1] - q.numpy()[0, 1]), tol=tol)
assert_np_equal(r2.numpy()[0], 2 * (v.numpy()[0, 2] - q.numpy()[0, 2]), tol=tol)
assert_np_equal(r3.numpy()[0], 2 * (v.numpy()[0, 3] - q.numpy()[0, 3]), tol=tol)
for i, l in enumerate([r0, r1, r2, r3]):
tape.backward(loss=l)
qgrads = tape.gradients[q].numpy()[0]
expected_grads = np.zeros_like(qgrads)
expected_grads[i] = -2
assert_np_equal(qgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v].numpy()[0]
expected_grads[i] = 2
assert_np_equal(vgrads, expected_grads, tol=tol)
tape.zero()
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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_scalar_mul(
s: wp.array(dtype=wptype),
q: wp.array(dtype=quat),
l0: wp.array(dtype=wptype),
l1: wp.array(dtype=wptype),
l2: wp.array(dtype=wptype),
l3: wp.array(dtype=wptype),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
lresult = s[0] * q[0]
rresult = q[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
l0[0] = wptype(2) * lresult[0]
l1[0] = wptype(2) * lresult[1]
l2[0] = wptype(2) * lresult[2]
l3[0] = wptype(2) * lresult[3]
r0[0] = wptype(2) * rresult[0]
r1[0] = wptype(2) * rresult[1]
r2[0] = wptype(2) * rresult[2]
r3[0] = wptype(2) * rresult[3]
kernel = getkernel(check_quat_scalar_mul, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(1).astype(dtype), requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
l0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
l1 = wp.zeros(1, dtype=wptype, 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)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, q],
outputs=[
l0,
l1,
l2,
l3,
r0,
r1,
r2,
r3,
],
device=device,
)
assert_np_equal(l0.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 0], tol=tol)
assert_np_equal(l1.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 1], tol=tol)
assert_np_equal(l2.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 2], tol=tol)
assert_np_equal(l3.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 3], tol=tol)
assert_np_equal(r0.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 0], tol=tol)
assert_np_equal(r1.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 1], tol=tol)
assert_np_equal(r2.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 2], tol=tol)
assert_np_equal(r3.numpy()[0], 2 * s.numpy()[0] * q.numpy()[0, 3], tol=tol)
if dtype in np_float_types:
for i, outputs in enumerate([(l0, r0), (l1, r1), (l2, r2), (l3, r3)]):
for l in outputs:
tape.backward(loss=l)
sgrad = tape.gradients[s].numpy()[0]
assert_np_equal(sgrad, 2 * q.numpy()[0, i], tol=tol)
allgrads = tape.gradients[q].numpy()[0]
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_division(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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_scalar_div(
s: wp.array(dtype=wptype),
q: wp.array(dtype=quat),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
result = q[0] / s[0]
# multiply outputs by 2 so we've got something to backpropagate:
r0[0] = wptype(2) * result[0]
r1[0] = wptype(2) * result[1]
r2[0] = wptype(2) * result[2]
r3[0] = wptype(2) * result[3]
kernel = getkernel(check_quat_scalar_div, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(1).astype(dtype), requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, q],
outputs=[
r0,
r1,
r2,
r3,
],
device=device,
)
assert_np_equal(r0.numpy()[0], 2 * q.numpy()[0, 0] / s.numpy()[0], tol=tol)
assert_np_equal(r1.numpy()[0], 2 * q.numpy()[0, 1] / s.numpy()[0], tol=tol)
assert_np_equal(r2.numpy()[0], 2 * q.numpy()[0, 2] / s.numpy()[0], tol=tol)
assert_np_equal(r3.numpy()[0], 2 * q.numpy()[0, 3] / s.numpy()[0], tol=tol)
if dtype in np_float_types:
for i, r in enumerate([r0, r1, r2, r3]):
tape.backward(loss=r)
sgrad = tape.gradients[s].numpy()[0]
assert_np_equal(sgrad, -2 * q.numpy()[0, i] / (s.numpy()[0] * s.numpy()[0]), tol=tol)
allgrads = tape.gradients[q].numpy()[0]
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = 2 / s.numpy()[0]
assert_np_equal(allgrads, expected_grads, tol=10 * tol)
tape.zero()
def test_quat_multiplication(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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_mul(
s: wp.array(dtype=quat),
q: wp.array(dtype=quat),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
result = s[0] * q[0]
# multiply outputs by 2 so we've got something to backpropagate:
r0[0] = wptype(2) * result[0]
r1[0] = wptype(2) * result[1]
r2[0] = wptype(2) * result[2]
r3[0] = wptype(2) * result[3]
kernel = getkernel(check_quat_mul, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, q],
outputs=[
r0,
r1,
r2,
r3,
],
device=device,
)
a = s.numpy()
b = q.numpy()
assert_np_equal(
r0.numpy()[0], 2 * (a[0, 3] * b[0, 0] + b[0, 3] * a[0, 0] + a[0, 1] * b[0, 2] - b[0, 1] * a[0, 2]), tol=tol
)
assert_np_equal(
r1.numpy()[0], 2 * (a[0, 3] * b[0, 1] + b[0, 3] * a[0, 1] + a[0, 2] * b[0, 0] - b[0, 2] * a[0, 0]), tol=tol
)
assert_np_equal(
r2.numpy()[0], 2 * (a[0, 3] * b[0, 2] + b[0, 3] * a[0, 2] + a[0, 0] * b[0, 1] - b[0, 0] * a[0, 1]), tol=tol
)
assert_np_equal(
r3.numpy()[0], 2 * (a[0, 3] * b[0, 3] - a[0, 0] * b[0, 0] - a[0, 1] * b[0, 1] - a[0, 2] * b[0, 2]), tol=tol
)
tape.backward(loss=r0)
agrad = tape.gradients[s].numpy()[0]
assert_np_equal(agrad, 2 * np.array([b[0, 3], b[0, 2], -b[0, 1], b[0, 0]]), tol=tol)
bgrad = tape.gradients[q].numpy()[0]
assert_np_equal(bgrad, 2 * np.array([a[0, 3], -a[0, 2], a[0, 1], a[0, 0]]), tol=tol)
tape.zero()
tape.backward(loss=r1)
agrad = tape.gradients[s].numpy()[0]
assert_np_equal(agrad, 2 * np.array([-b[0, 2], b[0, 3], b[0, 0], b[0, 1]]), tol=tol)
bgrad = tape.gradients[q].numpy()[0]
assert_np_equal(bgrad, 2 * np.array([a[0, 2], a[0, 3], -a[0, 0], a[0, 1]]), tol=tol)
tape.zero()
tape.backward(loss=r2)
agrad = tape.gradients[s].numpy()[0]
assert_np_equal(agrad, 2 * np.array([b[0, 1], -b[0, 0], b[0, 3], b[0, 2]]), tol=tol)
bgrad = tape.gradients[q].numpy()[0]
assert_np_equal(bgrad, 2 * np.array([-a[0, 1], a[0, 0], a[0, 3], a[0, 2]]), tol=tol)
tape.zero()
tape.backward(loss=r3)
agrad = tape.gradients[s].numpy()[0]
assert_np_equal(agrad, 2 * np.array([-b[0, 0], -b[0, 1], -b[0, 2], b[0, 3]]), tol=tol)
bgrad = tape.gradients[q].numpy()[0]
assert_np_equal(bgrad, 2 * np.array([-a[0, 0], -a[0, 1], -a[0, 2], a[0, 3]]), tol=tol)
tape.zero()
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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_indexing(
q: wp.array(dtype=quat),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
r0[0] = wptype(2) * q[0][0]
r1[0] = wptype(2) * q[0][1]
r2[0] = wptype(2) * q[0][2]
r3[0] = wptype(2) * q[0][3]
kernel = getkernel(check_quat_indexing, suffix=dtype.__name__)
if register_kernels:
return
q = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[q], outputs=[r0, r1, r2, r3], device=device)
for i, l in enumerate([r0, r1, r2, r3]):
tape.backward(loss=l)
allgrads = tape.gradients[q].numpy()[0]
expected_grads = np.zeros_like(allgrads)
expected_grads[i] = 2
assert_np_equal(allgrads, expected_grads, tol=tol)
tape.zero()
assert_np_equal(r0.numpy()[0], 2.0 * q.numpy()[0, 0], tol=tol)
assert_np_equal(r1.numpy()[0], 2.0 * q.numpy()[0, 1], tol=tol)
assert_np_equal(r2.numpy()[0], 2.0 * q.numpy()[0, 2], tol=tol)
assert_np_equal(r3.numpy()[0], 2.0 * q.numpy()[0, 3], tol=tol)
def test_quat_lerp(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)]
quat = wp.types.quaternion(dtype=wptype)
def check_quat_lerp(
s: wp.array(dtype=quat),
q: wp.array(dtype=quat),
t: wp.array(dtype=wptype),
r0: wp.array(dtype=wptype),
r1: wp.array(dtype=wptype),
r2: wp.array(dtype=wptype),
r3: wp.array(dtype=wptype),
):
result = wp.lerp(s[0], q[0], t[0])
# multiply outputs by 2 so we've got something to backpropagate:
r0[0] = wptype(2) * result[0]
r1[0] = wptype(2) * result[1]
r2[0] = wptype(2) * result[2]
r3[0] = wptype(2) * result[3]
kernel = getkernel(check_quat_lerp, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
q = wp.array(np.random.randn(1, 4).astype(dtype), dtype=quat, requires_grad=True, device=device)
t = wp.array(np.random.uniform(size=1).astype(dtype), dtype=wptype, requires_grad=True, device=device)
r0 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r1 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
r3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, q, t],
outputs=[
r0,
r1,
r2,
r3,
],
device=device,
)
a = s.numpy()
b = q.numpy()
tt = t.numpy()
assert_np_equal(r0.numpy()[0], 2 * ((1 - tt) * a[0, 0] + tt * b[0, 0]), tol=tol)
assert_np_equal(r1.numpy()[0], 2 * ((1 - tt) * a[0, 1] + tt * b[0, 1]), tol=tol)
assert_np_equal(r2.numpy()[0], 2 * ((1 - tt) * a[0, 2] + tt * b[0, 2]), tol=tol)
assert_np_equal(r3.numpy()[0], 2 * ((1 - tt) * a[0, 3] + tt * b[0, 3]), tol=tol)
for i, l in enumerate([r0, r1, r2, r3]):
tape.backward(loss=l)
agrad = tape.gradients[s].numpy()[0]
bgrad = tape.gradients[q].numpy()[0]
tgrad = tape.gradients[t].numpy()[0]
expected_grads = np.zeros_like(agrad)
expected_grads[i] = 2 * (1 - tt)
assert_np_equal(agrad, expected_grads, tol=tol)
expected_grads[i] = 2 * tt
assert_np_equal(bgrad, expected_grads, tol=tol)
assert_np_equal(tgrad, 2 * (b[0, i] - a[0, i]), tol=tol)
tape.zero()
def test_quat_rotate(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)]
quat = wp.types.quaternion(dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
def check_quat_rotate(
q: wp.array(dtype=quat),
v: wp.array(dtype=vec3),
outputs: wp.array(dtype=wptype),
outputs_inv: wp.array(dtype=wptype),
outputs_manual: wp.array(dtype=wptype),
outputs_inv_manual: wp.array(dtype=wptype),
):
result = wp.quat_rotate(q[0], v[0])
result_inv = wp.quat_rotate_inv(q[0], v[0])
qv = vec3(q[0][0], q[0][1], q[0][2])
qw = q[0][3]
result_manual = v[0] * (wptype(2) * qw * qw - wptype(1))
result_manual += wp.cross(qv, v[0]) * qw * wptype(2)
result_manual += qv * wp.dot(qv, v[0]) * wptype(2)
result_inv_manual = v[0] * (wptype(2) * qw * qw - wptype(1))
result_inv_manual -= wp.cross(qv, v[0]) * qw * wptype(2)
result_inv_manual += qv * wp.dot(qv, v[0]) * wptype(2)
for i in range(3):
# multiply outputs by 2 so we've got something to backpropagate:
outputs[i] = wptype(2) * result[i]
outputs_inv[i] = wptype(2) * result_inv[i]
outputs_manual[i] = wptype(2) * result_manual[i]
outputs_inv_manual[i] = wptype(2) * result_inv_manual[i]
kernel = getkernel(check_quat_rotate, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = np.random.randn(1, 4)
q /= np.linalg.norm(q)
q = wp.array(q.astype(dtype), dtype=quat, requires_grad=True, device=device)
v = wp.array(0.5 * np.random.randn(1, 3).astype(dtype), dtype=vec3, requires_grad=True, device=device)
# test values against the manually computed result:
outputs = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_inv = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_manual = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
outputs_inv_manual = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[q, v],
outputs=[
outputs,
outputs_inv,
outputs_manual,
outputs_inv_manual,
],
device=device,
)
assert_np_equal(outputs.numpy(), outputs_manual.numpy(), tol=tol)
assert_np_equal(outputs_inv.numpy(), outputs_inv_manual.numpy(), tol=tol)
# test gradients against the manually computed result:
for i in range(3):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_inv = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_inv_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[q, v],
outputs=[
outputs,
outputs_inv,
outputs_manual,
outputs_inv_manual,
],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[cmp], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_inv, i], outputs=[cmp_inv], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs_manual, i], outputs=[cmp_manual], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outputs_inv_manual, i], outputs=[cmp_inv_manual], device=device
)
tape.backward(loss=cmp)
qgrads = 1.0 * tape.gradients[q].numpy()
vgrads = 1.0 * tape.gradients[v].numpy()
tape.zero()
tape.backward(loss=cmp_inv)
qgrads_inv = 1.0 * tape.gradients[q].numpy()
vgrads_inv = 1.0 * tape.gradients[v].numpy()
tape.zero()
tape.backward(loss=cmp_manual)
qgrads_manual = 1.0 * tape.gradients[q].numpy()
vgrads_manual = 1.0 * tape.gradients[v].numpy()
tape.zero()
tape.backward(loss=cmp_inv_manual)
qgrads_inv_manual = 1.0 * tape.gradients[q].numpy()
vgrads_inv_manual = 1.0 * tape.gradients[v].numpy()
tape.zero()
assert_np_equal(qgrads, qgrads_manual, tol=tol)
assert_np_equal(vgrads, vgrads_manual, tol=tol)
assert_np_equal(qgrads_inv, qgrads_inv_manual, tol=tol)
assert_np_equal(vgrads_inv, vgrads_inv_manual, tol=tol)
def test_quat_to_matrix(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)]
quat = wp.types.quaternion(dtype=wptype)
mat3 = wp.types.matrix(shape=(3, 3), dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
def check_quat_to_matrix(
q: wp.array(dtype=quat),
outputs: wp.array(dtype=wptype),
outputs_manual: wp.array(dtype=wptype),
):
result = wp.quat_to_matrix(q[0])
xaxis = wp.quat_rotate(
q[0],
vec3(
wptype(1),
wptype(0),
wptype(0),
),
)
yaxis = wp.quat_rotate(
q[0],
vec3(
wptype(0),
wptype(1),
wptype(0),
),
)
zaxis = wp.quat_rotate(
q[0],
vec3(
wptype(0),
wptype(0),
wptype(1),
),
)
result_manual = mat3(xaxis, yaxis, zaxis)
idx = 0
for i in range(3):
for j in range(3):
# multiply outputs by 2 so we've got something to backpropagate:
outputs[idx] = wptype(2) * result[i, j]
outputs_manual[idx] = wptype(2) * result_manual[i, j]
idx = idx + 1
kernel = getkernel(check_quat_to_matrix, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
q = np.random.randn(1, 4)
q /= np.linalg.norm(q)
q = wp.array(q.astype(dtype), dtype=quat, requires_grad=True, device=device)
# test values against the manually computed result:
outputs = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
outputs_manual = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[q],
outputs=[
outputs,
outputs_manual,
],
device=device,
)
assert_np_equal(outputs.numpy(), outputs_manual.numpy(), tol=tol)
# sanity check: divide by 2 to remove that scale factor we put in there, and
# it should be a rotation matrix
R = 0.5 * outputs.numpy().reshape(3, 3)
assert_np_equal(np.matmul(R, R.T), np.eye(3), tol=tol)
# test gradients against the manually computed result:
idx = 0
for i in range(3):
for j in range(3):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
cmp_manual = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[q],
outputs=[
outputs,
outputs_manual,
],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, idx], outputs=[cmp], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outputs_manual, idx], outputs=[cmp_manual], device=device
)
tape.backward(loss=cmp)
qgrads = 1.0 * tape.gradients[q].numpy()
tape.zero()
tape.backward(loss=cmp_manual)
qgrads_manual = 1.0 * tape.gradients[q].numpy()
tape.zero()
assert_np_equal(qgrads, qgrads_manual, tol=tol)
idx = idx + 1
############################################################
def test_slerp_grad(test, device, dtype, register_kernels=False):
seed = 42
np.random.seed(seed)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(3, wptype)
quat = wp.types.quaternion(wptype)
def slerp_kernel(
q0: wp.array(dtype=quat),
q1: wp.array(dtype=quat),
t: wp.array(dtype=wptype),
loss: wp.array(dtype=wptype),
index: int,
):
tid = wp.tid()
q = wp.quat_slerp(q0[tid], q1[tid], t[tid])
wp.atomic_add(loss, 0, q[index])
slerp_kernel = getkernel(slerp_kernel, suffix=dtype.__name__)
def slerp_kernel_forward(
q0: wp.array(dtype=quat),
q1: wp.array(dtype=quat),
t: wp.array(dtype=wptype),
loss: wp.array(dtype=wptype),
index: int,
):
tid = wp.tid()
axis = vec3()
angle = wptype(0.0)
wp.quat_to_axis_angle(wp.mul(wp.quat_inverse(q0[tid]), q1[tid]), axis, angle)
q = wp.mul(q0[tid], wp.quat_from_axis_angle(axis, t[tid] * angle))
wp.atomic_add(loss, 0, q[index])
slerp_kernel_forward = getkernel(slerp_kernel_forward, suffix=dtype.__name__)
def quat_sampler_slerp(kernel_seed: int, quats: wp.array(dtype=quat)):
tid = wp.tid()
state = wp.rand_init(kernel_seed, tid)
angle = wp.randf(state, 0.0, 2.0 * 3.1415926535)
dir = wp.sample_unit_sphere_surface(state) * wp.sin(angle * 0.5)
q = quat(wptype(dir[0]), wptype(dir[1]), wptype(dir[2]), wptype(wp.cos(angle * 0.5)))
qn = wp.normalize(q)
quats[tid] = qn
quat_sampler = getkernel(quat_sampler_slerp, suffix=dtype.__name__)
if register_kernels:
return
N = 50
q0 = wp.zeros(N, dtype=quat, device=device, requires_grad=True)
q1 = wp.zeros(N, dtype=quat, device=device, requires_grad=True)
wp.launch(kernel=quat_sampler, dim=N, inputs=[seed, q0], device=device)
wp.launch(kernel=quat_sampler, dim=N, inputs=[seed + 1, q1], device=device)
t = np.random.uniform(0.0, 1.0, N)
t = wp.array(t, dtype=wptype, device=device, requires_grad=True)
def compute_gradients(kernel, wrt, index):
loss = wp.zeros(1, dtype=wptype, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=kernel, dim=N, inputs=[q0, q1, t, loss, index], device=device)
tape.backward(loss)
gradients = 1.0 * tape.gradients[wrt].numpy()
tape.zero()
return loss.numpy()[0], gradients
eps = {
np.float16: 2.0e-2,
np.float32: 1.0e-5,
np.float64: 1.0e-8,
}.get(dtype, 0)
# wrt t
# gather gradients from builtin adjoints
xcmp, gradients_x = compute_gradients(slerp_kernel, t, 0)
ycmp, gradients_y = compute_gradients(slerp_kernel, t, 1)
zcmp, gradients_z = compute_gradients(slerp_kernel, t, 2)
wcmp, gradients_w = compute_gradients(slerp_kernel, t, 3)
# gather gradients from autodiff
xcmp_auto, gradients_x_auto = compute_gradients(slerp_kernel_forward, t, 0)
ycmp_auto, gradients_y_auto = compute_gradients(slerp_kernel_forward, t, 1)
zcmp_auto, gradients_z_auto = compute_gradients(slerp_kernel_forward, t, 2)
wcmp_auto, gradients_w_auto = compute_gradients(slerp_kernel_forward, t, 3)
assert_np_equal(gradients_x, gradients_x_auto, tol=eps)
assert_np_equal(gradients_y, gradients_y_auto, tol=eps)
assert_np_equal(gradients_z, gradients_z_auto, tol=eps)
assert_np_equal(gradients_w, gradients_w_auto, tol=eps)
assert_np_equal(xcmp, xcmp_auto, tol=eps)
assert_np_equal(ycmp, ycmp_auto, tol=eps)
assert_np_equal(zcmp, zcmp_auto, tol=eps)
assert_np_equal(wcmp, wcmp_auto, tol=eps)
# wrt q0
# gather gradients from builtin adjoints
xcmp, gradients_x = compute_gradients(slerp_kernel, q0, 0)
ycmp, gradients_y = compute_gradients(slerp_kernel, q0, 1)
zcmp, gradients_z = compute_gradients(slerp_kernel, q0, 2)
wcmp, gradients_w = compute_gradients(slerp_kernel, q0, 3)
# gather gradients from autodiff
xcmp_auto, gradients_x_auto = compute_gradients(slerp_kernel_forward, q0, 0)
ycmp_auto, gradients_y_auto = compute_gradients(slerp_kernel_forward, q0, 1)
zcmp_auto, gradients_z_auto = compute_gradients(slerp_kernel_forward, q0, 2)
wcmp_auto, gradients_w_auto = compute_gradients(slerp_kernel_forward, q0, 3)
assert_np_equal(gradients_x, gradients_x_auto, tol=eps)
assert_np_equal(gradients_y, gradients_y_auto, tol=eps)
assert_np_equal(gradients_z, gradients_z_auto, tol=eps)
assert_np_equal(gradients_w, gradients_w_auto, tol=eps)
assert_np_equal(xcmp, xcmp_auto, tol=eps)
assert_np_equal(ycmp, ycmp_auto, tol=eps)
assert_np_equal(zcmp, zcmp_auto, tol=eps)
assert_np_equal(wcmp, wcmp_auto, tol=eps)
# wrt q1
# gather gradients from builtin adjoints
xcmp, gradients_x = compute_gradients(slerp_kernel, q1, 0)
ycmp, gradients_y = compute_gradients(slerp_kernel, q1, 1)
zcmp, gradients_z = compute_gradients(slerp_kernel, q1, 2)
wcmp, gradients_w = compute_gradients(slerp_kernel, q1, 3)
# gather gradients from autodiff
xcmp_auto, gradients_x_auto = compute_gradients(slerp_kernel_forward, q1, 0)
ycmp_auto, gradients_y_auto = compute_gradients(slerp_kernel_forward, q1, 1)
zcmp_auto, gradients_z_auto = compute_gradients(slerp_kernel_forward, q1, 2)
wcmp_auto, gradients_w_auto = compute_gradients(slerp_kernel_forward, q1, 3)
assert_np_equal(gradients_x, gradients_x_auto, tol=eps)
assert_np_equal(gradients_y, gradients_y_auto, tol=eps)
assert_np_equal(gradients_z, gradients_z_auto, tol=eps)
assert_np_equal(gradients_w, gradients_w_auto, tol=eps)
assert_np_equal(xcmp, xcmp_auto, tol=eps)
assert_np_equal(ycmp, ycmp_auto, tol=eps)
assert_np_equal(zcmp, zcmp_auto, tol=eps)
assert_np_equal(wcmp, wcmp_auto, tol=eps)
############################################################
def test_quat_to_axis_angle_grad(test, device, dtype, register_kernels=False):
seed = 42
rng = np.random.default_rng(seed)
num_rand = 50
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(3, wptype)
vec4 = wp.types.vector(4, wptype)
quat = wp.types.quaternion(wptype)
def quat_to_axis_angle_kernel(quats: wp.array(dtype=quat), loss: wp.array(dtype=wptype), coord_idx: int):
tid = wp.tid()
axis = vec3()
angle = wptype(0.0)
wp.quat_to_axis_angle(quats[tid], axis, angle)
a = vec4(axis[0], axis[1], axis[2], angle)
wp.atomic_add(loss, 0, a[coord_idx])
quat_to_axis_angle_kernel = getkernel(quat_to_axis_angle_kernel, suffix=dtype.__name__)
def quat_to_axis_angle_kernel_forward(quats: wp.array(dtype=quat), loss: wp.array(dtype=wptype), coord_idx: int):
tid = wp.tid()
q = quats[tid]
axis = vec3()
angle = wptype(0.0)
v = vec3(q[0], q[1], q[2])
if q[3] < wptype(0):
axis = -wp.normalize(v)
else:
axis = wp.normalize(v)
angle = wptype(2) * wp.atan2(wp.length(v), wp.abs(q[3]))
a = vec4(axis[0], axis[1], axis[2], angle)
wp.atomic_add(loss, 0, a[coord_idx])
quat_to_axis_angle_kernel_forward = getkernel(quat_to_axis_angle_kernel_forward, suffix=dtype.__name__)
def quat_sampler(kernel_seed: int, angles: wp.array(dtype=float), quats: wp.array(dtype=quat)):
tid = wp.tid()
state = wp.rand_init(kernel_seed, tid)
angle = angles[tid]
dir = wp.sample_unit_sphere_surface(state) * wp.sin(angle * 0.5)
q = quat(wptype(dir[0]), wptype(dir[1]), wptype(dir[2]), wptype(wp.cos(angle * 0.5)))
qn = wp.normalize(q)
quats[tid] = qn
quat_sampler = getkernel(quat_sampler, suffix=dtype.__name__)
if register_kernels:
return
quats = wp.zeros(num_rand, dtype=quat, device=device, requires_grad=True)
angles = wp.array(
np.linspace(0.0, 2.0 * np.pi, num_rand, endpoint=False, dtype=np.float32), dtype=float, device=device
)
wp.launch(kernel=quat_sampler, dim=num_rand, inputs=[seed, angles, quats], device=device)
edge_cases = np.array(
[(1.0, 0.0, 0.0, 0.0), (0.0, 1.0 / np.sqrt(3), 1.0 / np.sqrt(3), 1.0 / np.sqrt(3)), (0.0, 0.0, 0.0, 0.0)]
)
num_edge = len(edge_cases)
edge_cases = wp.array(edge_cases, dtype=quat, device=device, requires_grad=True)
def compute_gradients(arr, kernel, dim, index):
loss = wp.zeros(1, dtype=wptype, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=kernel, dim=dim, inputs=[arr, loss, index], device=device)
tape.backward(loss)
gradients = 1.0 * tape.gradients[arr].numpy()
tape.zero()
return loss.numpy()[0], gradients
# gather gradients from builtin adjoints
xcmp, gradients_x = compute_gradients(quats, quat_to_axis_angle_kernel, num_rand, 0)
ycmp, gradients_y = compute_gradients(quats, quat_to_axis_angle_kernel, num_rand, 1)
zcmp, gradients_z = compute_gradients(quats, quat_to_axis_angle_kernel, num_rand, 2)
wcmp, gradients_w = compute_gradients(quats, quat_to_axis_angle_kernel, num_rand, 3)
# gather gradients from autodiff
xcmp_auto, gradients_x_auto = compute_gradients(quats, quat_to_axis_angle_kernel_forward, num_rand, 0)
ycmp_auto, gradients_y_auto = compute_gradients(quats, quat_to_axis_angle_kernel_forward, num_rand, 1)
zcmp_auto, gradients_z_auto = compute_gradients(quats, quat_to_axis_angle_kernel_forward, num_rand, 2)
wcmp_auto, gradients_w_auto = compute_gradients(quats, quat_to_axis_angle_kernel_forward, num_rand, 3)
# edge cases: gather gradients from builtin adjoints
_, edge_gradients_x = compute_gradients(edge_cases, quat_to_axis_angle_kernel, num_edge, 0)
_, edge_gradients_y = compute_gradients(edge_cases, quat_to_axis_angle_kernel, num_edge, 1)
_, edge_gradients_z = compute_gradients(edge_cases, quat_to_axis_angle_kernel, num_edge, 2)
_, edge_gradients_w = compute_gradients(edge_cases, quat_to_axis_angle_kernel, num_edge, 3)
# edge cases: gather gradients from autodiff
_, edge_gradients_x_auto = compute_gradients(edge_cases, quat_to_axis_angle_kernel_forward, num_edge, 0)
_, edge_gradients_y_auto = compute_gradients(edge_cases, quat_to_axis_angle_kernel_forward, num_edge, 1)
_, edge_gradients_z_auto = compute_gradients(edge_cases, quat_to_axis_angle_kernel_forward, num_edge, 2)
_, edge_gradients_w_auto = compute_gradients(edge_cases, quat_to_axis_angle_kernel_forward, num_edge, 3)
eps = {
np.float16: 2.0e-1,
np.float32: 2.0e-4,
np.float64: 2.0e-7,
}.get(dtype, 0)
assert_np_equal(xcmp, xcmp_auto, tol=eps)
assert_np_equal(ycmp, ycmp_auto, tol=eps)
assert_np_equal(zcmp, zcmp_auto, tol=eps)
assert_np_equal(wcmp, wcmp_auto, tol=eps)
assert_np_equal(gradients_x, gradients_x_auto, tol=eps)
assert_np_equal(gradients_y, gradients_y_auto, tol=eps)
assert_np_equal(gradients_z, gradients_z_auto, tol=eps)
assert_np_equal(gradients_w, gradients_w_auto, tol=eps)
assert_np_equal(edge_gradients_x, edge_gradients_x_auto, tol=eps)
assert_np_equal(edge_gradients_y, edge_gradients_y_auto, tol=eps)
assert_np_equal(edge_gradients_z, edge_gradients_z_auto, tol=eps)
assert_np_equal(edge_gradients_w, edge_gradients_w_auto, tol=eps)
############################################################
def test_quat_rpy_grad(test, device, dtype, register_kernels=False):
seed = 42
np.random.seed(seed)
N = 3
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(3, wptype)
quat = wp.types.quaternion(wptype)
def rpy_to_quat_kernel(rpy_arr: wp.array(dtype=vec3), loss: wp.array(dtype=wptype), coord_idx: int):
tid = wp.tid()
rpy = rpy_arr[tid]
roll = rpy[0]
pitch = rpy[1]
yaw = rpy[2]
q = wp.quat_rpy(roll, pitch, yaw)
wp.atomic_add(loss, 0, q[coord_idx])
rpy_to_quat_kernel = getkernel(rpy_to_quat_kernel, suffix=dtype.__name__)
def rpy_to_quat_kernel_forward(rpy_arr: wp.array(dtype=vec3), loss: wp.array(dtype=wptype), coord_idx: int):
tid = wp.tid()
rpy = rpy_arr[tid]
roll = rpy[0]
pitch = rpy[1]
yaw = rpy[2]
cy = wp.cos(yaw * wptype(0.5))
sy = wp.sin(yaw * wptype(0.5))
cr = wp.cos(roll * wptype(0.5))
sr = wp.sin(roll * wptype(0.5))
cp = wp.cos(pitch * wptype(0.5))
sp = wp.sin(pitch * wptype(0.5))
w = cy * cr * cp + sy * sr * sp
x = cy * sr * cp - sy * cr * sp
y = cy * cr * sp + sy * sr * cp
z = sy * cr * cp - cy * sr * sp
q = quat(x, y, z, w)
wp.atomic_add(loss, 0, q[coord_idx])
rpy_to_quat_kernel_forward = getkernel(rpy_to_quat_kernel_forward, suffix=dtype.__name__)
if register_kernels:
return
rpy_arr = np.random.uniform(-np.pi, np.pi, (N, 3))
rpy_arr = wp.array(rpy_arr, dtype=vec3, device=device, requires_grad=True)
def compute_gradients(kernel, wrt, index):
loss = wp.zeros(1, dtype=wptype, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=kernel, dim=N, inputs=[wrt, loss, index], device=device)
tape.backward(loss)
gradients = 1.0 * tape.gradients[wrt].numpy()
tape.zero()
return loss.numpy()[0], gradients
# wrt rpy
# gather gradients from builtin adjoints
rcmp, gradients_r = compute_gradients(rpy_to_quat_kernel, rpy_arr, 0)
pcmp, gradients_p = compute_gradients(rpy_to_quat_kernel, rpy_arr, 1)
ycmp, gradients_y = compute_gradients(rpy_to_quat_kernel, rpy_arr, 2)
# gather gradients from autodiff
rcmp_auto, gradients_r_auto = compute_gradients(rpy_to_quat_kernel_forward, rpy_arr, 0)
pcmp_auto, gradients_p_auto = compute_gradients(rpy_to_quat_kernel_forward, rpy_arr, 1)
ycmp_auto, gradients_y_auto = compute_gradients(rpy_to_quat_kernel_forward, rpy_arr, 2)
eps = {
np.float16: 2.0e-2,
np.float32: 1.0e-5,
np.float64: 1.0e-8,
}.get(dtype, 0)
assert_np_equal(rcmp, rcmp_auto, tol=eps)
assert_np_equal(pcmp, pcmp_auto, tol=eps)
assert_np_equal(ycmp, ycmp_auto, tol=eps)
assert_np_equal(gradients_r, gradients_r_auto, tol=eps)
assert_np_equal(gradients_p, gradients_p_auto, tol=eps)
assert_np_equal(gradients_y, gradients_y_auto, tol=eps)
############################################################
def test_quat_from_matrix(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat33 = wp.types.matrix((3, 3), wptype)
quat = wp.types.quaternion(wptype)
def quat_from_matrix(m: wp.array2d(dtype=wptype), loss: wp.array(dtype=wptype), idx: int):
tid = wp.tid()
matrix = mat33(
m[tid, 0], m[tid, 1], m[tid, 2], m[tid, 3], m[tid, 4], m[tid, 5], m[tid, 6], m[tid, 7], m[tid, 8]
)
q = wp.quat_from_matrix(matrix)
wp.atomic_add(loss, 0, q[idx])
def quat_from_matrix_forward(mats: wp.array2d(dtype=wptype), loss: wp.array(dtype=wptype), idx: int):
tid = wp.tid()
m = mat33(
mats[tid, 0],
mats[tid, 1],
mats[tid, 2],
mats[tid, 3],
mats[tid, 4],
mats[tid, 5],
mats[tid, 6],
mats[tid, 7],
mats[tid, 8],
)
tr = m[0][0] + m[1][1] + m[2][2]
x = wptype(0)
y = wptype(0)
z = wptype(0)
w = wptype(0)
h = wptype(0)
if tr >= wptype(0):
h = wp.sqrt(tr + wptype(1))
w = wptype(0.5) * h
h = wptype(0.5) / h
x = (m[2][1] - m[1][2]) * h
y = (m[0][2] - m[2][0]) * h
z = (m[1][0] - m[0][1]) * h
else:
max_diag = 0
if m[1][1] > m[0][0]:
max_diag = 1
if m[2][2] > m[max_diag][max_diag]:
max_diag = 2
if max_diag == 0:
h = wp.sqrt((m[0][0] - (m[1][1] + m[2][2])) + wptype(1))
x = wptype(0.5) * h
h = wptype(0.5) / h
y = (m[0][1] + m[1][0]) * h
z = (m[2][0] + m[0][2]) * h
w = (m[2][1] - m[1][2]) * h
elif max_diag == 1:
h = wp.sqrt((m[1][1] - (m[2][2] + m[0][0])) + wptype(1))
y = wptype(0.5) * h
h = wptype(0.5) / h
z = (m[1][2] + m[2][1]) * h
x = (m[0][1] + m[1][0]) * h
w = (m[0][2] - m[2][0]) * h
if max_diag == 2:
h = wp.sqrt((m[2][2] - (m[0][0] + m[1][1])) + wptype(1))
z = wptype(0.5) * h
h = wptype(0.5) / h
x = (m[2][0] + m[0][2]) * h
y = (m[1][2] + m[2][1]) * h
w = (m[1][0] - m[0][1]) * h
q = wp.normalize(quat(x, y, z, w))
wp.atomic_add(loss, 0, q[idx])
quat_from_matrix = getkernel(quat_from_matrix, suffix=dtype.__name__)
quat_from_matrix_forward = getkernel(quat_from_matrix_forward, suffix=dtype.__name__)
if register_kernels:
return
m = np.array(
[
[1.0, 0.0, 0.0, 0.0, 0.5, 0.866, 0.0, -0.866, 0.5],
[0.866, 0.0, 0.25, -0.433, 0.5, 0.75, -0.25, -0.866, 0.433],
[0.866, -0.433, 0.25, 0.0, 0.5, 0.866, -0.5, -0.75, 0.433],
[-1.2, -1.6, -2.3, 0.25, -0.6, -0.33, 3.2, -1.0, -2.2],
]
)
m = wp.array2d(m, dtype=wptype, device=device, requires_grad=True)
N = m.shape[0]
def compute_gradients(kernel, wrt, index):
loss = wp.zeros(1, dtype=wptype, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=kernel, dim=N, inputs=[m, loss, index], device=device)
tape.backward(loss)
gradients = 1.0 * tape.gradients[wrt].numpy()
tape.zero()
return loss.numpy()[0], gradients
# gather gradients from builtin adjoints
cmpx, gradients_x = compute_gradients(quat_from_matrix, m, 0)
cmpy, gradients_y = compute_gradients(quat_from_matrix, m, 1)
cmpz, gradients_z = compute_gradients(quat_from_matrix, m, 2)
cmpw, gradients_w = compute_gradients(quat_from_matrix, m, 3)
# gather gradients from autodiff
cmpx_auto, gradients_x_auto = compute_gradients(quat_from_matrix_forward, m, 0)
cmpy_auto, gradients_y_auto = compute_gradients(quat_from_matrix_forward, m, 1)
cmpz_auto, gradients_z_auto = compute_gradients(quat_from_matrix_forward, m, 2)
cmpw_auto, gradients_w_auto = compute_gradients(quat_from_matrix_forward, m, 3)
# compare
eps = 1.0e6
eps = {
np.float16: 2.0e-2,
np.float32: 1.0e-5,
np.float64: 1.0e-8,
}.get(dtype, 0)
assert_np_equal(cmpx, cmpx_auto, tol=eps)
assert_np_equal(cmpy, cmpy_auto, tol=eps)
assert_np_equal(cmpz, cmpz_auto, tol=eps)
assert_np_equal(cmpw, cmpw_auto, tol=eps)
assert_np_equal(gradients_x, gradients_x_auto, tol=eps)
assert_np_equal(gradients_y, gradients_y_auto, tol=eps)
assert_np_equal(gradients_z, gradients_z_auto, tol=eps)
assert_np_equal(gradients_w, gradients_w_auto, tol=eps)
def test_quat_identity(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def quat_identity_test(output: wp.array(dtype=wptype)):
q = wp.quat_identity(dtype=wptype)
output[0] = q[0]
output[1] = q[1]
output[2] = q[2]
output[3] = q[3]
def quat_identity_test_default(output: wp.array(dtype=wp.float32)):
q = wp.quat_identity()
output[0] = q[0]
output[1] = q[1]
output[2] = q[2]
output[3] = q[3]
quat_identity_kernel = getkernel(quat_identity_test, suffix=dtype.__name__)
quat_identity_default_kernel = getkernel(quat_identity_test_default, suffix=np.float32.__name__)
if register_kernels:
return
output = wp.zeros(4, dtype=wptype, device=device)
wp.launch(quat_identity_kernel, dim=1, inputs=[], outputs=[output], device=device)
expected = np.zeros_like(output.numpy())
expected[3] = 1
assert_np_equal(output.numpy(), expected)
# let's just test that it defaults to float32:
output = wp.zeros(4, dtype=wp.float32, device=device)
wp.launch(quat_identity_default_kernel, dim=1, inputs=[], outputs=[output], device=device)
expected = np.zeros_like(output.numpy())
expected[3] = 1
assert_np_equal(output.numpy(), expected)
def test_anon_type_instance(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def quat_create_test(input: wp.array(dtype=wptype), output: wp.array(dtype=wptype)):
# component constructor:
q = wp.quaternion(input[0], input[1], input[2], input[3])
output[0] = wptype(2) * q[0]
output[1] = wptype(2) * q[1]
output[2] = wptype(2) * q[2]
output[3] = wptype(2) * q[3]
# vector / scalar constructor:
q2 = wp.quaternion(wp.vector(input[4], input[5], input[6]), input[7])
output[4] = wptype(2) * q2[0]
output[5] = wptype(2) * q2[1]
output[6] = wptype(2) * q2[2]
output[7] = wptype(2) * q2[3]
quat_create_kernel = getkernel(quat_create_test, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(np.random.randn(8).astype(dtype), requires_grad=True, device=device)
output = wp.zeros(8, dtype=wptype, requires_grad=True, device=device)
wp.launch(quat_create_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy())
for i in range(len(input)):
cmp = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(quat_create_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[cmp], device=device)
tape.backward(loss=cmp)
expectedgrads = np.zeros(len(input))
expectedgrads[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
# Same as above but with a default (float) type
# which tests some different code paths that
# need to ensure types are correctly canonicalized
# during codegen
@wp.kernel
def test_constructor_default():
qzero = wp.quat()
wp.expect_eq(qzero[0], 0.0)
wp.expect_eq(qzero[1], 0.0)
wp.expect_eq(qzero[2], 0.0)
wp.expect_eq(qzero[3], 0.0)
qval = wp.quat(1.0, 2.0, 3.0, 4.0)
wp.expect_eq(qval[0], 1.0)
wp.expect_eq(qval[1], 2.0)
wp.expect_eq(qval[2], 3.0)
wp.expect_eq(qval[3], 4.0)
qeye = wp.quat_identity()
wp.expect_eq(qeye[0], 0.0)
wp.expect_eq(qeye[1], 0.0)
wp.expect_eq(qeye[2], 0.0)
wp.expect_eq(qeye[3], 1.0)
def register(parent):
devices = get_test_devices()
class TestQuat(parent):
pass
add_kernel_test(TestQuat, test_constructor_default, dim=1, devices=devices)
for dtype in np_float_types:
add_function_test_register_kernel(
TestQuat, f"test_constructors_{dtype.__name__}", test_constructors, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_anon_type_instance_{dtype.__name__}", test_anon_type_instance, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_inverse_{dtype.__name__}", test_inverse, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_quat_identity_{dtype.__name__}", test_quat_identity, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_dotproduct_{dtype.__name__}", test_dotproduct, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_length_{dtype.__name__}", test_length, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_normalize_{dtype.__name__}", test_normalize, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_addition_{dtype.__name__}", test_addition, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat,
f"test_scalar_multiplication_{dtype.__name__}",
test_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestQuat, f"test_scalar_division_{dtype.__name__}", test_scalar_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat,
f"test_quat_multiplication_{dtype.__name__}",
test_quat_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestQuat, f"test_indexing_{dtype.__name__}", test_indexing, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_quat_lerp_{dtype.__name__}", test_quat_lerp, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat,
f"test_quat_to_axis_angle_grad_{dtype.__name__}",
test_quat_to_axis_angle_grad,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestQuat, f"test_slerp_grad_{dtype.__name__}", test_slerp_grad, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_quat_rpy_grad_{dtype.__name__}", test_quat_rpy_grad, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_quat_from_matrix_{dtype.__name__}", test_quat_from_matrix, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_quat_rotate_{dtype.__name__}", test_quat_rotate, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestQuat, f"test_quat_to_matrix_{dtype.__name__}", test_quat_to_matrix, devices=devices, dtype=dtype
)
return TestQuat
if __name__ == "__main__":
wp.build.clear_kernel_cache()
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_quat.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 matplotlib.pyplot as plt
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def test_kernel(
kernel_seed: int,
int_a: wp.array(dtype=int),
int_ab: wp.array(dtype=int),
float_01: wp.array(dtype=float),
float_ab: wp.array(dtype=float),
):
tid = wp.tid()
state = wp.rand_init(kernel_seed, tid)
int_a[tid] = wp.randi(state)
int_ab[tid] = wp.randi(state, 0, 100)
float_01[tid] = wp.randf(state)
float_ab[tid] = wp.randf(state, 0.0, 100.0)
def test_rand(test, device):
N = 10
int_a_device = wp.zeros(N, dtype=int, device=device)
int_a_host = wp.zeros(N, dtype=int, device="cpu")
int_ab_device = wp.zeros(N, dtype=int, device=device)
int_ab_host = wp.zeros(N, dtype=int, device="cpu")
float_01_device = wp.zeros(N, dtype=float, device=device)
float_01_host = wp.zeros(N, dtype=float, device="cpu")
float_ab_device = wp.zeros(N, dtype=float, device=device)
float_ab_host = wp.zeros(N, dtype=float, device="cpu")
seed = 42
wp.launch(
kernel=test_kernel,
dim=N,
inputs=[seed, int_a_device, int_ab_device, float_01_device, float_ab_device],
outputs=[],
device=device,
)
wp.copy(int_a_host, int_a_device)
wp.copy(int_ab_host, int_ab_device)
wp.copy(float_01_host, float_01_device)
wp.copy(float_ab_host, float_ab_device)
wp.synchronize()
int_a = int_a_host.numpy()
int_ab = int_ab_host.numpy()
float_01 = float_01_host.numpy()
float_ab = float_ab_host.numpy()
int_a_true = np.array(
[
-575632308,
59537738,
1898992239,
442961864,
-1069147335,
-478445524,
1803659809,
2122909397,
-1888556360,
334603718,
]
)
int_ab_true = np.array([46, 58, 46, 83, 85, 39, 72, 99, 18, 41])
float_01_true = np.array(
[
0.72961855,
0.86200964,
0.28770837,
0.8187722,
0.186335,
0.6101239,
0.56432086,
0.70428324,
0.64812654,
0.27679986,
]
)
float_ab_true = np.array(
[96.04259, 73.33809, 63.601555, 38.647305, 71.813896, 64.65809, 77.79791, 46.579605, 94.614456, 91.921814]
)
test.assertTrue((int_a == int_a_true).all())
test.assertTrue((int_ab == int_ab_true).all())
err = np.max(np.abs(float_01 - float_01_true))
test.assertTrue(err < 1e-04)
err = np.max(np.abs(float_ab - float_ab_true))
test.assertTrue(err < 1e-04)
@wp.kernel
def sample_cdf_kernel(kernel_seed: int, cdf: wp.array(dtype=float), samples: wp.array(dtype=int)):
tid = wp.tid()
state = wp.rand_init(kernel_seed, tid)
samples[tid] = wp.sample_cdf(state, cdf)
def test_sample_cdf(test, device):
seed = 42
cdf = np.arange(0.0, 1.0, 0.01, dtype=float)
cdf = cdf * cdf
cdf = wp.array(cdf, dtype=float, device=device)
num_samples = 1000
samples = wp.zeros(num_samples, dtype=int, device=device)
wp.launch(kernel=sample_cdf_kernel, dim=num_samples, inputs=[seed, cdf, samples], device=device)
# histogram should be linear
# plt.hist(samples.numpy())
# plt.show()
@wp.kernel
def sampling_kernel(
kernel_seed: int,
triangle_samples: wp.array(dtype=wp.vec2),
square_samples: wp.array(dtype=wp.vec2),
ring_samples: wp.array(dtype=wp.vec2),
disk_samples: wp.array(dtype=wp.vec2),
sphere_surface_samples: wp.array(dtype=wp.vec3),
sphere_samples: wp.array(dtype=wp.vec3),
hemisphere_surface_samples: wp.array(dtype=wp.vec3),
hemisphere_samples: wp.array(dtype=wp.vec3),
cube_samples: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
state = wp.rand_init(kernel_seed, tid)
triangle_samples[tid] = wp.sample_triangle(state)
ring_samples[tid] = wp.sample_unit_ring(state)
disk_samples[tid] = wp.sample_unit_disk(state)
sphere_surface_samples[tid] = wp.sample_unit_sphere_surface(state)
sphere_samples[tid] = wp.sample_unit_sphere(state)
hemisphere_surface_samples[tid] = wp.sample_unit_hemisphere_surface(state)
hemisphere_samples[tid] = wp.sample_unit_hemisphere(state)
square_samples[tid] = wp.sample_unit_square(state)
cube_samples[tid] = wp.sample_unit_cube(state)
def test_sampling_methods(test, device):
seed = 42
num_samples = 100
triangle_samples = wp.zeros(num_samples, dtype=wp.vec2, device=device)
square_samples = wp.zeros(num_samples, dtype=wp.vec2, device=device)
ring_samples = wp.zeros(num_samples, dtype=wp.vec2, device=device)
disk_samples = wp.zeros(num_samples, dtype=wp.vec2, device=device)
sphere_surface_samples = wp.zeros(num_samples, dtype=wp.vec3, device=device)
sphere_samples = wp.zeros(num_samples, dtype=wp.vec3, device=device)
hemisphere_surface_samples = wp.zeros(num_samples, dtype=wp.vec3, device=device)
hemisphere_samples = wp.zeros(num_samples, dtype=wp.vec3, device=device)
cube_samples = wp.zeros(num_samples, dtype=wp.vec3, device=device)
wp.launch(
kernel=sampling_kernel,
dim=num_samples,
inputs=[
seed,
triangle_samples,
square_samples,
ring_samples,
disk_samples,
sphere_surface_samples,
sphere_samples,
hemisphere_surface_samples,
hemisphere_samples,
cube_samples,
],
device=device,
)
# bounds check
test.assertTrue((triangle_samples.numpy()[:, 0] <= 1.0).all())
test.assertTrue((triangle_samples.numpy()[:, 0] >= 0.0).all())
test.assertTrue((triangle_samples.numpy()[:, 1] >= 0.0).all())
test.assertTrue((triangle_samples.numpy()[:, 1] >= 0.0).all())
test.assertTrue((square_samples.numpy()[:, 0] >= -0.5).all())
test.assertTrue((square_samples.numpy()[:, 0] <= 1.5).all())
test.assertTrue((square_samples.numpy()[:, 1] >= -0.5).all())
test.assertTrue((square_samples.numpy()[:, 1] <= 0.5).all())
test.assertTrue((cube_samples.numpy()[:, 0] >= -0.5).all())
test.assertTrue((cube_samples.numpy()[:, 0] <= 0.5).all())
test.assertTrue((cube_samples.numpy()[:, 1] >= -0.5).all())
test.assertTrue((cube_samples.numpy()[:, 1] <= 0.5).all())
test.assertTrue((cube_samples.numpy()[:, 2] >= -0.5).all())
test.assertTrue((cube_samples.numpy()[:, 2] <= 0.5).all())
test.assertTrue((hemisphere_surface_samples.numpy()[:, 2] >= 0.0).all())
test.assertTrue((hemisphere_samples.numpy()[:, 2] >= 0.0).all())
test.assertTrue((np.linalg.norm(ring_samples.numpy(), axis=1) <= 1.0 + 1e6).all())
test.assertTrue((np.linalg.norm(disk_samples.numpy(), axis=1) <= 1.0 + 1e6).all())
test.assertTrue((np.linalg.norm(sphere_surface_samples.numpy(), axis=1) <= 1.0 + 1e6).all())
test.assertTrue((np.linalg.norm(sphere_samples.numpy(), axis=1) <= 1.0 + 1e6).all())
test.assertTrue((np.linalg.norm(hemisphere_surface_samples.numpy(), axis=1) <= 1.0 + 1e6).all())
test.assertTrue((np.linalg.norm(hemisphere_samples.numpy(), axis=1) <= 1.0 + 1e6).all())
@wp.kernel
def sample_poisson_kernel(
kernel_seed: int, poisson_samples_low: wp.array(dtype=wp.uint32), poisson_samples_high: wp.array(dtype=wp.uint32)
):
tid = wp.tid()
state = wp.rand_init(kernel_seed, tid)
x = wp.poisson(state, 3.0)
y = wp.poisson(state, 42.0)
poisson_samples_low[tid] = x
poisson_samples_high[tid] = y
def test_poisson(test, device):
seed = 13
N = 20000
poisson_low = wp.zeros(N, dtype=wp.uint32, device=device)
poisson_high = wp.zeros(N, dtype=wp.uint32, device=device)
wp.launch(kernel=sample_poisson_kernel, dim=N, inputs=[seed, poisson_low, poisson_high], device=device)
# bins = np.arange(100)
# _ = plt.hist(poisson_high.numpy(), bins)
# plt.show()
np.random.default_rng(seed)
np_poisson_low = np.random.poisson(3.0, N)
np_poisson_high = np.random.poisson(42.0, N)
poisson_low_mean = np.mean(poisson_low.numpy())
np_poisson_low_mean = np.mean(np_poisson_low)
poisson_high_mean = np.mean(poisson_high.numpy())
np_poisson_high_mean = np.mean(np_poisson_high)
poisson_low_std = np.std(poisson_low.numpy())
np_poisson_low_std = np.std(np_poisson_low)
poisson_high_std = np.std(poisson_high.numpy())
np_poisson_high_std = np.std(np_poisson_high)
# compare basic distribution characteristics
test.assertTrue(np.abs(poisson_low_mean - np_poisson_low_mean) <= 5e-1)
test.assertTrue(np.abs(poisson_high_mean - np_poisson_high_mean) <= 5e-1)
test.assertTrue(np.abs(poisson_low_std - np_poisson_low_std) <= 2e-1)
test.assertTrue(np.abs(poisson_high_std - np_poisson_high_std) <= 2e-1)
def register(parent):
devices = get_test_devices()
class TestNoise(parent):
pass
add_function_test(TestNoise, "test_rand", test_rand, devices=devices)
add_function_test(TestNoise, "test_sample_cdf", test_sample_cdf, devices=devices)
add_function_test(TestNoise, "test_sampling_methods", test_sampling_methods, devices=devices)
add_function_test(TestNoise, "test_poisson", test_poisson, devices=devices)
return TestNoise
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_rand.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 min_vec3(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.min(a[0], b[0]), wp.min(a[1], b[1]), wp.min(a[2], b[2]))
@wp.func
def max_vec3(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.max(a[0], b[0]), wp.max(a[1], b[1]), wp.max(a[2], b[2]))
@wp.kernel
def compute_bounds(
indices: wp.array(dtype=int),
positions: wp.array(dtype=wp.vec3),
lowers: wp.array(dtype=wp.vec3),
uppers: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = indices[tid * 3 + 0]
j = indices[tid * 3 + 1]
k = indices[tid * 3 + 2]
x0 = positions[i] # point zero
x1 = positions[j] # point one
x2 = positions[k] # point two
lower = min_vec3(min_vec3(x0, x1), x2)
upper = max_vec3(max_vec3(x0, x1), x2)
lowers[tid] = lower
uppers[tid] = upper
@wp.kernel
def compute_num_contacts(
lowers: wp.array(dtype=wp.vec3), uppers: wp.array(dtype=wp.vec3), mesh_id: wp.uint64, counts: wp.array(dtype=int)
):
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
tid = wp.tid()
upper = uppers[tid]
lower = lowers[tid]
query = wp.mesh_query_aabb(mesh_id, lower, upper)
count = int(0)
# index = int(-1)
# while wp.mesh_query_aabb_next(query, index):
for index in query:
count = count + 1
counts[tid] = count
def test_compute_bounds(test, device):
# create two touching triangles.
points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [-1, -1, 1]])
indices = np.array([0, 1, 2, 1, 2, 3])
m = wp.Mesh(
points=wp.array(points, dtype=wp.vec3, device=device),
indices=wp.array(indices, dtype=int, device=device),
)
num_tris = int(len(indices) / 3)
# First compute bounds of each of the triangles.
lowers = wp.empty(n=num_tris, dtype=wp.vec3, device=device)
uppers = wp.empty_like(lowers)
wp.launch(
kernel=compute_bounds,
dim=num_tris,
inputs=[m.indices, m.points],
outputs=[lowers, uppers],
device=device,
)
lower_view = lowers.numpy()
upper_view = uppers.numpy()
wp.synchronize()
# Confirm the bounds of each triangle are correct.
test.assertTrue(lower_view[0][0] == 0)
test.assertTrue(lower_view[0][1] == 0)
test.assertTrue(lower_view[0][2] == 0)
test.assertTrue(upper_view[0][0] == 1)
test.assertTrue(upper_view[0][1] == 1)
test.assertTrue(upper_view[0][2] == 0)
test.assertTrue(lower_view[1][0] == -1)
test.assertTrue(lower_view[1][1] == -1)
test.assertTrue(lower_view[1][2] == 0)
test.assertTrue(upper_view[1][0] == 1)
test.assertTrue(upper_view[1][1] == 1)
test.assertTrue(upper_view[1][2] == 1)
def test_mesh_query_aabb_count_overlap(test, device):
# create two touching triangles.
points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [-1, -1, 1]])
indices = np.array([0, 1, 2, 1, 2, 3])
m = wp.Mesh(
points=wp.array(points, dtype=wp.vec3, device=device),
indices=wp.array(indices, dtype=int, device=device),
)
num_tris = int(len(indices) / 3)
# Compute AABB of each of the triangles.
lowers = wp.empty(n=num_tris, dtype=wp.vec3, device=device)
uppers = wp.empty_like(lowers)
wp.launch(
kernel=compute_bounds,
dim=num_tris,
inputs=[m.indices, m.points],
outputs=[lowers, uppers],
device=device,
)
counts = wp.empty(n=num_tris, dtype=int, device=device)
wp.launch(
kernel=compute_num_contacts,
dim=num_tris,
inputs=[lowers, uppers, m.id],
outputs=[counts],
device=device,
)
wp.synchronize()
view = counts.numpy()
# 2 triangles that share a vertex having overlapping AABBs.
for c in view:
test.assertTrue(c == 2)
def test_mesh_query_aabb_count_nonoverlap(test, device):
# create two separate triangles.
points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [10, 0, 0], [10, 1, 0], [10, 0, 1]])
indices = np.array([0, 1, 2, 3, 4, 5])
m = wp.Mesh(
points=wp.array(points, dtype=wp.vec3, device=device),
indices=wp.array(indices, dtype=int, device=device),
)
num_tris = int(len(indices) / 3)
lowers = wp.empty(n=num_tris, dtype=wp.vec3, device=device)
uppers = wp.empty_like(lowers)
wp.launch(
kernel=compute_bounds,
dim=num_tris,
inputs=[m.indices, m.points],
outputs=[lowers, uppers],
device=device,
)
counts = wp.empty(n=num_tris, dtype=int, device=device)
wp.launch(
kernel=compute_num_contacts,
dim=num_tris,
inputs=[lowers, uppers, m.id],
outputs=[counts],
device=device,
)
wp.synchronize()
view = counts.numpy()
# AABB query only returns one triangle at a time, the triangles are not close enough to overlap.
for c in view:
test.assertTrue(c == 1)
def register(parent):
devices = get_test_devices()
class TestMeshQueryAABBMethods(parent):
pass
add_function_test(TestMeshQueryAABBMethods, "test_compute_bounds", test_compute_bounds, devices=devices)
add_function_test(
TestMeshQueryAABBMethods,
"test_mesh_query_aabb_count_overlap",
test_mesh_query_aabb_count_overlap,
devices=devices,
)
add_function_test(
TestMeshQueryAABBMethods,
"test_mesh_query_aabb_count_nonoverlap",
test_mesh_query_aabb_count_nonoverlap,
devices=devices,
)
return TestMeshQueryAABBMethods
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_mesh_query_aabb.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 importlib
import os
import tempfile
import unittest
import warp as wp
from warp.tests.test_base import *
from importlib import util
CODE = """# -*- coding: utf-8 -*-
import warp as wp
@wp.struct
class Data:
x: wp.array(dtype=int)
@wp.func
def increment(x: int):
# This shouldn't be picked up.
return x + 123
@wp.func
def increment(x: int):
return x + 1
@wp.kernel
def compute(data: Data):
data.x[0] = increment(data.x[0])
"""
wp.init()
def load_code_as_module(code, name):
file, file_path = tempfile.mkstemp(suffix=".py")
try:
with os.fdopen(file, "w") as f:
f.write(code)
spec = util.spec_from_file_location(name, file_path)
module = util.module_from_spec(spec)
spec.loader.exec_module(module)
finally:
os.remove(file_path)
return module
def test_transient_module(test, device):
module = load_code_as_module(CODE, "")
# Loading it a second time shouldn't be an issue.
module = load_code_as_module(CODE, "")
assert len(module.compute.module.structs) == 1
assert len(module.compute.module.functions) == 1
data = module.Data()
data.x = wp.array([123], dtype=int)
wp.set_module_options({"foo": "bar"}, module=module)
assert wp.get_module_options(module=module).get("foo") == "bar"
assert module.compute.module.options.get("foo") == "bar"
wp.launch(module.compute, dim=1, inputs=[data])
assert_np_equal(data.x.numpy(), np.array([124]))
def register(parent):
devices = get_test_devices()
class TestTransientModule(parent):
pass
add_function_test(TestTransientModule, "test_transient_module", test_transient_module, devices=devices)
return TestTransientModule
if __name__ == "__main__":
_ = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_transient_module.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
import math
import warp as wp
from warp.tests.test_base import *
import unittest
import importlib
import os
# dummy module used for testing reload
import warp.tests.test_square as test_square
# dummy modules used for testing reload with dependencies
import warp.tests.test_dependent as test_dependent
import warp.tests.test_reference as test_reference
import warp.tests.test_reference_reference as test_reference_reference
wp.init()
def test_redefine(test, device):
# --------------------------------------------
# first pass
@wp.kernel
def basic(x: wp.array(dtype=float)):
tid = wp.tid()
x[tid] = float(tid) * 1.0
n = 32
x = wp.zeros(n, dtype=float, device=device)
wp.launch(kernel=basic, dim=n, inputs=[x], device=device)
# --------------------------------------------
# redefine kernel, should trigger a recompile
@wp.kernel
def basic(x: wp.array(dtype=float)):
tid = wp.tid()
x[tid] = float(tid) * 2.0
y = wp.zeros(n, dtype=float, device=device)
wp.launch(kernel=basic, dim=n, inputs=[y], device=device)
assert_np_equal(np.arange(0, n, 1), x.numpy())
assert_np_equal(np.arange(0, n, 1) * 2.0, y.numpy())
square_two = """import warp as wp
wp.init()
@wp.func
def sqr(x: float):
return x * x
@wp.kernel
def kern(expect: float):
wp.expect_eq(sqr(2.0), expect)
def run(expect, device):
wp.launch(kern, dim=1, inputs=[expect], device=device)
"""
square_four = """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)
"""
def test_reload(test, device):
# write out the module python and import it
f = open(os.path.abspath(os.path.join(os.path.dirname(__file__), "test_square.py")), "w")
f.writelines(square_two)
f.flush()
f.close()
importlib.reload(test_square)
test_square.run(expect=4.0, device=device) # 2*2=4
f = open(os.path.abspath(os.path.join(os.path.dirname(__file__), "test_square.py")), "w")
f.writelines(square_four)
f.flush()
f.close()
# reload module, this should trigger all of the funcs / kernels to be updated
importlib.reload(test_square)
test_square.run(expect=16.0, device=device) # 4*4 = 16
def test_reload_class(test, device):
def test_func():
import warp.tests.test_class_kernel
from warp.tests.test_class_kernel import ClassKernelTest
import importlib as imp
imp.reload(warp.tests.test_class_kernel)
ctest = ClassKernelTest(device)
expected = np.zeros((10, 3, 3), dtype=np.float32)
expected[:] = np.eye(3)
assert_np_equal(expected, ctest.identities.numpy())
test_func()
test_func()
template_ref = """# 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 {} * refref.more_magic()
"""
template_refref = """# This file is used to test reloading module references.
import warp as wp
wp.init()
@wp.func
def more_magic():
return {}
"""
def test_reload_references(test, device):
path_ref = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_reference.py"))
path_refref = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_reference_reference.py"))
# rewrite both dependency modules and reload them
with open(path_ref, "w") as f:
f.writelines(template_ref.format(1.0))
importlib.reload(test_reference)
with open(path_refref, "w") as f:
f.writelines(template_refref.format(1.0))
importlib.reload(test_reference_reference)
test_dependent.run(expect=1.0, device=device) # 1 * 1 = 1
# rewrite and reload the first dependency module
with open(path_ref, "w") as f:
f.writelines(template_ref.format(2.0))
importlib.reload(test_reference)
test_dependent.run(expect=2.0, device=device) # 2 * 1 = 1
# rewrite and reload the second dependency module
with open(path_refref, "w") as f:
f.writelines(template_refref.format(2.0))
importlib.reload(test_reference_reference)
test_dependent.run(expect=4.0, device=device) # 2 * 2 = 4
def register(parent):
devices = get_test_devices()
class TestReload(parent):
pass
add_function_test(TestReload, "test_redefine", test_redefine, devices=devices)
add_function_test(TestReload, "test_reload", test_reload, devices=devices)
add_function_test(TestReload, "test_reload_class", test_reload_class, devices=devices)
add_function_test(TestReload, "test_reload_references", test_reload_references, devices=devices)
return TestReload
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_reload.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()
def test_pinned(test, device):
assert wp.get_device(device).is_cuda, "Test device must be a CUDA device"
n = 1024 * 1024
ones = np.ones(n, dtype=np.float32)
# pageable host arrays for synchronous transfers
a_pageable1 = wp.array(ones, dtype=float, device="cpu")
a_pageable2 = wp.zeros_like(a_pageable1)
assert a_pageable1.pinned == False
assert a_pageable2.pinned == False
# pinned host arrays for asynchronous transfers
a_pinned1 = wp.array(ones, dtype=float, device="cpu", pinned=True)
a_pinned2 = wp.zeros_like(a_pinned1)
assert a_pinned1.pinned == True
assert a_pinned2.pinned == True
# device array
a_device = wp.zeros(n, dtype=float, device=device)
assert a_device.pinned == False
wp.synchronize_device(device)
with wp.ScopedTimer("Synchronous copy", print=False) as pageable_timer:
wp.copy(a_device, a_pageable1)
wp.copy(a_pageable2, a_device)
wp.synchronize_device(device)
with wp.ScopedTimer("Asynchronous copy", print=False) as pinned_timer:
wp.copy(a_device, a_pinned1)
wp.copy(a_pinned2, a_device)
wp.synchronize_device(device)
# ensure correct results
assert_np_equal(a_pageable2.numpy(), ones)
assert_np_equal(a_pinned2.numpy(), ones)
# ensure that launching asynchronous transfers took less CPU time
assert pinned_timer.elapsed < pageable_timer.elapsed, "Pinned transfers did not take less CPU time"
def register(parent):
cuda_devices = wp.get_cuda_devices()
class TestPinned(parent):
pass
if cuda_devices:
add_function_test(TestPinned, "test_pinned", test_pinned, devices=cuda_devices)
return TestPinned
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_pinned.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.func
def sqr(x: float):
return x * x
# test nested user function calls
# and explicit return type hints
@wp.func
def cube(x: float) -> float:
return sqr(x) * x
@wp.func
def custom(x: int):
return x + 1
@wp.func
def custom(x: float):
return x + 1.0
@wp.func
def custom(x: wp.vec3):
return x + wp.vec3(1.0, 0.0, 0.0)
@wp.func
def noreturn(x: wp.vec3):
x = x + wp.vec3(0.0, 1.0, 0.0)
wp.expect_eq(x, wp.vec3(1.0, 1.0, 0.0))
@wp.kernel
def test_overload_func():
# tests overloading a custom @wp.func
i = custom(1)
f = custom(1.0)
v = custom(wp.vec3(1.0, 0.0, 0.0))
wp.expect_eq(i, 2)
wp.expect_eq(f, 2.0)
wp.expect_eq(v, wp.vec3(2.0, 0.0, 0.0))
noreturn(wp.vec3(1.0, 0.0, 0.0))
@wp.func
def foo(x: int):
# This shouldn't be picked up.
return x * 2
@wp.func
def foo(x: int):
return x * 3
@wp.kernel
def test_override_func():
i = foo(1)
wp.expect_eq(i, 3)
def test_native_func_export(test, device):
# tests calling native functions from Python
q = wp.quat(0.0, 0.0, 0.0, 1.0)
assert_np_equal(np.array([*q]), np.array([0.0, 0.0, 0.0, 1.0]))
r = wp.quat_from_axis_angle((1.0, 0.0, 0.0), 2.0)
assert_np_equal(np.array([*r]), np.array([0.8414709568023682, 0.0, 0.0, 0.5403022170066833]), tol=1.0e-3)
q = wp.quat(1.0, 2.0, 3.0, 4.0)
q = wp.normalize(q) * 2.0
assert_np_equal(
np.array([*q]),
np.array([0.18257418274879456, 0.3651483654975891, 0.547722578048706, 0.7302967309951782]) * 2.0,
tol=1.0e-3,
)
v2 = wp.vec2(1.0, 2.0)
v2 = wp.normalize(v2) * 2.0
assert_np_equal(np.array([*v2]), np.array([0.4472135901451111, 0.8944271802902222]) * 2.0, tol=1.0e-3)
v3 = wp.vec3(1.0, 2.0, 3.0)
v3 = wp.normalize(v3) * 2.0
assert_np_equal(
np.array([*v3]), np.array([0.26726123690605164, 0.5345224738121033, 0.8017836809158325]) * 2.0, tol=1.0e-3
)
v4 = wp.vec4(1.0, 2.0, 3.0, 4.0)
v4 = wp.normalize(v4) * 2.0
assert_np_equal(
np.array([*v4]),
np.array([0.18257418274879456, 0.3651483654975891, 0.547722578048706, 0.7302967309951782]) * 2.0,
tol=1.0e-3,
)
m22 = wp.mat22(1.0, 2.0, 3.0, 4.0)
m22 = m22 + m22
test.assertEqual(m22[1, 1], 8.0)
test.assertEqual(str(m22), "[[2.0, 4.0],\n [6.0, 8.0]]")
t = wp.transform(
wp.vec3(0.0, 0.0, 0.0),
wp.quat(0.0, 0.0, 0.0, 1.0),
)
assert_np_equal(np.array([*t]), np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]))
f = wp.sin(math.pi * 0.5)
test.assertAlmostEqual(f, 1.0, places=3)
def test_user_func_export(test, device):
# tests calling overloaded user-defined functions from Python
i = custom(1)
f = custom(1.0)
v = custom(wp.vec3(1.0, 0.0, 0.0))
test.assertEqual(i, 2)
test.assertEqual(f, 2.0)
assert_np_equal(np.array([*v]), np.array([2.0, 0.0, 0.0]))
def test_func_closure_capture(test, device):
def make_closure_kernel(func):
def closure_kernel_fn(data: wp.array(dtype=float), expected: float):
f = func(data[wp.tid()])
wp.expect_eq(f, expected)
key = f"test_func_closure_capture_{func.key}"
return wp.Kernel(func=closure_kernel_fn, key=key, module=wp.get_module(closure_kernel_fn.__module__))
sqr_closure = make_closure_kernel(sqr)
cube_closure = make_closure_kernel(cube)
data = wp.array([2.0], dtype=float, device=device)
expected_sqr = 4.0
expected_cube = 8.0
wp.launch(sqr_closure, dim=data.shape, inputs=[data, expected_sqr], device=device)
wp.launch(cube_closure, dim=data.shape, inputs=[data, expected_cube], device=device)
@wp.func
def test_func(param1: wp.int32, param2: wp.int32, param3: wp.int32) -> wp.float32:
return 1.0
@wp.kernel
def test_return_kernel(test_data: wp.array(dtype=wp.float32)):
tid = wp.tid()
test_data[tid] = wp.lerp(test_func(0, 1, 2), test_func(0, 1, 2), 0.5)
def test_return_func(test, device):
test_data = wp.zeros(100, dtype=wp.float32, device=device)
wp.launch(kernel=test_return_kernel, dim=test_data.size, inputs=[test_data], device=device)
@wp.func
def multi_valued_func(a: wp.float32, b: wp.float32):
return a + b, a - b, a * b, a / b
def test_multi_valued_func(test, device):
@wp.kernel
def test_multi_valued_kernel(test_data1: wp.array(dtype=wp.float32), test_data2: wp.array(dtype=wp.float32)):
tid = wp.tid()
d1, d2 = test_data1[tid], test_data2[tid]
a, b, c, d = multi_valued_func(d1, d2)
wp.expect_eq(a, d1 + d2)
wp.expect_eq(b, d1 - d2)
wp.expect_eq(c, d1 * d2)
wp.expect_eq(d, d1 / d2)
test_data1 = wp.array(np.arange(100), dtype=wp.float32, device=device)
test_data2 = wp.array(np.arange(100, 0, -1), dtype=wp.float32, device=device)
wp.launch(kernel=test_multi_valued_kernel, dim=test_data1.size, inputs=[test_data1, test_data2], device=device)
@wp.kernel
def test_func_defaults():
# test default as expected
wp.expect_near(1.0, 1.0 + 1.0e-6)
# test that changing tolerance still works
wp.expect_near(1.0, 1.1, 0.5)
def register(parent):
devices = get_test_devices()
class TestFunc(parent):
pass
add_kernel_test(TestFunc, kernel=test_overload_func, name="test_overload_func", dim=1, devices=devices)
add_function_test(TestFunc, func=test_return_func, name="test_return_func", devices=devices)
add_kernel_test(TestFunc, kernel=test_override_func, name="test_override_func", dim=1, devices=devices)
add_function_test(TestFunc, func=test_native_func_export, name="test_native_func_export", devices=["cpu"])
add_function_test(TestFunc, func=test_user_func_export, name="test_user_func_export", devices=["cpu"])
add_function_test(TestFunc, func=test_func_closure_capture, name="test_func_closure_capture", devices=devices)
add_function_test(TestFunc, func=test_multi_valued_func, name="test_multi_valued_func", devices=devices)
add_kernel_test(TestFunc, kernel=test_func_defaults, name="test_func_defaults", dim=1, devices=devices)
return TestFunc
if __name__ == "__main__":
c = register(unittest.TestCase)
wp.force_load()
unittest.main(verbosity=2)
| warp-main | warp/tests/test_func.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 numpy as np
import unittest
import os
import ctypes
import warp as wp
from warp.tests.test_base import *
wp.init()
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
def test_dlpack_warp_to_warp(test, device):
a1 = wp.array(data=np.arange(10, dtype=np.float32), device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1))
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a1.dtype, a2.dtype)
test.assertEqual(a1.shape, a2.shape)
test.assertEqual(a1.strides, a2.strides)
assert_np_equal(a1.numpy(), a2.numpy())
wp.launch(inc, dim=a2.size, inputs=[a2], device=device)
assert_np_equal(a1.numpy(), a2.numpy())
def test_dlpack_dtypes_and_shapes(test, device):
# automatically determine scalar dtype
def wrap_scalar_tensor_implicit(dtype):
a1 = wp.zeros(10, dtype=dtype, device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1))
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a1.dtype, a2.dtype)
test.assertEqual(a1.shape, a2.shape)
test.assertEqual(a1.strides, a2.strides)
# explicitly specify scalar dtype
def wrap_scalar_tensor_explicit(dtype, target_dtype):
a1 = wp.zeros(10, dtype=dtype, device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=target_dtype)
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a1.dtype, dtype)
test.assertEqual(a2.dtype, target_dtype)
test.assertEqual(a1.shape, a2.shape)
test.assertEqual(a1.strides, a2.strides)
# convert vector arrays to scalar arrays
def wrap_vector_to_scalar_tensor(vec_dtype):
scalar_type = vec_dtype._wp_scalar_type_
scalar_size = ctypes.sizeof(vec_dtype._type_)
a1 = wp.zeros(10, dtype=vec_dtype, device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=scalar_type)
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a2.ndim, a1.ndim + 1)
test.assertEqual(a1.dtype, vec_dtype)
test.assertEqual(a2.dtype, scalar_type)
test.assertEqual(a2.shape, (*a1.shape, vec_dtype._length_))
test.assertEqual(a2.strides, (*a1.strides, scalar_size))
# convert scalar arrays to vector arrays
def wrap_scalar_to_vector_tensor(vec_dtype):
scalar_type = vec_dtype._wp_scalar_type_
scalar_size = ctypes.sizeof(vec_dtype._type_)
a1 = wp.zeros((10, vec_dtype._length_), dtype=scalar_type, device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=vec_dtype)
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a2.ndim, a1.ndim - 1)
test.assertEqual(a1.dtype, scalar_type)
test.assertEqual(a2.dtype, vec_dtype)
test.assertEqual(a1.shape, (*a2.shape, vec_dtype._length_))
test.assertEqual(a1.strides, (*a2.strides, scalar_size))
# convert matrix arrays to scalar arrays
def wrap_matrix_to_scalar_tensor(mat_dtype):
scalar_type = mat_dtype._wp_scalar_type_
scalar_size = ctypes.sizeof(mat_dtype._type_)
a1 = wp.zeros(10, dtype=mat_dtype, device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=scalar_type)
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a2.ndim, a1.ndim + 2)
test.assertEqual(a1.dtype, mat_dtype)
test.assertEqual(a2.dtype, scalar_type)
test.assertEqual(a2.shape, (*a1.shape, *mat_dtype._shape_))
test.assertEqual(a2.strides, (*a1.strides, scalar_size * mat_dtype._shape_[1], scalar_size))
# convert scalar arrays to matrix arrays
def wrap_scalar_to_matrix_tensor(mat_dtype):
scalar_type = mat_dtype._wp_scalar_type_
scalar_size = ctypes.sizeof(mat_dtype._type_)
a1 = wp.zeros((10, *mat_dtype._shape_), dtype=scalar_type, device=device)
a2 = wp.from_dlpack(wp.to_dlpack(a1), dtype=mat_dtype)
test.assertEqual(a1.ptr, a2.ptr)
test.assertEqual(a1.device, a2.device)
test.assertEqual(a2.ndim, a1.ndim - 2)
test.assertEqual(a1.dtype, scalar_type)
test.assertEqual(a2.dtype, mat_dtype)
test.assertEqual(a1.shape, (*a2.shape, *mat_dtype._shape_))
test.assertEqual(a1.strides, (*a2.strides, scalar_size * mat_dtype._shape_[1], scalar_size))
for t in wp.types.scalar_types:
wrap_scalar_tensor_implicit(t)
for t in wp.types.scalar_types:
wrap_scalar_tensor_explicit(t, t)
# test signed/unsigned conversions
wrap_scalar_tensor_explicit(wp.int8, wp.uint8)
wrap_scalar_tensor_explicit(wp.uint8, wp.int8)
wrap_scalar_tensor_explicit(wp.int16, wp.uint16)
wrap_scalar_tensor_explicit(wp.uint16, wp.int16)
wrap_scalar_tensor_explicit(wp.int32, wp.uint32)
wrap_scalar_tensor_explicit(wp.uint32, wp.int32)
wrap_scalar_tensor_explicit(wp.int64, wp.uint64)
wrap_scalar_tensor_explicit(wp.uint64, wp.int64)
vec_types = []
for t in wp.types.scalar_types:
for vec_len in [2, 3, 4, 5]:
vec_types.append(wp.types.vector(vec_len, t))
vec_types.append(wp.quath)
vec_types.append(wp.quatf)
vec_types.append(wp.quatd)
vec_types.append(wp.transformh)
vec_types.append(wp.transformf)
vec_types.append(wp.transformd)
vec_types.append(wp.spatial_vectorh)
vec_types.append(wp.spatial_vectorf)
vec_types.append(wp.spatial_vectord)
for vec_type in vec_types:
wrap_vector_to_scalar_tensor(vec_type)
wrap_scalar_to_vector_tensor(vec_type)
mat_shapes = [(2, 2), (3, 3), (4, 4), (5, 5), (2, 3), (3, 2), (3, 4), (4, 3)]
mat_types = []
for t in wp.types.scalar_types:
for mat_shape in mat_shapes:
mat_types.append(wp.types.matrix(mat_shape, t))
mat_types.append(wp.spatial_matrixh)
mat_types.append(wp.spatial_matrixf)
mat_types.append(wp.spatial_matrixd)
for mat_type in mat_types:
wrap_matrix_to_scalar_tensor(mat_type)
wrap_scalar_to_matrix_tensor(mat_type)
def test_dlpack_warp_to_torch(test, device):
import torch.utils.dlpack
a = wp.array(data=np.arange(10, dtype=np.float32), device=device)
t = torch.utils.dlpack.from_dlpack(wp.to_dlpack(a))
item_size = wp.types.type_size_in_bytes(a.dtype)
test.assertEqual(a.ptr, t.data_ptr())
test.assertEqual(a.device, wp.device_from_torch(t.device))
test.assertEqual(a.dtype, wp.torch.dtype_from_torch(t.dtype))
test.assertEqual(a.shape, tuple(t.shape))
test.assertEqual(a.strides, tuple(s * item_size for s in t.stride()))
assert_np_equal(a.numpy(), t.cpu().numpy())
wp.launch(inc, dim=a.size, inputs=[a], device=device)
assert_np_equal(a.numpy(), t.cpu().numpy())
t += 1
assert_np_equal(a.numpy(), t.cpu().numpy())
def test_dlpack_torch_to_warp(test, device):
import torch
import torch.utils.dlpack
t = torch.arange(10, dtype=torch.float32, device=wp.device_to_torch(device))
a = wp.from_dlpack(torch.utils.dlpack.to_dlpack(t))
item_size = wp.types.type_size_in_bytes(a.dtype)
test.assertEqual(a.ptr, t.data_ptr())
test.assertEqual(a.device, wp.device_from_torch(t.device))
test.assertEqual(a.dtype, wp.torch.dtype_from_torch(t.dtype))
test.assertEqual(a.shape, tuple(t.shape))
test.assertEqual(a.strides, tuple(s * item_size for s in t.stride()))
assert_np_equal(a.numpy(), t.cpu().numpy())
wp.launch(inc, dim=a.size, inputs=[a], device=device)
assert_np_equal(a.numpy(), t.cpu().numpy())
t += 1
assert_np_equal(a.numpy(), t.cpu().numpy())
def test_dlpack_warp_to_jax(test, device):
import jax
import jax.dlpack
a = wp.array(data=np.arange(10, dtype=np.float32), device=device)
# use generic dlpack conversion
j1 = jax.dlpack.from_dlpack(wp.to_dlpack(a))
# use jax wrapper
j2 = wp.to_jax(a)
test.assertEqual(a.ptr, j1.unsafe_buffer_pointer())
test.assertEqual(a.ptr, j2.unsafe_buffer_pointer())
test.assertEqual(a.device, wp.device_from_jax(j1.device()))
test.assertEqual(a.device, wp.device_from_jax(j2.device()))
test.assertEqual(a.shape, j1.shape)
test.assertEqual(a.shape, j2.shape)
assert_np_equal(a.numpy(), np.asarray(j1))
assert_np_equal(a.numpy(), np.asarray(j2))
wp.launch(inc, dim=a.size, inputs=[a], device=device)
wp.synchronize_device(device)
# HACK? Run a no-op operation so that Jax flags the arrays as dirty
# and gets the latest values, which were modified by Warp.
j1 += 0
j2 += 0
assert_np_equal(a.numpy(), np.asarray(j1))
assert_np_equal(a.numpy(), np.asarray(j2))
def test_dlpack_jax_to_warp(test, device):
import jax
import jax.dlpack
with jax.default_device(wp.device_to_jax(device)):
j = jax.numpy.arange(10, dtype=jax.numpy.float32)
# use generic dlpack conversion
a1 = wp.from_dlpack(jax.dlpack.to_dlpack(j))
# use jax wrapper
a2 = wp.from_jax(j)
test.assertEqual(a1.ptr, j.unsafe_buffer_pointer())
test.assertEqual(a2.ptr, j.unsafe_buffer_pointer())
test.assertEqual(a1.device, wp.device_from_jax(j.device()))
test.assertEqual(a2.device, wp.device_from_jax(j.device()))
test.assertEqual(a1.shape, j.shape)
test.assertEqual(a2.shape, j.shape)
assert_np_equal(a1.numpy(), np.asarray(j))
assert_np_equal(a2.numpy(), np.asarray(j))
wp.launch(inc, dim=a1.size, inputs=[a1], device=device)
wp.synchronize_device(device)
# HACK? Run a no-op operation so that Jax flags the array as dirty
# and gets the latest values, which were modified by Warp.
j += 0
assert_np_equal(a1.numpy(), np.asarray(j))
assert_np_equal(a2.numpy(), np.asarray(j))
def register(parent):
class TestDLPack(parent):
pass
devices = get_test_devices()
add_function_test(TestDLPack, "test_dlpack_warp_to_warp", test_dlpack_warp_to_warp, devices=devices)
add_function_test(TestDLPack, "test_dlpack_dtypes_and_shapes", test_dlpack_dtypes_and_shapes, devices=devices)
# torch interop via dlpack
try:
import torch
import torch.utils.dlpack
# 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 = []
for d in test_devices:
try:
t = torch.arange(10, device=wp.device_to_torch(d))
t += 1
torch_compatible_devices.append(d)
except Exception as e:
print(f"Skipping Torch DLPack tests on device '{d}' due to exception: {e}")
if torch_compatible_devices:
add_function_test(
TestDLPack, "test_dlpack_warp_to_torch", test_dlpack_warp_to_torch, devices=torch_compatible_devices
)
add_function_test(
TestDLPack, "test_dlpack_torch_to_warp", test_dlpack_torch_to_warp, devices=torch_compatible_devices
)
except Exception as e:
print(f"Skipping Torch DLPack tests due to exception: {e}")
# jax interop via dlpack
try:
# prevent Jax from gobbling up GPU memory
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
import jax
import jax.dlpack
# check which Warp devices work with Jax
# CUDA devices may fail if Jax cannot find a CUDA Toolkit
test_devices = get_test_devices()
jax_compatible_devices = []
for d in test_devices:
try:
with jax.default_device(wp.device_to_jax(d)):
j = jax.numpy.arange(10, dtype=jax.numpy.float32)
j += 1
jax_compatible_devices.append(d)
except Exception as e:
print(f"Skipping Jax DLPack tests on device '{d}' due to exception: {e}")
if jax_compatible_devices:
add_function_test(
TestDLPack, "test_dlpack_warp_to_jax", test_dlpack_warp_to_jax, devices=jax_compatible_devices
)
add_function_test(
TestDLPack, "test_dlpack_jax_to_warp", test_dlpack_jax_to_warp, devices=jax_compatible_devices
)
except Exception as e:
print(f"Skipping Jax DLPack tests due to exception: {e}")
return TestDLPack
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_dlpack.py |
import numpy as np
import math
import warp as wp
from warp.tests.test_base import *
import unittest
wp.init()
@wp.kernel
def eval_dense_gemm(
m: int,
n: int,
p: int,
t1: int,
t2: int,
A: wp.array(dtype=float),
B: wp.array(dtype=float),
C: wp.array(dtype=float),
):
wp.dense_gemm(m, n, p, t1, t2, A, B, C)
@wp.kernel
def eval_dense_cholesky(n: int, A: wp.array(dtype=float), regularization: float, L: wp.array(dtype=float)):
wp.dense_chol(n, A, regularization, L)
@wp.kernel
def eval_dense_subs(n: int, L: wp.array(dtype=float), b: wp.array(dtype=float), x: wp.array(dtype=float)):
wp.dense_subs(n, L, b, x)
# helper that propagates gradients back to A, treating L as a constant / temporary variable
# allows us to reuse the Cholesky decomposition from the forward pass
@wp.kernel
def eval_dense_solve(
n: int, A: wp.array(dtype=float), L: wp.array(dtype=float), b: wp.array(dtype=float), x: wp.array(dtype=float)
):
wp.dense_solve(n, A, L, b, x)
def register(parent):
devices = get_test_devices()
class TestDense(parent):
pass
# just testing compilation of the dense matrix routines
# most are deprecated / WIP
wp.force_load()
return TestDense
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_dense.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
from typing import Any
import numpy as np
import warp as wp
from warp.tests.test_array import FillStruct
from warp.tests.test_base import *
wp.init()
@wp.kernel
def kernel_1d(a: wp.indexedarray(dtype=float), expected: wp.array(dtype=float)):
i = wp.tid()
wp.expect_eq(a[i], expected[i])
a[i] = 2.0 * a[i]
wp.atomic_add(a, i, 1.0)
wp.expect_eq(a[i], 2.0 * expected[i] + 1.0)
def test_indexedarray_1d(test, device):
values = np.arange(10, dtype=np.float32)
arr = wp.array(data=values, device=device)
indices = wp.array([1, 3, 5, 7, 9], dtype=int, device=device)
iarr = wp.indexedarray(arr, [indices])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 1)
test.assertEqual(iarr.shape, (5,))
test.assertEqual(iarr.size, 5)
expected_arr = wp.array(data=[1, 3, 5, 7, 9], dtype=float, device=device)
wp.launch(kernel_1d, dim=iarr.size, inputs=[iarr, expected_arr], device=device)
@wp.kernel
def kernel_2d(a: wp.indexedarray2d(dtype=float), expected: wp.array2d(dtype=float)):
i, j = wp.tid()
# check expected values
wp.expect_eq(a[i, j], expected[i, j])
# test wp.view()
wp.expect_eq(a[i][j], a[i, j])
a[i, j] = 2.0 * a[i, j]
wp.atomic_add(a, i, j, 1.0)
wp.expect_eq(a[i, j], 2.0 * expected[i, j] + 1.0)
def test_indexedarray_2d(test, device):
values = np.arange(100, dtype=np.float32).reshape((10, 10))
arr = wp.array(data=values, device=device)
indices0 = wp.array([1, 3], dtype=int, device=device)
indices1 = wp.array([2, 4, 8], dtype=int, device=device)
iarr = wp.indexedarray(arr, [indices0, indices1])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 2)
test.assertEqual(iarr.shape, (2, 3))
test.assertEqual(iarr.size, 6)
expected_values = [[12, 14, 18], [32, 34, 38]]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_2d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
@wp.kernel
def kernel_3d(a: wp.indexedarray3d(dtype=float), expected: wp.array3d(dtype=float)):
i, j, k = wp.tid()
# check expected values
wp.expect_eq(a[i, j, k], expected[i, j, k])
# test wp.view()
wp.expect_eq(a[i][j][k], a[i, j, k])
wp.expect_eq(a[i, j][k], a[i, j, k])
wp.expect_eq(a[i][j, k], a[i, j, k])
a[i, j, k] = 2.0 * a[i, j, k]
wp.atomic_add(a, i, j, k, 1.0)
wp.expect_eq(a[i, j, k], 2.0 * expected[i, j, k] + 1.0)
def test_indexedarray_3d(test, device):
values = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))
arr = wp.array(data=values, device=device)
indices0 = wp.array([1, 3], dtype=int, device=device)
indices1 = wp.array([2, 4, 8], dtype=int, device=device)
indices2 = wp.array([0, 5], dtype=int, device=device)
iarr = wp.indexedarray(arr, [indices0, indices1, indices2])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 3)
test.assertEqual(iarr.shape, (2, 3, 2))
test.assertEqual(iarr.size, 12)
expected_values = [
[[120, 125], [140, 145], [180, 185]],
[[320, 325], [340, 345], [380, 385]],
]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_3d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
@wp.kernel
def kernel_4d(a: wp.indexedarray4d(dtype=float), expected: wp.array4d(dtype=float)):
i, j, k, l = wp.tid()
# check expected values
wp.expect_eq(a[i, j, k, l], expected[i, j, k, l])
# test wp.view()
wp.expect_eq(a[i][j][k][l], a[i, j, k, l])
wp.expect_eq(a[i][j, k, l], a[i, j, k, l])
wp.expect_eq(a[i, j][k, l], a[i, j, k, l])
wp.expect_eq(a[i, j, k][l], a[i, j, k, l])
a[i, j, k, l] = 2.0 * a[i, j, k, l]
wp.atomic_add(a, i, j, k, l, 1.0)
wp.expect_eq(a[i, j, k, l], 2.0 * expected[i, j, k, l] + 1.0)
def test_indexedarray_4d(test, device):
values = np.arange(10000, dtype=np.float32).reshape((10, 10, 10, 10))
arr = wp.array(data=values, device=device)
indices0 = wp.array([1, 3], dtype=int, device=device)
indices1 = wp.array([2, 4, 8], dtype=int, device=device)
indices2 = wp.array([0, 5], dtype=int, device=device)
indices3 = wp.array([6, 7, 9], dtype=int, device=device)
iarr = wp.indexedarray(arr, [indices0, indices1, indices2, indices3])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 4)
test.assertEqual(iarr.shape, (2, 3, 2, 3))
test.assertEqual(iarr.size, 36)
expected_values = [
[
[[1206, 1207, 1209], [1256, 1257, 1259]],
[[1406, 1407, 1409], [1456, 1457, 1459]],
[[1806, 1807, 1809], [1856, 1857, 1859]],
],
[
[[3206, 3207, 3209], [3256, 3257, 3259]],
[[3406, 3407, 3409], [3456, 3457, 3459]],
[[3806, 3807, 3809], [3856, 3857, 3859]],
],
]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_4d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
def test_indexedarray_mixed(test, device):
# [[[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [12, 13, 14, 15]],
# [[16, 17, 18, 19],
# [20, 21, 22, 23],
# [24, 25, 26, 27],
# [28, 29, 30, 31]],
# [[32, 33, 34, 35],
# [36, 37, 38, 39],
# [40, 41, 42, 43],
# [44, 45, 46, 47],
# [[48, 49, 50, 51],
# [52, 53, 54, 55],
# [56, 57, 58, 59],
# [60, 61, 62, 63]]]]
values = np.arange(64, dtype=np.float32).reshape((4, 4, 4))
indices = wp.array([0, 3], dtype=int, device=device)
# -----
arr = wp.array(data=values, device=device)
iarr = wp.indexedarray(arr, [indices, None, None])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 3)
test.assertEqual(iarr.shape, (2, 4, 4))
test.assertEqual(iarr.size, 32)
expected_values = [
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]],
[[48, 49, 50, 51], [52, 53, 54, 55], [56, 57, 58, 59], [60, 61, 62, 63]],
]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_3d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
# -----
arr = wp.array(data=values, device=device)
iarr = wp.indexedarray(arr, [indices, indices, None])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 3)
test.assertEqual(iarr.shape, (2, 2, 4))
test.assertEqual(iarr.size, 16)
expected_values = [[[0, 1, 2, 3], [12, 13, 14, 15]], [[48, 49, 50, 51], [60, 61, 62, 63]]]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_3d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
# -----
arr = wp.array(data=values, device=device)
iarr = wp.indexedarray(arr, [indices, None, indices])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 3)
test.assertEqual(iarr.shape, (2, 4, 2))
test.assertEqual(iarr.size, 16)
expected_values = [[[0, 3], [4, 7], [8, 11], [12, 15]], [[48, 51], [52, 55], [56, 59], [60, 63]]]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_3d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
# -----
arr = wp.array(data=values, device=device)
iarr = wp.indexedarray(arr, [None, indices, indices])
test.assertEqual(iarr.dtype, arr.dtype)
test.assertEqual(iarr.ndim, 3)
test.assertEqual(iarr.shape, (4, 2, 2))
test.assertEqual(iarr.size, 16)
expected_values = [[[0, 3], [12, 15]], [[16, 19], [28, 31]], [[32, 35], [44, 47]], [[48, 51], [60, 63]]]
expected_arr = wp.array(data=expected_values, dtype=float, device=device)
wp.launch(kernel_3d, dim=iarr.shape, inputs=[iarr, expected_arr], device=device)
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)
@wp.kernel
def shape_kernel_1d(arr: wp.indexedarray1d(dtype=float), expected: int):
wp.expect_eq(arr.shape[0], expected)
@wp.kernel
def shape_kernel_2d(arr: wp.indexedarray2d(dtype=float), expected: vec2i):
wp.expect_eq(arr.shape[0], expected[0])
wp.expect_eq(arr.shape[1], expected[1])
# 1d slice
view = arr[0]
wp.expect_eq(view.shape[0], expected[1])
@wp.kernel
def shape_kernel_3d(arr: wp.indexedarray3d(dtype=float), expected: vec3i):
wp.expect_eq(arr.shape[0], expected[0])
wp.expect_eq(arr.shape[1], expected[1])
wp.expect_eq(arr.shape[2], expected[2])
# 2d slice
view2 = arr[0]
wp.expect_eq(view2.shape[0], expected[1])
wp.expect_eq(view2.shape[1], expected[2])
# 1d slice
view1 = arr[0, 0]
wp.expect_eq(view1.shape[0], expected[2])
@wp.kernel
def shape_kernel_4d(arr: wp.indexedarray4d(dtype=float), expected: vec4i):
wp.expect_eq(arr.shape[0], expected[0])
wp.expect_eq(arr.shape[1], expected[1])
wp.expect_eq(arr.shape[2], expected[2])
wp.expect_eq(arr.shape[3], expected[3])
# 3d slice
view3 = arr[0]
wp.expect_eq(view3.shape[0], expected[1])
wp.expect_eq(view3.shape[1], expected[2])
wp.expect_eq(view3.shape[2], expected[3])
# 2d slice
view2 = arr[0, 0]
wp.expect_eq(view2.shape[0], expected[2])
wp.expect_eq(view2.shape[1], expected[3])
# 1d slice
view1 = arr[0, 0, 0]
wp.expect_eq(view1.shape[0], expected[3])
def test_indexedarray_shape(test, device):
with wp.ScopedDevice(device):
data1 = wp.zeros(10, dtype=float)
data2 = wp.zeros((10, 20), dtype=float)
data3 = wp.zeros((10, 20, 30), dtype=float)
data4 = wp.zeros((10, 20, 30, 40), dtype=float)
indices1 = wp.array(data=[2, 7], dtype=int)
indices2 = wp.array(data=[2, 7, 12, 17], dtype=int)
indices3 = wp.array(data=[2, 7, 12, 17, 22, 27], dtype=int)
indices4 = wp.array(data=[2, 7, 12, 17, 22, 27, 32, 37], dtype=int)
ia1 = wp.indexedarray(data1, [indices1])
wp.launch(shape_kernel_1d, dim=1, inputs=[ia1, 2])
ia2_1 = wp.indexedarray(data2, [indices1, None])
ia2_2 = wp.indexedarray(data2, [None, indices2])
ia2_3 = wp.indexedarray(data2, [indices1, indices2])
wp.launch(shape_kernel_2d, dim=1, inputs=[ia2_1, vec2i(2, 20)])
wp.launch(shape_kernel_2d, dim=1, inputs=[ia2_2, vec2i(10, 4)])
wp.launch(shape_kernel_2d, dim=1, inputs=[ia2_3, vec2i(2, 4)])
ia3_1 = wp.indexedarray(data3, [indices1, None, None])
ia3_2 = wp.indexedarray(data3, [None, indices2, None])
ia3_3 = wp.indexedarray(data3, [None, None, indices3])
ia3_4 = wp.indexedarray(data3, [indices1, indices2, None])
ia3_5 = wp.indexedarray(data3, [indices1, None, indices3])
ia3_6 = wp.indexedarray(data3, [None, indices2, indices3])
ia3_7 = wp.indexedarray(data3, [indices1, indices2, indices3])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_1, vec3i(2, 20, 30)])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_2, vec3i(10, 4, 30)])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_3, vec3i(10, 20, 6)])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_4, vec3i(2, 4, 30)])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_5, vec3i(2, 20, 6)])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_6, vec3i(10, 4, 6)])
wp.launch(shape_kernel_3d, dim=1, inputs=[ia3_7, vec3i(2, 4, 6)])
ia4_1 = wp.indexedarray(data4, [indices1, None, None, None])
ia4_2 = wp.indexedarray(data4, [indices1, None, None, indices4])
ia4_3 = wp.indexedarray(data4, [None, indices2, indices3, None])
ia4_4 = wp.indexedarray(data4, [indices1, indices2, indices3, indices4])
wp.launch(shape_kernel_4d, dim=1, inputs=[ia4_1, vec4i(2, 20, 30, 40)])
wp.launch(shape_kernel_4d, dim=1, inputs=[ia4_2, vec4i(2, 20, 30, 8)])
wp.launch(shape_kernel_4d, dim=1, inputs=[ia4_3, vec4i(10, 4, 6, 40)])
wp.launch(shape_kernel_4d, dim=1, inputs=[ia4_4, vec4i(2, 4, 6, 8)])
wp.synchronize_device(device)
def test_indexedarray_getitem(test, device):
with wp.ScopedDevice(device):
data = wp.array(data=np.arange(1000, dtype=np.int32).reshape((10, 10, 10)))
I = wp.array(data=[0, 1, 2], dtype=int)
# use constructor
a1 = wp.indexedarray(data, [None, None, I])
a2 = wp.indexedarray(data, [None, I])
a3 = wp.indexedarray(data, [None, I, I])
a4 = wp.indexedarray(data, [I])
a5 = wp.indexedarray(data, [I, None, I])
a6 = wp.indexedarray(data, [I, I])
a7 = wp.indexedarray(data, [I, I, I])
# use array.__getitem__()
b1 = data[:, :, I]
b2 = data[:, I]
b3 = data[:, I, I]
b4 = data[I]
b5 = data[I, :, I]
b6 = data[I, I]
b7 = data[I, I, I]
test.assertEqual(type(a1), type(b1))
test.assertEqual(type(a2), type(b2))
test.assertEqual(type(a3), type(b3))
test.assertEqual(type(a4), type(b4))
test.assertEqual(type(a5), type(b5))
test.assertEqual(type(a6), type(b6))
test.assertEqual(type(a7), type(b7))
assert_np_equal(a1.numpy(), b1.numpy())
assert_np_equal(a2.numpy(), b2.numpy())
assert_np_equal(a3.numpy(), b3.numpy())
assert_np_equal(a4.numpy(), b4.numpy())
assert_np_equal(a5.numpy(), b5.numpy())
assert_np_equal(a6.numpy(), b6.numpy())
assert_np_equal(a7.numpy(), b7.numpy())
def test_indexedarray_slicing(test, device):
with wp.ScopedDevice(device):
data = wp.array(data=np.arange(1000, dtype=np.int32).reshape((10, 10, 10)))
# test equivalence of slicing and indexing the same range
s = slice(0, 3)
I = wp.array(data=[0, 1, 2], dtype=int)
a0 = data[s, s, s]
test.assertEqual(type(a0), wp.array)
a1 = data[s, s, I]
test.assertEqual(type(a1), wp.indexedarray)
a2 = data[s, I, s]
test.assertEqual(type(a2), wp.indexedarray)
a3 = data[s, I, I]
test.assertEqual(type(a3), wp.indexedarray)
a4 = data[I, s, s]
test.assertEqual(type(a4), wp.indexedarray)
a5 = data[I, s, I]
test.assertEqual(type(a5), wp.indexedarray)
a6 = data[I, I, s]
test.assertEqual(type(a6), wp.indexedarray)
a7 = data[I, I, I]
test.assertEqual(type(a7), wp.indexedarray)
expected = a0.numpy()
assert_np_equal(a1.numpy(), expected)
assert_np_equal(a2.numpy(), expected)
assert_np_equal(a3.numpy(), expected)
assert_np_equal(a4.numpy(), expected)
assert_np_equal(a5.numpy(), expected)
assert_np_equal(a6.numpy(), expected)
assert_np_equal(a7.numpy(), expected)
# generic increment kernels that work with any array (regular or indexed)
@wp.kernel
def inc_1d(a: Any):
i = wp.tid()
a[i] = a[i] + 1
@wp.kernel
def inc_2d(a: Any):
i, j = wp.tid()
a[i, j] = a[i, j] + 1
@wp.kernel
def inc_3d(a: Any):
i, j, k = wp.tid()
a[i, j, k] = a[i, j, k] + 1
@wp.kernel
def inc_4d(a: Any):
i, j, k, l = wp.tid()
a[i, j, k, l] = a[i, j, k, l] + 1
# optional overloads to avoid module reloading
wp.overload(inc_1d, [wp.array1d(dtype=int)])
wp.overload(inc_2d, [wp.array2d(dtype=int)])
wp.overload(inc_3d, [wp.array3d(dtype=int)])
wp.overload(inc_4d, [wp.array4d(dtype=int)])
wp.overload(inc_1d, [wp.indexedarray1d(dtype=int)])
wp.overload(inc_2d, [wp.indexedarray2d(dtype=int)])
wp.overload(inc_3d, [wp.indexedarray3d(dtype=int)])
wp.overload(inc_4d, [wp.indexedarray4d(dtype=int)])
def test_indexedarray_generics(test, device):
with wp.ScopedDevice(device):
data1 = wp.zeros((5,), dtype=int)
data2 = wp.zeros((5, 5), dtype=int)
data3 = wp.zeros((5, 5, 5), dtype=int)
data4 = wp.zeros((5, 5, 5, 5), dtype=int)
indices = wp.array(data=[0, 4], dtype=int)
ia1 = wp.indexedarray(data1, [indices])
ia2 = wp.indexedarray(data2, [indices, indices])
ia3 = wp.indexedarray(data3, [indices, indices, indices])
ia4 = wp.indexedarray(data4, [indices, indices, indices, indices])
wp.launch(inc_1d, dim=data1.shape, inputs=[data1])
wp.launch(inc_2d, dim=data2.shape, inputs=[data2])
wp.launch(inc_3d, dim=data3.shape, inputs=[data3])
wp.launch(inc_4d, dim=data4.shape, inputs=[data4])
wp.launch(inc_1d, dim=ia1.shape, inputs=[ia1])
wp.launch(inc_2d, dim=ia2.shape, inputs=[ia2])
wp.launch(inc_3d, dim=ia3.shape, inputs=[ia3])
wp.launch(inc_4d, dim=ia4.shape, inputs=[ia4])
expected1 = np.ones(5, dtype=np.int32)
expected1[0] = 2
expected1[4] = 2
expected2 = np.ones((5, 5), dtype=np.int32)
expected2[0, 0] = 2
expected2[0, 4] = 2
expected2[4, 0] = 2
expected2[4, 4] = 2
expected3 = np.ones((5, 5, 5), dtype=np.int32)
expected3[0, 0, 0] = 2
expected3[0, 0, 4] = 2
expected3[0, 4, 0] = 2
expected3[0, 4, 4] = 2
expected3[4, 0, 0] = 2
expected3[4, 0, 4] = 2
expected3[4, 4, 0] = 2
expected3[4, 4, 4] = 2
expected4 = np.ones((5, 5, 5, 5), dtype=np.int32)
expected4[0, 0, 0, 0] = 2
expected4[0, 0, 0, 4] = 2
expected4[0, 0, 4, 0] = 2
expected4[0, 0, 4, 4] = 2
expected4[0, 4, 0, 0] = 2
expected4[0, 4, 0, 4] = 2
expected4[0, 4, 4, 0] = 2
expected4[0, 4, 4, 4] = 2
expected4[4, 0, 0, 0] = 2
expected4[4, 0, 0, 4] = 2
expected4[4, 0, 4, 0] = 2
expected4[4, 0, 4, 4] = 2
expected4[4, 4, 0, 0] = 2
expected4[4, 4, 0, 4] = 2
expected4[4, 4, 4, 0] = 2
expected4[4, 4, 4, 4] = 2
assert_np_equal(data1.numpy(), expected1)
assert_np_equal(data2.numpy(), expected2)
assert_np_equal(data3.numpy(), expected3)
assert_np_equal(data4.numpy(), expected4)
assert_np_equal(ia1.numpy(), np.full((2,), 2, dtype=np.int32))
assert_np_equal(ia2.numpy(), np.full((2, 2), 2, dtype=np.int32))
assert_np_equal(ia3.numpy(), np.full((2, 2, 2), 2, dtype=np.int32))
assert_np_equal(ia4.numpy(), np.full((2, 2, 2, 2), 2, dtype=np.int32))
def test_indexedarray_empty(test, device):
# Test whether common operations work with empty (zero-sized) indexed arrays
# without throwing exceptions.
def test_empty_ops(ndim, nrows, ncols, wptype, nptype):
data_shape = (1,) * 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 data array
data = wp.empty(data_shape, dtype=wptype, device=device, requires_grad=True)
# create a zero-sized array of indices
indices = wp.empty(0, dtype=int, device=device)
a = data[indices]
# we expect dim to be zero for the empty indexed array, unchanged otherwise
expected_shape = (0, *data_shape[1:])
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, expected_shape)
# all of these methods should succeed with zero-sized arrays
a.zero_()
a.fill_(fill_value)
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, (*expected_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_indexedarray_fill_scalar(test, device):
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
data1 = wp.zeros(dim_x, dtype=wptype, device=device)
data2 = wp.zeros((dim_x, dim_x), dtype=wptype, device=device)
data3 = wp.zeros((dim_x, dim_x, dim_x), dtype=wptype, device=device)
data4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=wptype, device=device)
indices = wp.array(np.arange(0, dim_x, 2, dtype=np.int32), device=device)
a1 = data1[indices]
a2 = data2[indices]
a3 = data3[indices]
a4 = data4[indices]
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_indexedarray_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_
data1 = wp.zeros(dim_x, dtype=vec_type, device=device)
data2 = wp.zeros((dim_x, dim_x), dtype=vec_type, device=device)
data3 = wp.zeros((dim_x, dim_x, dim_x), dtype=vec_type, device=device)
data4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=vec_type, device=device)
indices = wp.array(np.arange(0, dim_x, 2, dtype=np.int32), device=device)
a1 = data1[indices]
a2 = data2[indices]
a3 = data3[indices]
a4 = data4[indices]
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_indexedarray_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_
data1 = wp.zeros(dim_x, dtype=mat_type, device=device)
data2 = wp.zeros((dim_x, dim_x), dtype=mat_type, device=device)
data3 = wp.zeros((dim_x, dim_x, dim_x), dtype=mat_type, device=device)
data4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=mat_type, device=device)
indices = wp.array(np.arange(0, dim_x, 2, dtype=np.int32), device=device)
a1 = data1[indices]
a2 = data2[indices]
a3 = data3[indices]
a4 = data4[indices]
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)
def test_indexedarray_fill_struct(test, device):
dim_x = 8
nptype = FillStruct.numpy_dtype()
data1 = wp.zeros(dim_x, dtype=FillStruct, device=device)
data2 = wp.zeros((dim_x, dim_x), dtype=FillStruct, device=device)
data3 = wp.zeros((dim_x, dim_x, dim_x), dtype=FillStruct, device=device)
data4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=FillStruct, device=device)
indices = wp.array(np.arange(0, dim_x, 2, dtype=np.int32), device=device)
a1 = data1[indices]
a2 = data2[indices]
a3 = data3[indices]
a4 = data4[indices]
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 register(parent):
devices = get_test_devices()
class TestIndexedArray(parent):
pass
add_function_test(TestIndexedArray, "test_indexedarray_1d", test_indexedarray_1d, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_2d", test_indexedarray_2d, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_3d", test_indexedarray_3d, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_4d", test_indexedarray_4d, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_mixed", test_indexedarray_mixed, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_shape", test_indexedarray_shape, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_getitem", test_indexedarray_getitem, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_slicing", test_indexedarray_slicing, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_generics", test_indexedarray_generics, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_empty", test_indexedarray_empty, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_fill_scalar", test_indexedarray_fill_scalar, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_fill_vector", test_indexedarray_fill_vector, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_fill_matrix", test_indexedarray_fill_matrix, devices=devices)
add_function_test(TestIndexedArray, "test_indexedarray_fill_struct", test_indexedarray_fill_struct, devices=devices)
return TestIndexedArray
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_indexedarray.py |
import warp as wp
@wp.kernel
def unresolved_symbol_kernel():
# this should trigger an exception due to unresolved symbol
x = missing_symbol
| warp-main | warp/tests/test_unresolved_symbol.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 test_arrays(test, device, dtype):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
np.random.seed(123)
v2_np = randvals([10, 2, 2], dtype)
v3_np = randvals([10, 3, 3], dtype)
v4_np = randvals([10, 4, 4], dtype)
v5_np = randvals([10, 5, 5], dtype)
v32_np = randvals([10, 3, 2], dtype)
v2 = wp.array(v2_np, dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(v3_np, dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(v4_np, dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(v5_np, dtype=mat55, requires_grad=True, device=device)
v32 = wp.array(v32_np, dtype=mat32, 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)
assert_np_equal(v32.numpy(), v32_np, tol=1.0e-6)
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
v2 = wp.array(v2_np, dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(v3_np, dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(v4_np, dtype=mat44, 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 matrix 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)]
mat23 = wp.types.matrix(shape=(2, 3), dtype=wptype)
m = mat23(1, 2, 3, 4, 5, 6)
# test __getitem__ for row vectors
r0 = m[0]
r1 = m[1]
test.assertEqual(r0[0], 1)
test.assertEqual(r0[1], 2)
test.assertEqual(r0[2], 3)
test.assertEqual(r1[0], 4)
test.assertEqual(r1[1], 5)
test.assertEqual(r1[2], 6)
# test __getitem__ for individual components
test.assertEqual(m[0, 0], 1)
test.assertEqual(m[0, 1], 2)
test.assertEqual(m[0, 2], 3)
test.assertEqual(m[1, 0], 4)
test.assertEqual(m[1, 1], 5)
test.assertEqual(m[1, 2], 6)
# test __setitem__ for row vectors
m[0] = [7, 8, 9]
m[1] = [10, 11, 12]
test.assertEqual(m[0, 0], 7)
test.assertEqual(m[0, 1], 8)
test.assertEqual(m[0, 2], 9)
test.assertEqual(m[1, 0], 10)
test.assertEqual(m[1, 1], 11)
test.assertEqual(m[1, 2], 12)
# test __setitem__ for individual components
m[0, 0] = 13
m[0, 1] = 14
m[0, 2] = 15
m[1, 0] = 16
m[1, 1] = 17
m[1, 2] = 18
test.assertEqual(m[0, 0], 13)
test.assertEqual(m[0, 1], 14)
test.assertEqual(m[0, 2], 15)
test.assertEqual(m[1, 0], 16)
test.assertEqual(m[1, 1], 17)
test.assertEqual(m[1, 2], 18)
def test_constants(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
cm22 = wp.constant(mat22(22))
cm33 = wp.constant(mat33(33))
cm44 = wp.constant(mat44(44))
cm55 = wp.constant(mat55(55))
cm32 = wp.constant(mat32(32))
def check_matrix_constants():
wp.expect_eq(cm22, mat22(wptype(22)))
wp.expect_eq(cm33, mat33(wptype(33)))
wp.expect_eq(cm44, mat44(wptype(44)))
wp.expect_eq(cm55, mat55(wptype(55)))
wp.expect_eq(cm32, mat32(wptype(32)))
kernel = getkernel(check_matrix_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: 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)
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_scalar_mat_constructor(
input: wp.array(dtype=wptype),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m2result = wptype(2) * mat22(input[0])
m3result = wptype(2) * mat33(input[0])
m4result = wptype(2) * mat44(input[0])
m5result = wptype(2) * mat55(input[0])
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m5result[i, j]
idx = idx + 1
def check_component_mat_constructor(
input: wp.array(dtype=wptype),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m2result = wptype(2) * mat22(input[0], input[1], input[2], input[3])
m3result = wptype(2) * mat33(
input[4],
input[5],
input[6],
input[7],
input[8],
input[9],
input[10],
input[11],
input[12],
)
m4result = wptype(2) * mat44(
input[13],
input[14],
input[15],
input[16],
input[17],
input[18],
input[19],
input[20],
input[21],
input[22],
input[23],
input[24],
input[25],
input[26],
input[27],
input[28],
)
m5result = wptype(2) * mat55(
input[29],
input[30],
input[31],
input[32],
input[33],
input[34],
input[35],
input[36],
input[37],
input[38],
input[39],
input[40],
input[41],
input[42],
input[43],
input[44],
input[45],
input[46],
input[47],
input[48],
input[49],
input[50],
input[51],
input[52],
input[53],
)
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m5result[i, j]
idx = idx + 1
def check_vector_mat_constructor(
input: wp.array(dtype=wptype),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m2result = wptype(2) * mat22(vec2(input[0], input[2]), vec2(input[1], input[3]))
m3result = wptype(2) * mat33(
vec3(input[4], input[7], input[10]),
vec3(input[5], input[8], input[11]),
vec3(input[6], input[9], input[12]),
)
m4result = wptype(2) * mat44(
vec4(input[13], input[17], input[21], input[25]),
vec4(input[14], input[18], input[22], input[26]),
vec4(input[15], input[19], input[23], input[27]),
vec4(input[16], input[20], input[24], input[28]),
)
m5result = wptype(2) * mat55(
vec5(input[29], input[34], input[39], input[44], input[49]),
vec5(input[30], input[35], input[40], input[45], input[50]),
vec5(input[31], input[36], input[41], input[46], input[51]),
vec5(input[32], input[37], input[42], input[47], input[52]),
vec5(input[33], input[38], input[43], input[48], input[53]),
)
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m5result[i, j]
idx = idx + 1
kernel = getkernel(check_scalar_mat_constructor, suffix=dtype.__name__)
compkernel = getkernel(check_component_mat_constructor, suffix=dtype.__name__)
veckernel = getkernel(check_vector_mat_constructor, suffix=dtype.__name__)
if register_kernels:
return
input = wp.array(randvals([1], dtype), requires_grad=True, device=device)
val = input.numpy()[0]
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * val * np.ones(2 * 2), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * val * np.ones(3 * 3), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * val * np.ones(4 * 4), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * val * np.ones(5 * 5), tol=tol)
if dtype in np_float_types:
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
test.assertEqual(tape.gradients[input].numpy()[0], 2)
tape.zero()
input = wp.array(randvals([2 * 2 + 3 * 3 + 4 * 4 + 5 * 5], dtype), requires_grad=True, device=device)
wp.launch(compkernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
assert_np_equal(2 * input.numpy(), outcomponents.numpy(), tol=10 * tol)
if dtype in np_float_types:
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(compkernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedgrads = np.zeros(len(input))
expectedgrads[idx] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
wp.launch(veckernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
assert_np_equal(2 * input.numpy(), outcomponents.numpy(), tol=10 * tol)
if dtype in np_float_types:
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(veckernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedgrads = np.zeros(len(input))
expectedgrads[idx] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
def test_quat_constructor(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)]
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
quat = wp.types.quaternion(dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_quat_constructor(
p: wp.array(dtype=vec3),
r: wp.array(dtype=quat),
s: wp.array(dtype=vec3),
outcomponents: wp.array(dtype=wptype),
outcomponents_alt: wp.array(dtype=wptype),
):
m = mat44(p[0], r[0], s[0])
R = wp.transpose(wp.quat_to_matrix(r[0]))
c0 = s[0][0] * R[0]
c1 = s[0][1] * R[1]
c2 = s[0][2] * R[2]
m_alt = mat44(
vec4(c0[0], c0[1], c0[2], wptype(0.0)),
vec4(c1[0], c1[1], c1[2], wptype(0.0)),
vec4(c2[0], c2[1], c2[2], wptype(0.0)),
vec4(p[0][0], p[0][1], p[0][2], wptype(1.0)),
)
idx = 0
for i in range(4):
for j in range(4):
outcomponents[idx] = m[i, j]
outcomponents_alt[idx] = m_alt[i, j]
idx = idx + 1
kernel = getkernel(check_mat_quat_constructor, suffix=dtype.__name__)
if register_kernels:
return
# translation:
p = wp.array(np.random.randn(1, 3).astype(dtype), dtype=vec3, requires_grad=True, device=device)
# generate a normalized quaternion for the rotation:
r = np.random.randn(1, 4)
r /= np.linalg.norm(r)
r = wp.array(r.astype(dtype), dtype=quat, requires_grad=True, device=device)
# scale:
s = wp.array(np.random.randn(1, 3).astype(dtype), dtype=vec3, requires_grad=True, device=device)
# just going to generate the matrix using the constructor, then
# more manually, and make sure the values/gradients are the same:
outcomponents = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
outcomponents_alt = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
assert_np_equal(outcomponents.numpy(), outcomponents_alt.numpy(), tol=1.0e-6)
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
out_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(4):
for j in range(4):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents_alt, idx], outputs=[out_alt], device=device
)
tape.backward(loss=out)
p_grad = 1.0 * tape.gradients[p].numpy()[0]
r_grad = 1.0 * tape.gradients[r].numpy()[0]
s_grad = 1.0 * tape.gradients[s].numpy()[0]
tape.zero()
tape.backward(loss=out_alt)
p_grad_alt = 1.0 * tape.gradients[p].numpy()[0]
r_grad_alt = 1.0 * tape.gradients[r].numpy()[0]
s_grad_alt = 1.0 * tape.gradients[s].numpy()[0]
tape.zero()
assert_np_equal(p_grad, p_grad_alt, tol=tol)
assert_np_equal(r_grad, r_grad_alt, tol=tol)
assert_np_equal(s_grad, s_grad_alt, tol=tol)
idx = idx + 1
def test_indexing(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_indexing(
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2[0][i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3[0][i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4[0][i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5[0][i, j]
idx = idx + 1
kernel = getkernel(check_mat_indexing, suffix=dtype.__name__)
if register_kernels:
return
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * m3.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * m4.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * m5.numpy().reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
def check_mat_equality():
wp.expect_eq(
mat22(wptype(1.0), wptype(2.0), wptype(3.0), wptype(4.0)),
mat22(wptype(1.0), wptype(2.0), wptype(3.0), wptype(4.0)),
)
wp.expect_neq(
mat22(wptype(1.0), wptype(2.0), wptype(3.0), -wptype(4.0)),
mat22(wptype(1.0), wptype(2.0), wptype(3.0), wptype(4.0)),
)
wp.expect_eq(
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
)
wp.expect_neq(
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
-wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
)
wp.expect_eq(
mat44(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
mat44(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
)
wp.expect_neq(
mat44(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
mat44(
-wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
)
wp.expect_eq(
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
)
wp.expect_neq(
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
-wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
)
kernel = getkernel(check_mat_equality, suffix=dtype.__name__)
if register_kernels:
return
wp.launch(kernel, dim=1, inputs=[], outputs=[], device=device)
def test_negation(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_negation(
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
mat2 = -m2[0]
mat3 = -m3[0]
mat4 = -m4[0]
mat5 = -m5[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * mat2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * mat3[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * mat4[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * mat5[i, j]
idx = idx + 1
kernel = getkernel(check_mat_negation, suffix=dtype.__name__)
if register_kernels:
return
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], -2 * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], -2 * m3.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], -2 * m4.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], -2 * m5.numpy().reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = -2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
def test_transpose(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_transpose(
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
m32: wp.array(dtype=mat32),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
mat2 = wptype(2) * wp.transpose(m2[0])
mat3 = wptype(2) * wp.transpose(m3[0])
mat4 = wptype(2) * wp.transpose(m4[0])
mat5 = wptype(2) * wp.transpose(m5[0])
mat32 = wptype(2) * wp.transpose(m32[0])
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = mat2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = mat3[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = mat4[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = mat5[i, j]
idx = idx + 1
for i in range(2):
for j in range(3):
outcomponents[idx] = mat32[i, j]
idx = idx + 1
kernel = getkernel(check_mat_transpose, suffix=dtype.__name__)
if register_kernels:
return
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m32 = wp.array(randvals([1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 2 * 3, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * m2.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * m3.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * m4.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * m5.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[54:], 2 * m32.numpy()[0].T.reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for input in [m2, m3, m4, m5]:
for i in range(input.dtype._shape_[0]):
for j in range(input.dtype._shape_[1]):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((input.dtype._shape_[1], input.dtype._shape_[0]), dtype=dtype)
expectedresult[j, i] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
def test_scalar_multiplication(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_scalar_mul(
s: wp.array(dtype=wptype),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
outcomponents_rightmul: wp.array(dtype=wptype),
):
m2result = s[0] * m2[0]
m3result = s[0] * m3[0]
m4result = s[0] * m4[0]
m5result = s[0] * m5[0]
m2resultright = m2[0] * s[0]
m3resultright = m3[0] * s[0]
m4resultright = m4[0] * s[0]
m5resultright = m5[0] * s[0]
m2result_2 = s[0] * m2[0]
m3result_2 = s[0] * m3[0]
m4result_2 = s[0] * m4[0]
m5result_2 = s[0] * m5[0]
m2resultright_2 = m2[0] * s[0]
m3resultright_2 = m3[0] * s[0]
m4resultright_2 = m4[0] * s[0]
m5resultright_2 = m5[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m2resultright[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m3resultright[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m4resultright[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m5resultright[i, j]
idx = idx + 1
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m2resultright_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m3resultright_2[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m4resultright_2[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m5resultright_2[i, j]
idx = idx + 1
kernel = getkernel(check_mat_scalar_mul, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals([1], dtype), requires_grad=True, device=device)
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * (2 * 2 + 3 * 3 + 4 * 4 + 5 * 5), dtype=wptype, requires_grad=True, device=device)
outcomponents_rightmul = wp.zeros(
2 * (2 * 2 + 3 * 3 + 4 * 4 + 5 * 5), dtype=wptype, requires_grad=True, device=device
)
wp.launch(kernel, dim=1, inputs=[s, m2, m3, m4, m5], outputs=[outcomponents, outcomponents_rightmul], device=device)
sval = s.numpy()[0]
assert_np_equal(outcomponents.numpy()[:4], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[:4], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents_rightmul.numpy()[4:13], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[13:29], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[29:54], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[54:58], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[58:67], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[67:83], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[83:108], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[54:58], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents_rightmul.numpy()[58:67], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[67:83], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[83:108], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
# test left mul gradient:
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, m2, m3, m4, m5],
outputs=[outcomponents, outcomponents_rightmul],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2 * sval
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult, tol=10 * tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * input.numpy()[0, i, j], tol=10 * tol)
tape.zero()
# test right mul gradient:
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, m2, m3, m4, m5],
outputs=[outcomponents, outcomponents_rightmul],
device=device,
)
wp.launch(
output_select_kernel,
dim=1,
inputs=[outcomponents_rightmul, idx],
outputs=[out],
device=device,
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2 * sval
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult, tol=10 * tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * input.numpy()[0, i, j], tol=10 * tol)
tape.zero()
idx = idx + 1
def test_matvec_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
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)
output_select_kernel = get_select_kernel(wptype)
def check_mat_vec_mul(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v32: wp.array(dtype=vec2),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
m32: wp.array(dtype=mat32),
outcomponents: wp.array(dtype=wptype),
):
v2result = m2[0] * v2[0]
v3result = m3[0] * v3[0]
v4result = m4[0] * v4[0]
v5result = m5[0] * v5[0]
v32result = m32[0] * v32[0]
v2result_2 = m2[0] @ v2[0]
v3result_2 = m3[0] @ v3[0]
v4result_2 = m4[0] @ v4[0]
v5result_2 = m5[0] @ v5[0]
v32result_2 = m32[0] @ v32[0]
idx = 0
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(2):
outcomponents[idx] = wptype(2) * v2result[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v3result[i]
idx = idx + 1
for i in range(4):
outcomponents[idx] = wptype(2) * v4result[i]
idx = idx + 1
for i in range(5):
outcomponents[idx] = wptype(2) * v5result[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v32result[i]
idx = idx + 1
for i in range(2):
outcomponents[idx] = wptype(2) * v2result_2[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v3result_2[i]
idx = idx + 1
for i in range(4):
outcomponents[idx] = wptype(2) * v4result_2[i]
idx = idx + 1
for i in range(5):
outcomponents[idx] = wptype(2) * v5result_2[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v32result_2[i]
idx = idx + 1
kernel = getkernel(check_mat_vec_mul, 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)
v32 = wp.array(randvals([1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m32 = wp.array(randvals([1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * (2 + 3 + 4 + 5 + 3), dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:2], 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[2:5], 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[5:9], 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[9:14], 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[14:17], 2 * np.matmul(m32.numpy()[0], v32.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[17:19], 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[19:22], 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[22:26], 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[26:31], 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[31:34], 2 * np.matmul(m32.numpy()[0], v32.numpy()[0]), tol=5 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, invec, inmat in [(2, v2, m2), (3, v3, m3), (4, v4, m4), (5, v5, m5), (3, v32, m32)]:
for i in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32],
outputs=[outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(tape.gradients[invec].numpy()[0], 2 * inmat.numpy()[0, i, :], tol=2 * tol)
expectedresult = np.zeros(inmat.dtype._shape_, dtype=dtype)
expectedresult[i, :] = 2 * invec.numpy()[0]
assert_np_equal(tape.gradients[inmat].numpy()[0], expectedresult, tol=2 * tol)
tape.zero()
idx = idx + 1
def test_matmat_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_mat_mul(
a2: wp.array(dtype=mat22),
a3: wp.array(dtype=mat33),
a4: wp.array(dtype=mat44),
a5: wp.array(dtype=mat55),
a32: wp.array(dtype=mat32),
b2: wp.array(dtype=mat22),
b3: wp.array(dtype=mat33),
b4: wp.array(dtype=mat44),
b5: wp.array(dtype=mat55),
b32: wp.array(dtype=mat32),
outcomponents: wp.array(dtype=wptype),
):
c2result = b2[0] * a2[0]
c3result = b3[0] * a3[0]
c4result = b4[0] * a4[0]
c5result = b5[0] * a5[0]
c32result = b32[0] * a2[0]
c32result2 = b3[0] * a32[0]
c2result_2 = b2[0] @ a2[0]
c3result_2 = b3[0] @ a3[0]
c4result_2 = b4[0] @ a4[0]
c5result_2 = b5[0] @ a5[0]
c32result_2 = b32[0] @ a2[0]
c32result2_2 = b3[0] @ a32[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * c2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * c3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * c4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * c5result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result2[i, j]
idx = idx + 1
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * c2result_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * c3result_2[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * c4result_2[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * c5result_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result2_2[i, j]
idx = idx + 1
kernel = getkernel(check_mat_mat_mul, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v32 = wp.array(randvals([1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m32 = wp.array(randvals([1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
outcomponents = wp.zeros(
2 * (2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2 + 3 * 2), dtype=wptype, requires_grad=True, device=device
)
wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=2 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[54:60], 2 * np.matmul(m32.numpy()[0], v2.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[60:66], 2 * np.matmul(m3.numpy()[0], v32.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[66:70], 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[70:79], 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[79:95], 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=2 * tol)
assert_np_equal(outcomponents.numpy()[95:120], 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[120:126], 2 * np.matmul(m32.numpy()[0], v2.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[126:132], 2 * np.matmul(m3.numpy()[0], v32.numpy()[0]), tol=5 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for v, m in [(v2, m2), (v3, m3), (v4, m4), (v5, m5), (v2, m32), (v32, m3)]:
rows, cols = m.dtype._shape_[0], v.dtype._shape_[1]
for i in range(rows):
for j in range(cols):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expected = np.zeros(v.dtype._shape_, dtype=dtype)
expected[:, j] = 2 * m.numpy()[0, i, :]
assert_np_equal(tape.gradients[v].numpy()[0], expected, tol=10 * tol)
expected = np.zeros(m.dtype._shape_, dtype=dtype)
expected[i, :] = 2 * v.numpy()[0, :, j]
assert_np_equal(tape.gradients[m].numpy()[0], expected, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_cw_multiplication(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 5.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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_cw_mul(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
v2result = wptype(2) * wp.cw_mul(v2[0], s2[0])
v3result = wptype(2) * wp.cw_mul(v3[0], s3[0])
v4result = wptype(2) * wp.cw_mul(v4[0], s4[0])
v5result = wptype(2) * wp.cw_mul(v5[0], s5[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_cw_mul, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() * s2.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() * s3.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() * s4.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() * s5.numpy()).reshape(-1), tol=50 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2 * in1.numpy()[0][i, j]
assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=5 * tol)
expectedresult[i, j] = 2 * in2.numpy()[0][i, j]
assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=5 * tol)
tape.zero()
idx = idx + 1
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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_cw_div(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
v2result = wptype(2) * wp.cw_div(v2[0], s2[0])
v3result = wptype(2) * wp.cw_div(v3[0], s3[0])
v4result = wptype(2) * wp.cw_div(v4[0], s4[0])
v5result = wptype(2) * wp.cw_div(v5[0], s5[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_cw_div, suffix=dtype.__name__)
if register_kernels:
return
s2 = randvals([1, 2, 2], dtype)
s3 = randvals([1, 3, 3], dtype)
s4 = randvals([1, 4, 4], dtype)
s5 = randvals([1, 5, 5], dtype)
# set denominators to 1 if their magnitudes are small
# to prevent divide by zero, or overflows if we're testing
# float16:
s2[np.abs(s2) < 1.0e-2] = 1
s3[np.abs(s3) < 1.0e-2] = 1
s4[np.abs(s4) < 1.0e-2] = 1
s5[np.abs(s5) < 1.0e-2] = 1
s2 = wp.array(s2, dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(s3, dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(s4, dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(s5, dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
if dtype in np_float_types:
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() / s2.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() / s3.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() / s4.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() / s5.numpy()).reshape(-1), tol=50 * tol)
else:
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() // s2.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() // s3.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() // s4.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() // s5.numpy()).reshape(-1), tol=50 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, s, v in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
# y = v/s
# dy/dv = 1.0/s
# dy/ds = -v/s^2
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2.0 / (s.numpy()[0, i, j])
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=50 * tol)
expectedresult[i, j] = -2.0 * v.numpy()[0, i, j] / (s.numpy()[0, i, j] ** 2)
assert_np_equal(
tape.gradients[s].numpy()[0], expectedresult, tol=abs(outcomponents.numpy()[idx]) * 50 * tol
)
tape.zero()
idx = idx + 1
def test_outer_product(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)
output_select_kernel = get_select_kernel(wptype)
def check_mat_outer_product(
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),
outcomponents: wp.array(dtype=wptype),
):
m22result = wptype(2) * wp.outer(s2[0], v2[0])
m33result = wptype(2) * wp.outer(s3[0], v3[0])
m44result = wptype(2) * wp.outer(s4[0], v4[0])
m55result = wptype(2) * wp.outer(s5[0], v5[0])
m25result = wptype(2) * wp.outer(s2[0], v5[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m22result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m33result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m44result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m55result[i, j]
idx = idx + 1
for i in range(2):
for j in range(5):
outcomponents[idx] = m25result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_outer_product, 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)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 2 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s2, s3, s4, s5, v2, v3, v4, v5], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * s2.numpy()[0, :, None] * v2.numpy()[0, None, :], tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * s3.numpy()[0, :, None] * v3.numpy()[0, None, :], tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * s4.numpy()[0, :, None] * v4.numpy()[0, None, :], tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * s5.numpy()[0, :, None] * v5.numpy()[0, None, :], tol=10 * tol)
assert_np_equal(outcomponents.numpy()[54:], 2 * s2.numpy()[0, :, None] * v5.numpy()[0, None, :], tol=10 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for s, v in [(s2, v2), (s3, v3), (s4, v4), (s5, v5), (s2, v5)]:
rows = s.dtype._length_
cols = v.dtype._length_
for i in range(rows):
for j in range(cols):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
# this component's gonna be s_i * v_j, so its s gradient is gonna be nozero
# at the ith component and its v gradient will be nonzero at the jth component:
expectedresult = np.zeros((rows), dtype=dtype)
expectedresult[i] = 2 * v.numpy()[0, j]
assert_np_equal(tape.gradients[s].numpy()[0], expectedresult, tol=10 * tol)
expectedresult = np.zeros((cols), dtype=dtype)
expectedresult[j] = 2 * s.numpy()[0, i]
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_scalar_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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_scalar_div(
s: wp.array(dtype=wptype),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
m2result = m2[0] / s[0]
m3result = m3[0] / s[0]
m4result = m4[0] / s[0]
m5result = m5[0] / s[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_scalar_div, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals([1], dtype), requires_grad=True, device=device)
m2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s, m2, m3, m4, m5], outputs=[outcomponents], device=device)
sval = s.numpy()[0]
if dtype in np_float_types:
assert_np_equal(outcomponents.numpy()[:4], 2 * m2.numpy().reshape(-1) / sval, tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * m3.numpy().reshape(-1) / sval, tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * m4.numpy().reshape(-1) / sval, tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * m5.numpy().reshape(-1) / sval, tol=10 * tol)
else:
assert_np_equal(outcomponents.numpy()[:4], 2 * (m2.numpy().reshape(-1) // sval), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (m3.numpy().reshape(-1) // sval), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (m4.numpy().reshape(-1) // sval), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (m5.numpy().reshape(-1) // sval), tol=10 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s, m2, m3, m4, m5], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2.0 / sval
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult, tol=10 * tol)
assert_np_equal(
tape.gradients[s].numpy()[0], -2 * input.numpy()[0, i, j] / (sval * sval), tol=10 * tol
)
tape.zero()
idx = idx + 1
def test_addition(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_add(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: 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 we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_add, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() + s2.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() + s3.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() + s4.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() + s5.numpy()).reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_sub(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: 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 we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_sub, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() - s2.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() - s3.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() - s4.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() - s5.numpy()).reshape(-1), tol=10 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
expectedresult[i, j] = -2
assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_ddot(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
def check_mat_dot(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
dot2: wp.array(dtype=wptype),
dot3: wp.array(dtype=wptype),
dot4: wp.array(dtype=wptype),
dot5: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
dot2[0] = wptype(2) * wp.ddot(v2[0], s2[0])
dot3[0] = wptype(2) * wp.ddot(v3[0], s3[0])
dot4[0] = wptype(2) * wp.ddot(v4[0], s4[0])
dot5[0] = wptype(2) * wp.ddot(v5[0], s5[0])
kernel = getkernel(check_mat_dot, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, 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 * (v2.numpy() * s2.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot3.numpy()[0], 2 * (v3.numpy() * s3.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot4.numpy()[0], 2 * (v4.numpy() * s4.numpy()).sum(), tol=50 * tol)
assert_np_equal(dot5.numpy()[0], 2 * (v5.numpy() * s5.numpy()).sum(), tol=200 * 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=10 * 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=10 * 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=10 * 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_determinant(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
def check_mat_det(
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
det2: wp.array(dtype=wptype),
det3: wp.array(dtype=wptype),
det4: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
det2[0] = wptype(2) * wp.determinant(v2[0])
det3[0] = wptype(2) * wp.determinant(v3[0])
det4[0] = wptype(2) * wp.determinant(v4[0])
kernel = getkernel(check_mat_det, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
det2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
det3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
det4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
v2,
v3,
v4,
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
if dtype in np_float_types:
assert_np_equal(det2.numpy()[0], 2 * np.linalg.det(v2.numpy()[0].astype(np.float64)), tol=100 * tol)
assert_np_equal(det3.numpy()[0], 2 * np.linalg.det(v3.numpy()[0].astype(np.float64)), tol=100 * tol)
assert_np_equal(det4.numpy()[0], 2 * np.linalg.det(v4.numpy()[0].astype(np.float64)), tol=420 * tol)
else:
assert_np_equal(det2.numpy()[0], 2 * np.around(np.linalg.det(v2.numpy()[0])).astype(int))
assert_np_equal(det3.numpy()[0], 2 * np.around(np.linalg.det(v3.numpy()[0])).astype(int))
assert_np_equal(det4.numpy()[0], 2 * np.around(np.linalg.det(v4.numpy()[0])).astype(int))
if dtype in np_float_types:
# determinant derivative formula is annoying so finite differences?
tape.backward(loss=det2)
v2grads = 1.0 * tape.gradients[v2].numpy()[0]
tape.zero()
tape.backward(loss=det3)
v3grads = 1.0 * tape.gradients[v3].numpy()[0]
tape.zero()
tape.backward(loss=det4)
v4grads = 1.0 * tape.gradients[v4].numpy()[0]
tape.zero()
# finite differences are also annoying hence the large tolerance...
# absolute nightmare in float16 too innit...
dx = 0.01 if dtype == np.float16 else 0.0001
fdtol = 2.0e-1 if dtype == np.float16 else 2.0e-3
for i in range(2):
for j in range(2):
v2test = v2.numpy()
v2test[0, i, j] += dx
wp.launch(
kernel,
dim=1,
inputs=[
wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
v3,
v4,
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
dplus = det2.numpy()[0]
v2test[0, i, j] -= 2.0 * dx
wp.launch(
kernel,
dim=1,
inputs=[
wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
v3,
v4,
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
dminus = det2.numpy()[0]
assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v2grads[i, j] / dplus, tol=fdtol)
for i in range(3):
for j in range(3):
v3test = v3.numpy()
v3test[0, i, j] += dx
wp.launch(
kernel,
dim=1,
inputs=[
v2,
wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
v4,
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
dplus = det3.numpy()[0]
v3test[0, i, j] -= 2.0 * dx
wp.launch(
kernel,
dim=1,
inputs=[
v2,
wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
v4,
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
dminus = det3.numpy()[0]
assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v3grads[i, j] / dplus, tol=fdtol)
for i in range(4):
for j in range(4):
v4test = v4.numpy()
v4test[0, i, j] += dx
wp.launch(
kernel,
dim=1,
inputs=[
v2,
v3,
wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
dplus = det4.numpy()[0]
v4test[0, i, j] -= 2.0 * dx
wp.launch(
kernel,
dim=1,
inputs=[
v2,
v3,
wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
],
outputs=[
det2,
det3,
det4,
],
device=device,
)
dminus = det4.numpy()[0]
assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v4grads[i, j] / dplus, tol=fdtol)
def test_trace(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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
def check_mat_trace(
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
tr2: wp.array(dtype=wptype),
tr3: wp.array(dtype=wptype),
tr4: wp.array(dtype=wptype),
tr5: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
tr2[0] = wptype(2) * wp.trace(v2[0])
tr3[0] = wptype(2) * wp.trace(v3[0])
tr4[0] = wptype(2) * wp.trace(v4[0])
tr5[0] = wptype(2) * wp.trace(v5[0])
kernel = getkernel(check_mat_trace, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals([1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals([1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals([1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
tr2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tr3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tr4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tr5 = 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=[
tr2,
tr3,
tr4,
tr5,
],
device=device,
)
assert_np_equal(tr2.numpy()[0], 2 * np.trace(v2.numpy()[0]), tol=10 * tol)
assert_np_equal(tr3.numpy()[0], 2 * np.trace(v3.numpy()[0]), tol=10 * tol)
assert_np_equal(tr4.numpy()[0], 2 * np.trace(v4.numpy()[0]), tol=200 * tol)
assert_np_equal(tr4.numpy()[0], 2 * np.trace(v4.numpy()[0]), tol=200 * tol)
if dtype in np_float_types:
tape.backward(loss=tr2)
vgrads = tape.gradients[v2].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(2), tol=10 * tol)
tape.zero()
tape.backward(loss=tr3)
vgrads = tape.gradients[v3].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(3), tol=10 * tol)
tape.zero()
tape.backward(loss=tr4)
vgrads = tape.gradients[v4].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(4), tol=10 * tol)
tape.zero()
tape.backward(loss=tr5)
vgrads = tape.gradients[v5].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(5), tol=10 * tol)
tape.zero()
def test_diag(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)]
vec5 = wp.types.vector(length=5, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_diag(
s5: wp.array(dtype=vec5),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m55result = wptype(2) * wp.diag(s5[0])
idx = 0
for i in range(5):
for j in range(5):
outcomponents[idx] = m55result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
if register_kernels:
return
s5 = wp.array(randvals([1, 5], dtype), dtype=vec5, requires_grad=True, device=device)
outcomponents = wp.zeros(5 * 5, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s5], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy(), 2 * np.diag(s5.numpy()[0]), tol=tol)
if dtype in np_float_types:
idx = 0
for i in range(5):
for j in range(5):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s5], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(5, dtype=dtype)
if i == j:
expectedresult[i] = 2
assert_np_equal(tape.gradients[s5].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_get_diag(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)]
mat55 = wp.types.vector(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_diag(
m55: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
vec5result = wptype(2) * wp.get_diag(m55[0])
idx = 0
for i in range(5):
outcomponents[idx] = vec5result[i]
idx = idx + 1
kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
if register_kernels:
return
m55 = wp.array(randvals((1, 5, 5), dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(5, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy(), 2 * np.diag(m55.numpy()[0]), tol=tol)
if dtype in np_float_types:
idx = 0
for i in range(5):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros((5, 5), dtype=dtype)
expectedresult[i, i] = 2
assert_np_equal(tape.gradients[m55].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_inverse(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.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)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_inverse(
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
outcomponents: wp.array(dtype=wptype),
):
m2result = wp.inverse(m2[0])
m3result = wp.inverse(m3[0])
m4result = wp.inverse(m4[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_inverse, suffix=dtype.__name__)
if register_kernels:
return
m2 = wp.array(2 * (randvals([1, 2, 2], dtype) + 0.2 * np.eye(2)), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(2 * (randvals([1, 3, 3], dtype) + 0.2 * np.eye(3)), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(2 * (randvals([1, 4, 4], dtype) + 0.2 * np.eye(4)), dtype=mat44, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * np.linalg.inv(m2.numpy()[0].astype(np.float64)), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * np.linalg.inv(m3.numpy()[0].astype(np.float64)), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[13:], 2 * np.linalg.inv(m4.numpy()[0].astype(np.float64)), tol=5 * tol)
if dtype in np_float_types:
# check gradients:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4)]:
minv = np.linalg.inv(input.numpy()[0].astype(np.float64))
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
d = np.zeros((dim, dim))
d[j, i] = 2
assert_np_equal(
tape.gradients[input].numpy()[0], -np.matmul(minv, np.matmul(d, minv)).T, tol=10 * tol
)
tape.zero()
idx = idx + 1
# let's check 2x2 using different formulae just for (in)sanity's sake:
m = m2.numpy()[0]
det = m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]
expected = 2 * np.array([[m[1, 1], -m[0, 1]], [-m[1, 0], m[0, 0]]], dtype=dtype) / det
assert_np_equal(expected, outcomponents.numpy()[:4], tol=tol)
# 0,0 component is this:
# 2 * m[1,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
assert_np_equal(2 * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[0], tol=tol)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 0], outputs=[out], device=device)
if dtype in np_float_types:
tape.backward(loss=out)
g = tape.gradients[m2].numpy()[0]
assert_np_equal(-2 * m[1, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
assert_np_equal(2 * m[1, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
tape.zero()
# 0,1 component is this:
# -2 * m[0,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
assert_np_equal(-2 * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[1], tol=tol)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 1], outputs=[out], device=device)
if dtype in np_float_types:
tape.backward(loss=out)
g = tape.gradients[m2].numpy()[0]
assert_np_equal(2 * m[0, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
assert_np_equal(-2 * m[0, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
assert_np_equal(-2 * m[1, 1] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
tape.zero()
# 1,0 component is this:
# -2 * m[1,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
assert_np_equal(-2 * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[2], tol=tol)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 2], outputs=[out], device=device)
if dtype in np_float_types:
tape.backward(loss=out)
g = tape.gradients[m2].numpy()[0]
assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
assert_np_equal(-2 * m[0, 0] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
assert_np_equal(-2 * m[1, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
tape.zero()
# 1,1 component is this:
# 2 * m[0,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
assert_np_equal(2 * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[3], tol=tol)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 3], outputs=[out], device=device)
if dtype in np_float_types:
tape.backward(loss=out)
g = tape.gradients[m2].numpy()[0]
assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
assert_np_equal(-2 * m[0, 0] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
tape.zero()
def test_svd(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-6,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(length=3, dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
def check_mat_svd(
m3: wp.array(dtype=mat33),
Uout: wp.array(dtype=mat33),
sigmaout: wp.array(dtype=vec3),
Vout: wp.array(dtype=mat33),
outcomponents: wp.array(dtype=wptype),
):
U = mat33()
sigma = vec3()
V = mat33()
wp.svd3(m3[0], U, sigma, V)
Uout[0] = U
sigmaout[0] = sigma
Vout[0] = V
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * U[i, j]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * sigma[i]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * V[i, j]
idx = idx + 1
kernel = getkernel(check_mat_svd, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
m3 = wp.array(randvals([1, 3, 3], dtype) + np.eye(3), dtype=mat33, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
Uout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
sigmaout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
Vout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
Uout_np = Uout.numpy()[0].astype(np.float64)
sigmaout_np = np.diag(sigmaout.numpy()[0].astype(np.float64))
Vout_np = Vout.numpy()[0].astype(np.float64)
assert_np_equal(
np.matmul(Uout_np, np.matmul(sigmaout_np, Vout_np.T)), m3.numpy()[0].astype(np.float64), tol=30 * tol
)
if dtype == np.float16:
# I'm not even going to bother testing the gradients for float16
# because the rounding errors are terrible...
return
# check gradients:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
idx = 0
for idx in range(3 * 3 + 3 + 3 * 3):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(out)
m3grads = 1.0 * tape.gradients[m3].numpy()[0]
tape.zero()
dx = 0.0001
fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
for ii in range(3):
for jj in range(3):
m3test = 1.0 * m3.numpy()
m3test[0, ii, jj] += dx
wp.launch(
kernel,
dim=1,
inputs=[wp.array(m3test, dtype=mat33, device=device)],
outputs=[Uout, sigmaout, Vout, outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
plusval = out.numpy()[0]
m3test = 1.0 * m3.numpy()
m3test[0, ii, jj] -= dx
wp.launch(
kernel,
dim=1,
inputs=[wp.array(m3test, dtype=mat33, device=device)],
outputs=[Uout, sigmaout, Vout, outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
minusval = out.numpy()[0]
assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
def test_qr(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 2.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-6,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
def check_mat_qr(
m3: wp.array(dtype=mat33),
Qout: wp.array(dtype=mat33),
Rout: wp.array(dtype=mat33),
outcomponents: wp.array(dtype=wptype),
):
Q = mat33()
R = mat33()
wp.qr3(m3[0], Q, R)
Qout[0] = Q
Rout[0] = R
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * Q[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * R[i, j]
idx = idx + 1
kernel = getkernel(check_mat_qr, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
m3 = wp.array(0.5 * (randvals([1, 3, 3], dtype) + np.eye(3)), dtype=mat33, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 3 * 3, dtype=wptype, requires_grad=True, device=device)
Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
Rout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
Qout_np = Qout.numpy()[0].astype(np.float64)
Rout_np = Rout.numpy()[0].astype(np.float64)
# check it's actually a q and an r:
assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3, dtype=np.float64), tol=tol)
assert_np_equal(Rout_np[1, [0]], np.zeros(1, dtype=np.float64), tol=tol)
assert_np_equal(Rout_np[2, [0, 1]], np.zeros(2, dtype=np.float64), tol=tol)
# check it's a factorization:
assert_np_equal(np.matmul(Qout_np, Rout_np), m3.numpy()[0].astype(np.float64), tol=30 * tol)
if dtype == np.float16:
# I'm not even going to bother testing the gradients for float16
# because the rounding errors are terrible...
return
# check gradients:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
idx = 0
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(out)
m3grads = 1.0 * tape.gradients[m3].numpy()[0]
tape.zero()
dx = 0.0001
fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
for ii in range(3):
for jj in range(3):
m3test = 1.0 * m3.numpy()
m3test[0, ii, jj] += dx
wp.launch(
kernel,
dim=1,
inputs=[wp.array(m3test, dtype=mat33, device=device)],
outputs=[Qout, Rout, outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
plusval = out.numpy()[0]
m3test = 1.0 * m3.numpy()
m3test[0, ii, jj] -= dx
wp.launch(
kernel,
dim=1,
inputs=[wp.array(m3test, dtype=mat33, device=device)],
outputs=[Qout, Rout, outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
minusval = out.numpy()[0]
assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
def test_eig(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 4.0e-2,
np.float32: 1.0e-5,
np.float64: 1.0e-5,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec3 = wp.types.vector(length=3, dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
def check_mat_eig(
m3: wp.array(dtype=mat33),
Qout: wp.array(dtype=mat33),
dout: wp.array(dtype=vec3),
outcomponents: wp.array(dtype=wptype),
):
Q = mat33()
d = vec3()
wp.eig3(m3[0] + wp.transpose(m3[0]), Q, d)
Qout[0] = Q
dout[0] = d
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * Q[i, j]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * d[i]
idx = idx + 1
kernel = getkernel(check_mat_eig, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
m3_np = randvals([1, 3, 3], dtype) + np.eye(3, dtype=dtype)
m3 = wp.array(m3_np, dtype=mat33, requires_grad=True, device=device)
outcomponents = wp.zeros(3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
dout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
Qout_np = Qout.numpy()[0].astype(np.float64)
dout_np = dout.numpy()[0].astype(np.float64)
Dout_np = np.diag(dout_np)
# check Q is orthogonal:
assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3), tol=tol)
# check Q contains eigenvectors:
assert_np_equal(np.matmul(Qout_np, np.matmul(Dout_np, Qout_np.T)), (m3_np[0] + m3_np[0].transpose()), tol=tol)
if dtype == np.float16:
# I'm not even going to bother testing the gradients for float16
# because the rounding errors are terrible...
return
# check gradients:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
idx = 0
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(out)
m3grads = 1.0 * tape.gradients[m3].numpy()[0]
tape.zero()
dx = 0.0001
fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
for ii in range(3):
for jj in range(3):
m3test = 1.0 * m3.numpy()
m3test[0, ii, jj] += dx
wp.launch(
kernel,
dim=1,
inputs=[wp.array(m3test, dtype=mat33, device=device)],
outputs=[Qout, dout, outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
plusval = out.numpy()[0]
m3test = 1.0 * m3.numpy()
m3test[0, ii, jj] -= dx
wp.launch(
kernel,
dim=1,
inputs=[wp.array(m3test, dtype=mat33, device=device)],
outputs=[Qout, dout, outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
minusval = out.numpy()[0]
assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
def test_skew(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)]
vec3 = wp.types.vector(length=3, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_skew(
v3: wp.array(dtype=vec3),
outcomponents: wp.array(dtype=wptype),
):
m3result = wp.skew(v3[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_skew, suffix=dtype.__name__)
if register_kernels:
return
v3 = wp.array(randvals([1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
outcomponents = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
# make sure it gives you a cross product matrix:
crossprodmat = outcomponents.numpy().reshape(3, 3)
v = np.array([1, 0, 0])
assert_np_equal(
np.matmul(crossprodmat, np.array([1, 0, 0])).reshape(-1),
2 * np.cross(v3.numpy()[0], np.array([1, 0, 0])),
tol=tol,
)
assert_np_equal(
np.matmul(crossprodmat, np.array([0, 1, 0])).reshape(-1),
2 * np.cross(v3.numpy()[0], np.array([0, 1, 0])),
tol=tol,
)
assert_np_equal(
np.matmul(crossprodmat, np.array([0, 0, 1])).reshape(-1),
2 * np.cross(v3.numpy()[0], np.array([0, 0, 1])),
tol=tol,
)
# check it another way:
x0 = v3.numpy()[0, 0]
x1 = v3.numpy()[0, 1]
x2 = v3.numpy()[0, 2]
crossprodmat_expected = np.array(
[
[0, -x2, x1],
[x2, 0, -x0],
[-x1, x0, 0],
],
dtype=dtype,
)
assert_np_equal(crossprodmat, 2 * crossprodmat_expected, tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(3):
for j in range(3):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
if i == j:
assert_np_equal(tape.gradients[v3].numpy()[0], np.zeros(3))
elif [i, j] == [0, 1]:
assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, -2]))
elif [i, j] == [1, 0]:
assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, 2]))
elif [i, j] == [0, 2]:
assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 2, 0]))
elif [i, j] == [2, 0]:
assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, -2, 0]))
elif [i, j] == [1, 2]:
assert_np_equal(tape.gradients[v3].numpy()[0], np.array([-2, 0, 0]))
elif [i, j] == [2, 1]:
assert_np_equal(tape.gradients[v3].numpy()[0], np.array([2, 0, 0]))
tape.zero()
idx = idx + 1
def test_transform_point(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)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_transform_point(
v3: wp.array(dtype=vec3),
m4: wp.array(dtype=mat44),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
presult = wptype(2) * wp.transform_point(m4[0], v3[0])
outcomponents[0] = presult[0]
outcomponents[1] = presult[1]
outcomponents[2] = presult[2]
kernel = getkernel(check_mat_transform_point, suffix=dtype.__name__)
if register_kernels:
return
v3 = wp.array(randvals([1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
v3homog = np.ones(4, dtype=dtype)
v3homog[:3] = v3.numpy()[0]
assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
if dtype in np_float_types:
for j in range(3):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
expected = np.zeros((4, 4), dtype=dtype)
expected[j, :3] = 2 * v3.numpy()
expected[j, 3] = 2
assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
tape.zero()
def test_transform_vector(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)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_transform_vector(
v3: wp.array(dtype=vec3),
m4: wp.array(dtype=mat44),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
presult = wptype(2) * wp.transform_vector(m4[0], v3[0])
outcomponents[0] = presult[0]
outcomponents[1] = presult[1]
outcomponents[2] = presult[2]
kernel = getkernel(check_mat_transform_vector, suffix=dtype.__name__)
if register_kernels:
return
v3 = wp.array(randvals([1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
m4 = wp.array(randvals([1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
v3homog = np.zeros(4, dtype=dtype)
v3homog[:3] = v3.numpy()[0]
assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
if dtype in np_float_types:
for j in range(3):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
expected = np.zeros((4, 4), dtype=dtype)
expected[j, :3] = 2 * v3.numpy()
assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
tape.zero()
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),
):
m2result = wp.matrix(input[0], shape=(2, 2))
m3result = wp.matrix(input[1], shape=(3, 3))
m4result = wp.matrix(input[2], shape=(4, 4))
m5result = wp.matrix(input[3], shape=(5, 5))
m32result = wp.matrix(input[4], shape=(3, 2))
idx = 0
for i in range(2):
for j in range(2):
output[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
output[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
output[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
output[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
output[idx] = wptype(2) * m32result[i, j]
idx = idx + 1
def check_component_init(
input: wp.array(dtype=wptype),
output: wp.array(dtype=wptype),
):
m2result = wp.matrix(input[0], input[1], input[2], input[3], shape=(2, 2))
m3result = wp.matrix(
input[4], input[5], input[6], input[7], input[8], input[9], input[10], input[11], input[12], shape=(3, 3)
)
m4result = wp.matrix(
input[13],
input[14],
input[15],
input[16],
input[17],
input[18],
input[19],
input[20],
input[21],
input[22],
input[23],
input[24],
input[25],
input[26],
input[27],
input[28],
shape=(4, 4),
)
m5result = wp.matrix(
input[29],
input[30],
input[31],
input[32],
input[33],
input[34],
input[35],
input[36],
input[37],
input[38],
input[39],
input[40],
input[41],
input[42],
input[43],
input[44],
input[45],
input[46],
input[47],
input[48],
input[49],
input[50],
input[51],
input[52],
input[53],
shape=(5, 5),
)
m32result = wp.matrix(input[54], input[55], input[56], input[57], input[58], input[59], shape=(3, 2))
idx = 0
for i in range(2):
for j in range(2):
output[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
output[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
output[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
output[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
output[idx] = wptype(2) * m32result[i, j]
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([5], dtype), requires_grad=True, device=device)
output = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2, dtype=wptype, requires_grad=True, device=device)
wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy()[:4], 2 * np.array([input.numpy()[0]] * 2 * 2), tol=1.0e-6)
assert_np_equal(output.numpy()[4:13], 2 * np.array([input.numpy()[1]] * 3 * 3), tol=1.0e-6)
assert_np_equal(output.numpy()[13:29], 2 * np.array([input.numpy()[2]] * 4 * 4), tol=1.0e-6)
assert_np_equal(output.numpy()[29:54], 2 * np.array([input.numpy()[3]] * 5 * 5), tol=1.0e-6)
assert_np_equal(output.numpy()[54:], 2 * np.array([input.numpy()[4]] * 3 * 2), 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 < 4:
expected[0] = 2
elif i < 13:
expected[1] = 2
elif i < 29:
expected[2] = 2
elif i < 54:
expected[3] = 2
else:
expected[4] = 2
assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol)
tape.reset()
tape.zero()
input = wp.array(randvals([2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2], dtype), requires_grad=True, device=device)
output = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2, 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_identity(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_identity_mat(
output: wp.array(dtype=wptype),
):
m2result = wp.identity(dtype=wptype, n=2)
m3result = wp.identity(dtype=wptype, n=3)
m4result = wp.identity(dtype=wptype, n=4)
m5result = wp.identity(dtype=wptype, n=5)
idx = 0
for i in range(2):
for j in range(2):
output[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
output[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
output[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
output[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
id_kernel = getkernel(check_identity_mat, suffix=dtype.__name__)
if register_kernels:
return
output = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(id_kernel, dim=1, inputs=[], outputs=[output], device=device)
assert_np_equal(output.numpy()[:4], 2 * np.eye(2), tol=1.0e-6)
assert_np_equal(output.numpy()[4:13], 2 * np.eye(3), tol=1.0e-6)
assert_np_equal(output.numpy()[13:29], 2 * np.eye(4), tol=1.0e-6)
assert_np_equal(output.numpy()[29:], 2 * np.eye(5), tol=1.0e-6)
def test_equivalent_types(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
# matrix types
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
# matrix types equivalent to the above
mat22_equiv = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33_equiv = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44_equiv = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55_equiv = wp.types.matrix(shape=(5, 5), dtype=wptype)
# declare kernel with original types
def check_equivalence(
m2: mat22,
m3: mat33,
m4: mat44,
m5: mat55,
):
wp.expect_eq(m2, mat22(wptype(42)))
wp.expect_eq(m3, mat33(wptype(43)))
wp.expect_eq(m4, mat44(wptype(44)))
wp.expect_eq(m5, mat55(wptype(45)))
wp.expect_eq(m2, mat22_equiv(wptype(42)))
wp.expect_eq(m3, mat33_equiv(wptype(43)))
wp.expect_eq(m4, mat44_equiv(wptype(44)))
wp.expect_eq(m5, mat55_equiv(wptype(45)))
kernel = getkernel(check_equivalence, suffix=dtype.__name__)
if register_kernels:
return
# call kernel with equivalent types
m2 = mat22_equiv(42)
m3 = mat33_equiv(43)
m4 = mat44_equiv(44)
m5 = mat55_equiv(45)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], device=device)
def test_conversions(test, device, dtype, register_kernels=False):
def check_matrices_equal(
m0: wp.mat22,
m1: wp.mat22,
m2: wp.mat22,
m3: wp.mat22,
m4: wp.mat22,
m5: wp.mat22,
m6: wp.mat22,
):
wp.expect_eq(m1, m0)
wp.expect_eq(m2, m0)
wp.expect_eq(m3, m0)
wp.expect_eq(m4, m0)
wp.expect_eq(m5, m0)
wp.expect_eq(m6, m0)
kernel = getkernel(check_matrices_equal, suffix=dtype.__name__)
if register_kernels:
return
m0 = wp.mat22(1, 2, 3, 4)
# test explicit conversions - constructing matrices from different containers
m1 = wp.mat22(((1, 2), (3, 4))) # nested tuples
m2 = wp.mat22([[1, 2], [3, 4]]) # nested lists
m3 = wp.mat22(np.array([[1, 2], [3, 4]], dtype=dtype)) # 2d array
m4 = wp.mat22((1, 2, 3, 4)) # flat tuple
m5 = wp.mat22([1, 2, 3, 4]) # flat list
m6 = wp.mat22(np.array([1, 2, 3, 4], dtype=dtype)) # 1d array
wp.launch(kernel, dim=1, inputs=[m0, m1, m2, m3, m4, m5, m6], device=device)
# test implicit conversions - passing different containers as matrices to wp.launch()
m1 = ((1, 2), (3, 4)) # nested tuples
m2 = [[1, 2], [3, 4]] # nested lists
m3 = np.array([[1, 2], [3, 4]], dtype=dtype) # 2d array
m4 = (1, 2, 3, 4) # flat tuple
m5 = [1, 2, 3, 4] # flat list
m6 = np.array([1, 2, 3, 4], dtype=dtype) # 1d array
wp.launch(kernel, dim=1, inputs=[m0, m1, m2, m3, m4, m5, m6], 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
eye = wp.identity(dtype=wp.float16, n=2)
zeros = wp.matrix(shape=(2, 2), dtype=wp.float16)
custom = wp.matrix(wp.float16(0.0), wp.float16(1.0), wp.float16(2.0), wp.float16(3.0), shape=(2, 2))
for i in range(2):
for j in range(2):
if i == j:
wp.expect_eq(eye[i, j], wp.float16(1.0))
else:
wp.expect_eq(eye[i, j], wp.float16(0.0))
wp.expect_eq(zeros[i, j], wp.float16(0.0))
wp.expect_eq(custom[i, j], wp.float16(i) * wp.float16(2.0) + wp.float16(j))
# 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 default (float) matrix types
eye = wp.identity(dtype=float, n=2)
zeros = wp.matrix(shape=(2, 2), dtype=float)
custom = wp.matrix(0.0, 1.0, 2.0, 3.0, shape=(2, 2))
for i in range(2):
for j in range(2):
if i == j:
wp.expect_eq(eye[i, j], 1.0)
else:
wp.expect_eq(eye[i, j], 0.0)
wp.expect_eq(zeros[i, j], 0.0)
wp.expect_eq(custom[i, j], float(i) * 2.0 + float(j))
@wp.kernel
def test_matrix_mutation(expected: wp.types.matrix(shape=(10, 3), dtype=float)):
m = wp.matrix(shape=(10, 3), dtype=float)
# test direct element indexing
m[0, 0] = 1.0
m[0, 1] = 2.0
m[0, 2] = 3.0
# The nested indexing (matrix->vector->scalar) below does not
# currently modify m because m[0] returns row vector by
# value rather than reference, this is different from NumPy
# which always returns by ref. Not clear how we can support
# this as well as auto-diff.
# m[0][1] = 2.0
# m[0][2] = 3.0
# test setting rows
for i in range(1, 10):
m[i] = m[i - 1] + wp.vec3(1.0, 2.0, 3.0)
wp.expect_eq(m, expected)
CONSTANT_SHAPE_ROWS = wp.constant(10)
CONSTANT_SHAPE_COLS = wp.constant(10)
# tests that we can use global constants in shape keyword argument
# for matrix constructor
@wp.kernel
def test_constructors_constant_shape():
m = wp.matrix(shape=(CONSTANT_SHAPE_ROWS, CONSTANT_SHAPE_COLS), dtype=float)
for i in range(CONSTANT_SHAPE_ROWS):
for j in range(CONSTANT_SHAPE_COLS):
m[i, j] = float(i * j)
def register(parent):
devices = get_test_devices()
class TestMat(parent):
pass
add_kernel_test(TestMat, test_constructors_explicit_precision, dim=1, devices=devices)
add_kernel_test(TestMat, test_constructors_default_precision, dim=1, devices=devices)
add_kernel_test(TestMat, test_constructors_constant_shape, dim=1, devices=devices)
mat103 = wp.types.matrix(shape=(10, 3), dtype=float)
add_kernel_test(
TestMat,
test_matrix_mutation,
dim=1,
inputs=[
mat103(
1.0,
2.0,
3.0,
2.0,
4.0,
6.0,
3.0,
6.0,
9.0,
4.0,
8.0,
12.0,
5.0,
10.0,
15.0,
6.0,
12.0,
18.0,
7.0,
14.0,
21.0,
8.0,
16.0,
24.0,
9.0,
18.0,
27.0,
10.0,
20.0,
30.0,
)
],
devices=devices,
)
for dtype in np_signed_int_types + np_float_types:
add_function_test_register_kernel(
TestMat, f"test_negation_{dtype.__name__}", test_negation, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
)
for dtype in np_scalar_types:
add_function_test(TestMat, f"test_arrays_{dtype.__name__}", test_arrays, devices=devices, dtype=dtype)
add_function_test(TestMat, f"test_components_{dtype.__name__}", test_components, devices=None, dtype=dtype)
add_function_test_register_kernel(
TestMat, f"test_constructors_{dtype.__name__}", test_constructors, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_anon_type_instance_{dtype.__name__}", test_anon_type_instance, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_identity_{dtype.__name__}", test_identity, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_indexing_{dtype.__name__}", test_indexing, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_equality_{dtype.__name__}", test_equality, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat,
f"test_scalar_multiplication_{dtype.__name__}",
test_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMat,
f"test_matvec_multiplication_{dtype.__name__}",
test_matvec_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMat,
f"test_matmat_multiplication_{dtype.__name__}",
test_matmat_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMat, f"test_cw_multiplication_{dtype.__name__}", test_cw_multiplication, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_cw_division_{dtype.__name__}", test_cw_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_outer_product_{dtype.__name__}", test_outer_product, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_transpose_{dtype.__name__}", test_transpose, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_scalar_division_{dtype.__name__}", test_scalar_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_addition_{dtype.__name__}", test_addition, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_ddot_{dtype.__name__}", test_ddot, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_trace_{dtype.__name__}", test_trace, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_diag_{dtype.__name__}", test_diag, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_get_diag_{dtype.__name__}", test_diag, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_equivalent_types_{dtype.__name__}", test_equivalent_types, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_conversions_{dtype.__name__}", test_conversions, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_constants_{dtype.__name__}", test_constants, devices=devices, dtype=dtype
)
for dtype in np_float_types:
add_function_test_register_kernel(
TestMat, f"test_quat_constructor_{dtype.__name__}", test_quat_constructor, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_inverse_{dtype.__name__}", test_inverse, devices=devices, dtype=dtype
)
add_function_test_register_kernel(TestMat, f"test_svd_{dtype.__name__}", test_svd, devices=devices, dtype=dtype)
add_function_test_register_kernel(TestMat, f"test_qr_{dtype.__name__}", test_qr, devices=devices, dtype=dtype)
add_function_test_register_kernel(TestMat, f"test_eig_{dtype.__name__}", test_eig, devices=devices, dtype=dtype)
add_function_test_register_kernel(
TestMat, f"test_transform_point_{dtype.__name__}", test_transform_point, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_transform_vector_{dtype.__name__}", test_transform_vector, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_determinant_{dtype.__name__}", test_determinant, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMat, f"test_skew_{dtype.__name__}", test_skew, devices=devices, dtype=dtype
)
return TestMat
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=True)
| warp-main | warp/tests/test_mat.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.
# include parent path
import math
import unittest
from typing import Any
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
# types to test fabric arrays
_fabric_types = [
*wp.types.scalar_types,
*[wp.types.vector(2, T) for T in wp.types.scalar_types],
*[wp.types.vector(3, T) for T in wp.types.scalar_types],
*[wp.types.vector(4, T) for T in wp.types.scalar_types],
*[wp.types.matrix((2, 2), T) for T in wp.types.scalar_types],
*[wp.types.matrix((3, 3), T) for T in wp.types.scalar_types],
*[wp.types.matrix((4, 4), T) for T in wp.types.scalar_types],
*[wp.types.quaternion(T) for T in wp.types.float_types],
]
def _warp_type_to_fabric(dtype, is_array=False):
scalar_map = {
wp.bool: "b",
wp.int8: "i1",
wp.int16: "i2",
wp.int32: "i4",
wp.int64: "i8",
wp.uint8: "u1",
wp.uint16: "u2",
wp.uint32: "u4",
wp.uint64: "u8",
wp.float16: "f2",
wp.float32: "f4",
wp.float64: "f8",
}
if hasattr(dtype, "_wp_scalar_type_"):
type_str = scalar_map[dtype._wp_scalar_type_]
if len(dtype._shape_) == 1:
role = "vector"
else:
role = "matrix"
else:
type_str = scalar_map[dtype]
role = ""
if is_array:
array_depth = 1
else:
array_depth = 0
return (True, type_str, dtype._length_, array_depth, role)
# returns a fabric array interface constructed from a regular array
def _create_fabric_array_interface(data: wp.array, attrib: str, bucket_sizes: list = None, copy=False):
assert isinstance(data, wp.array)
assert data.ndim == 1
assert isinstance(attrib, str)
if copy:
data = wp.clone(data)
if bucket_sizes is not None:
assert hasattr(bucket_sizes, "__len__")
# verify total size
total_size = 0
for bucket_size in bucket_sizes:
total_size += bucket_size
if total_size != data.size:
raise RuntimeError("Bucket sizes don't add up to the size of data array")
elif data.size > 0:
# generate random bucket sizes
bucket_min = 1
bucket_max = math.ceil(0.5 * data.size)
total_size = data.size
size_remaining = total_size
bucket_sizes = []
while size_remaining >= bucket_max:
bucket_size = np.random.randint(bucket_min, bucket_max)
bucket_sizes.append(bucket_size)
size_remaining -= bucket_size
if size_remaining > 0:
bucket_sizes.append(size_remaining)
else:
# empty data array
bucket_sizes = []
dtype_size = wp.types.type_size_in_bytes(data.dtype)
p = int(data.ptr) if data.ptr else 0
pointers = []
counts = []
for bucket_size in bucket_sizes:
pointers.append(p)
counts.append(bucket_size)
p += bucket_size * dtype_size
attrib_info = {}
attrib_info["type"] = _warp_type_to_fabric(data.dtype)
attrib_info["access"] = 2 # ReadWrite
attrib_info["pointers"] = pointers
attrib_info["counts"] = counts
iface = {}
iface["version"] = 1
iface["device"] = str(data.device)
iface["attribs"] = {attrib: attrib_info}
iface["_ref"] = data # backref to keep the array alive
return iface
# returns a fabric array array interface constructed from a list of regular arrays
def _create_fabric_array_array_interface(data: list, attrib: str, bucket_sizes: list = None):
# data should be a list of arrays
assert isinstance(data, list)
num_arrays = len(data)
assert num_arrays > 0
device = data[0].device
dtype = data[0].dtype
assert isinstance(attrib, str)
if bucket_sizes is not None:
assert hasattr(bucket_sizes, "__len__")
# verify total size
total_size = 0
for bucket_size in bucket_sizes:
total_size += bucket_size
if total_size != num_arrays:
raise RuntimeError("Bucket sizes don't add up to the number of given arrays")
else:
# generate random bucket sizes
bucket_min = 1
bucket_max = math.ceil(0.5 * num_arrays)
total_size = num_arrays
size_remaining = total_size
bucket_sizes = []
while size_remaining >= bucket_max:
bucket_size = np.random.randint(bucket_min, bucket_max)
bucket_sizes.append(bucket_size)
size_remaining -= bucket_size
if size_remaining > 0:
bucket_sizes.append(size_remaining)
# initialize array of pointers to arrays and their lengths
_array_pointers = []
_array_lengths = []
for i in range(num_arrays):
_array_pointers.append(data[i].ptr)
_array_lengths.append(data[i].size)
array_pointers = wp.array(_array_pointers, dtype=wp.uint64, device=device)
pointer_size = wp.types.type_size_in_bytes(array_pointers.dtype)
lengths = wp.array(_array_lengths, dtype=wp.uint64, device=device)
length_size = wp.types.type_size_in_bytes(lengths.dtype)
p_pointers = int(array_pointers.ptr)
p_lengths = int(lengths.ptr)
pointers = []
counts = []
array_lengths = []
for bucket_size in bucket_sizes:
pointers.append(p_pointers)
counts.append(bucket_size)
array_lengths.append(p_lengths)
p_pointers += bucket_size * pointer_size
p_lengths += bucket_size * length_size
attrib_info = {}
attrib_info["type"] = _warp_type_to_fabric(dtype, is_array=True)
attrib_info["access"] = 2 # ReadWrite
attrib_info["pointers"] = pointers
attrib_info["counts"] = counts
attrib_info["array_lengths"] = array_lengths
iface = {}
iface["version"] = 1
iface["device"] = str(device)
iface["attribs"] = {attrib: attrib_info}
iface["_ref"] = data # backref to keep the data arrays alive
iface["_ref_pointers"] = array_pointers # backref to keep the array pointers alive
iface["_ref_lengths"] = lengths # backref to keep the lengths array alive
return iface
@wp.kernel
def fa_kernel(a: wp.fabricarray(dtype=float), expected: wp.array(dtype=float)):
i = wp.tid()
wp.expect_eq(a[i], expected[i])
a[i] = 2.0 * a[i]
wp.atomic_add(a, i, 1.0)
wp.expect_eq(a[i], 2.0 * expected[i] + 1.0)
@wp.kernel
def fa_kernel_indexed(a: wp.indexedfabricarray(dtype=float), expected: wp.indexedarray(dtype=float)):
i = wp.tid()
wp.expect_eq(a[i], expected[i])
a[i] = 2.0 * a[i]
wp.atomic_add(a, i, 1.0)
wp.expect_eq(a[i], 2.0 * expected[i] + 1.0)
def test_fabricarray_kernel(test, device):
data = wp.array(data=np.arange(100, dtype=np.float32), device=device)
iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=iface, attrib="foo")
test.assertEqual(fa.dtype, data.dtype)
test.assertEqual(fa.ndim, 1)
test.assertEqual(fa.shape, data.shape)
test.assertEqual(fa.size, data.size)
wp.launch(fa_kernel, dim=fa.size, inputs=[fa, data], device=device)
# reset data
wp.copy(fa, data)
# test indexed
indices = wp.array(data=np.arange(1, data.size, 2, dtype=np.int32), device=device)
ifa = fa[indices]
idata = data[indices]
test.assertEqual(ifa.dtype, idata.dtype)
test.assertEqual(ifa.ndim, 1)
test.assertEqual(ifa.shape, idata.shape)
test.assertEqual(ifa.size, idata.size)
wp.launch(fa_kernel_indexed, dim=ifa.size, inputs=[ifa, idata], device=device)
wp.synchronize_device(device)
@wp.kernel
def fa_generic_dtype_kernel(a: wp.fabricarray(dtype=Any), b: wp.fabricarray(dtype=Any)):
i = wp.tid()
b[i] = a[i] + a[i]
@wp.kernel
def fa_generic_dtype_kernel_indexed(a: wp.indexedfabricarray(dtype=Any), b: wp.indexedfabricarray(dtype=Any)):
i = wp.tid()
b[i] = a[i] + a[i]
def test_fabricarray_generic_dtype(test, device):
for T in _fabric_types:
if hasattr(T, "_wp_scalar_type_"):
nptype = wp.types.warp_type_to_np_dtype[T._wp_scalar_type_]
else:
nptype = wp.types.warp_type_to_np_dtype[T]
data = wp.array(data=np.arange(10, dtype=nptype), device=device)
data_iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=data_iface, attrib="foo")
result = wp.zeros_like(data)
result_iface = _create_fabric_array_interface(result, "foo", copy=True)
fb = wp.fabricarray(data=result_iface, attrib="foo")
test.assertEqual(fa.dtype, fb.dtype)
test.assertEqual(fa.ndim, fb.ndim)
test.assertEqual(fa.shape, fb.shape)
test.assertEqual(fa.size, fb.size)
wp.launch(fa_generic_dtype_kernel, dim=fa.size, inputs=[fa, fb], device=device)
assert_np_equal(fb.numpy(), 2 * fa.numpy())
# reset data
wp.copy(fa, data)
wp.copy(fb, result)
# test indexed
indices = wp.array(data=np.arange(1, data.size, 2, dtype=np.int32), device=device)
ifa = fa[indices]
ifb = fb[indices]
test.assertEqual(ifa.dtype, ifb.dtype)
test.assertEqual(ifa.ndim, ifb.ndim)
test.assertEqual(ifa.shape, ifb.shape)
test.assertEqual(ifa.size, ifb.size)
wp.launch(fa_generic_dtype_kernel_indexed, dim=ifa.size, inputs=[ifa, ifb], device=device)
assert_np_equal(ifb.numpy(), 2 * ifa.numpy())
@wp.kernel
def fa_generic_array_kernel(a: Any, b: Any):
i = wp.tid()
b[i] = a[i] + a[i]
def test_fabricarray_generic_array(test, device):
for T in _fabric_types:
if hasattr(T, "_wp_scalar_type_"):
nptype = wp.types.warp_type_to_np_dtype[T._wp_scalar_type_]
else:
nptype = wp.types.warp_type_to_np_dtype[T]
data = wp.array(data=np.arange(100, dtype=nptype), device=device)
data_iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=data_iface, attrib="foo")
result = wp.zeros_like(data)
result_iface = _create_fabric_array_interface(result, "foo", copy=True)
fb = wp.fabricarray(data=result_iface, attrib="foo")
test.assertEqual(fa.dtype, fb.dtype)
test.assertEqual(fa.ndim, fb.ndim)
test.assertEqual(fa.shape, fb.shape)
test.assertEqual(fa.size, fb.size)
wp.launch(fa_generic_array_kernel, dim=fa.size, inputs=[fa, fb], device=device)
assert_np_equal(fb.numpy(), 2 * fa.numpy())
# reset data
wp.copy(fa, data)
wp.copy(fb, result)
# test indexed
indices = wp.array(data=np.arange(1, data.size, 2, dtype=np.int32), device=device)
ifa = fa[indices]
ifb = fb[indices]
test.assertEqual(ifa.dtype, ifb.dtype)
test.assertEqual(ifa.ndim, ifb.ndim)
test.assertEqual(ifa.shape, ifb.shape)
test.assertEqual(ifa.size, ifb.size)
wp.launch(fa_generic_array_kernel, dim=ifa.size, inputs=[ifa, ifb], device=device)
assert_np_equal(ifb.numpy(), 2 * ifa.numpy())
def test_fabricarray_empty(test, device):
# Test whether common operations work with empty (zero-sized) indexed arrays
# without throwing exceptions.
def test_empty_ops(nrows, ncols, wptype, nptype):
# 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_
else:
dtype_shape = ()
fill_value = wptype(42)
# create an empty data array
data = wp.empty(0, dtype=wptype, device=device)
iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=iface, attrib="foo")
test.assertEqual(fa.size, 0)
test.assertEqual(fa.shape, (0,))
# all of these methods should succeed with zero-sized arrays
fa.zero_()
fa.fill_(fill_value)
fb = fa.contiguous()
fb = wp.empty_like(fa)
fb = wp.zeros_like(fa)
fb = wp.full_like(fa, fill_value)
fb = wp.clone(fa)
wp.copy(fa, fb)
fa.assign(fb)
na = fa.numpy()
test.assertEqual(na.size, 0)
test.assertEqual(na.shape, (0, *dtype_shape))
test.assertEqual(na.dtype, nptype)
test.assertEqual(fa.list(), [])
# test indexed
# create a zero-sized array of indices
indices = wp.empty(0, dtype=int, device=device)
ifa = fa[indices]
test.assertEqual(ifa.size, 0)
test.assertEqual(ifa.shape, (0,))
# all of these methods should succeed with zero-sized arrays
ifa.zero_()
ifa.fill_(fill_value)
ifb = ifa.contiguous()
ifb = wp.empty_like(ifa)
ifb = wp.zeros_like(ifa)
ifb = wp.full_like(ifa, fill_value)
ifb = wp.clone(ifa)
wp.copy(ifa, ifb)
ifa.assign(ifb)
na = ifa.numpy()
test.assertEqual(na.size, 0)
test.assertEqual(na.shape, (0, *dtype_shape))
test.assertEqual(na.dtype, nptype)
test.assertEqual(ifa.list(), [])
# test with scalars, vectors, and matrices
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# scalars
test_empty_ops(0, 0, wptype, nptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_ops(0, ncols, wptype, nptype)
# square matrices (the Fabric interface only supports square matrices right now)
test_empty_ops(ncols, ncols, wptype, nptype)
def test_fabricarray_fill_scalar(test, device):
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# create a data array
data = wp.zeros(100, dtype=wptype, device=device)
iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=iface, attrib="foo")
assert_np_equal(fa.numpy(), np.zeros(fa.shape, dtype=nptype))
# fill with int value
fill_value = 42
fa.fill_(fill_value)
assert_np_equal(fa.numpy(), np.full(fa.shape, fill_value, dtype=nptype))
fa.zero_()
assert_np_equal(fa.numpy(), np.zeros(fa.shape, dtype=nptype))
if wptype in wp.types.float_types:
# fill with float value
fill_value = 13.37
fa.fill_(fill_value)
assert_np_equal(fa.numpy(), np.full(fa.shape, fill_value, dtype=nptype))
# fill with Warp scalar value
fill_value = wptype(17)
fa.fill_(fill_value)
assert_np_equal(fa.numpy(), np.full(fa.shape, fill_value.value, dtype=nptype))
# reset data
wp.copy(fa, data)
# test indexed
indices1 = wp.array(data=np.arange(1, data.size, 2, dtype=np.int32), device=device)
ifa = fa[indices1]
# ensure that the other indices remain unchanged
indices2 = wp.array(data=np.arange(0, data.size, 2, dtype=np.int32), device=device)
ifb = fa[indices2]
assert_np_equal(ifa.numpy(), np.zeros(ifa.shape, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros(ifb.shape, dtype=nptype))
# fill with int value
fill_value = 42
ifa.fill_(fill_value)
assert_np_equal(ifa.numpy(), np.full(ifa.shape, fill_value, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros(ifb.shape, dtype=nptype))
ifa.zero_()
assert_np_equal(ifa.numpy(), np.zeros(ifa.shape, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros(ifb.shape, dtype=nptype))
if wptype in wp.types.float_types:
# fill with float value
fill_value = 13.37
ifa.fill_(fill_value)
assert_np_equal(ifa.numpy(), np.full(ifa.shape, fill_value, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros(ifb.shape, dtype=nptype))
# fill with Warp scalar value
fill_value = wptype(17)
ifa.fill_(fill_value)
assert_np_equal(ifa.numpy(), np.full(ifa.shape, fill_value.value, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros(ifb.shape, dtype=nptype))
def test_fabricarray_fill_vector(test, device):
# test filling a vector array with scalar or vector values (vec_type, list, or numpy array)
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_
data = wp.zeros(100, dtype=vec_type, device=device)
iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=iface, attrib="foo")
assert_np_equal(fa.numpy(), np.zeros((*fa.shape, vec_len), dtype=nptype))
# fill with int scalar
fill_value = 42
fa.fill_(fill_value)
assert_np_equal(fa.numpy(), np.full((*fa.shape, vec_len), fill_value, dtype=nptype))
# test zeroing
fa.zero_()
assert_np_equal(fa.numpy(), np.zeros((*fa.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)
expected = np.tile(fill_arr, fa.size).reshape((*fa.shape, vec_len))
# fill with list of vector length
fa.fill_(fill_list)
assert_np_equal(fa.numpy(), expected)
# clear
fa.zero_()
# fill with numpy array of vector length
fa.fill_(fill_arr)
assert_np_equal(fa.numpy(), expected)
# clear
fa.zero_()
# fill with vec instance
fa.fill_(fill_vec)
assert_np_equal(fa.numpy(), expected)
if wptype in wp.types.float_types:
# fill with float scalar
fill_value = 13.37
fa.fill_(fill_value)
assert_np_equal(fa.numpy(), np.full((*fa.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]
fa.fill_(fill_list)
expected = np.tile(np.array(fill_list, dtype=nptype), fa.size).reshape((*fa.shape, vec_len))
assert_np_equal(fa.numpy(), expected)
# reset data
wp.copy(fa, data)
# test indexed
indices1 = wp.array(data=np.arange(1, data.size, 2, dtype=np.int32), device=device)
ifa = fa[indices1]
# ensure that the other indices remain unchanged
indices2 = wp.array(data=np.arange(0, data.size, 2, dtype=np.int32), device=device)
ifb = fa[indices2]
assert_np_equal(ifa.numpy(), np.zeros((*ifa.shape, vec_len), dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
# fill with int scalar
fill_value = 42
ifa.fill_(fill_value)
assert_np_equal(ifa.numpy(), np.full((*ifa.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
# test zeroing
ifa.zero_()
assert_np_equal(ifa.numpy(), np.zeros((*ifa.shape, vec_len), dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.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)
expected = np.tile(fill_arr, ifa.size).reshape((*ifa.shape, vec_len))
# fill with list of vector length
ifa.fill_(fill_list)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
# clear
ifa.zero_()
# fill with numpy array of vector length
ifa.fill_(fill_arr)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
# clear
ifa.zero_()
# fill with vec instance
ifa.fill_(fill_vec)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
if wptype in wp.types.float_types:
# fill with float scalar
fill_value = 13.37
ifa.fill_(fill_value)
assert_np_equal(ifa.numpy(), np.full((*ifa.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
# fill with float list of vector length
fill_list = [-2.5, -1.25, 1.25, 2.5, 5.0][:vec_len]
ifa.fill_(fill_list)
expected = np.tile(np.array(fill_list, dtype=nptype), ifa.size).reshape((*ifa.shape, vec_len))
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, vec_len), dtype=nptype))
def test_fabricarray_fill_matrix(test, device):
# test filling a matrix array with scalar or matrix values (mat_type, nested list, or 2d numpy array)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# matrix types
matrix_types = [
# square matrices only
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
]
for mat_type in matrix_types:
mat_len = mat_type._length_
mat_shape = mat_type._shape_
data = wp.zeros(100, dtype=mat_type, device=device)
iface = _create_fabric_array_interface(data, "foo", copy=True)
fa = wp.fabricarray(data=iface, attrib="foo")
assert_np_equal(fa.numpy(), np.zeros((*fa.shape, *mat_shape), dtype=nptype))
# fill with scalar
fill_value = 42
fa.fill_(fill_value)
assert_np_equal(fa.numpy(), np.full((*fa.shape, *mat_shape), fill_value, dtype=nptype))
# test zeroing
fa.zero_()
assert_np_equal(fa.numpy(), np.zeros((*fa.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)
expected = np.tile(fill_arr1, fa.size).reshape((*fa.shape, *mat_shape))
# fill with 1d numpy array
fa.fill_(fill_arr1)
assert_np_equal(fa.numpy(), expected)
# clear
fa.zero_()
# fill with 2d numpy array
fa.fill_(fill_arr2)
assert_np_equal(fa.numpy(), expected)
# clear
fa.zero_()
# fill with flat list
fa.fill_(fill_list1)
assert_np_equal(fa.numpy(), expected)
# clear
fa.zero_()
# fill with nested list
fa.fill_(fill_list2)
assert_np_equal(fa.numpy(), expected)
# clear
fa.zero_()
# fill with mat instance
fa.fill_(fill_mat)
assert_np_equal(fa.numpy(), expected)
# reset data
wp.copy(fa, data)
# test indexed
indices1 = wp.array(data=np.arange(1, data.size, 2, dtype=np.int32), device=device)
ifa = fa[indices1]
# ensure that the other indices remain unchanged
indices2 = wp.array(data=np.arange(0, data.size, 2, dtype=np.int32), device=device)
ifb = fa[indices2]
assert_np_equal(ifa.numpy(), np.zeros((*ifa.shape, *mat_shape), dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
# fill with scalar
fill_value = 42
ifa.fill_(fill_value)
assert_np_equal(ifa.numpy(), np.full((*ifa.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
# test zeroing
ifa.zero_()
assert_np_equal(ifa.numpy(), np.zeros((*ifa.shape, *mat_shape), dtype=nptype))
assert_np_equal(ifb.numpy(), np.zeros((*ifb.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)
expected = np.tile(fill_arr1, ifa.size).reshape((*ifa.shape, *mat_shape))
# fill with 1d numpy array
ifa.fill_(fill_arr1)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
# clear
ifa.zero_()
# fill with 2d numpy array
ifa.fill_(fill_arr2)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
# clear
ifa.zero_()
# fill with flat list
ifa.fill_(fill_list1)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
# clear
ifa.zero_()
# fill with nested list
ifa.fill_(fill_list2)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
# clear
ifa.zero_()
# fill with mat instance
ifa.fill_(fill_mat)
assert_np_equal(ifa.numpy(), expected)
assert_np_equal(ifb.numpy(), np.zeros((*ifb.shape, *mat_shape), dtype=nptype))
@wp.kernel
def fa_generic_sums_kernel(a: wp.fabricarrayarray(dtype=Any), sums: wp.array(dtype=Any)):
i = wp.tid()
# get sub-array using wp::view()
row = a[i]
# get sub-array length
count = row.shape[0]
# compute sub-array sum
for j in range(count):
sums[i] = sums[i] + row[j]
@wp.kernel
def fa_generic_sums_kernel_indexed(a: wp.indexedfabricarrayarray(dtype=Any), sums: wp.array(dtype=Any)):
i = wp.tid()
# get sub-array using wp::view()
row = a[i]
# get sub-array length
count = row.shape[0]
# compute sub-array sum
for j in range(count):
sums[i] = sums[i] + row[j]
def test_fabricarrayarray(test, device):
for T in _fabric_types:
if hasattr(T, "_wp_scalar_type_"):
nptype = wp.types.warp_type_to_np_dtype[T._wp_scalar_type_]
else:
nptype = wp.types.warp_type_to_np_dtype[T]
n = 100
min_length = 1
max_length = 10
arrays = []
expected_sums = []
expected_sums_indexed = []
# generate data arrays
length = min_length
for i in range(n):
if length > max_length:
length = min_length
na = np.arange(1, length + 1, dtype=nptype)
arrays.append(wp.array(data=na, device=device))
expected_sums.append(na.sum())
# every second index
if i % 2 == 0:
expected_sums_indexed.append(na.sum())
length += 1
data_iface = _create_fabric_array_array_interface(arrays, "foo")
fa = wp.fabricarrayarray(data=data_iface, attrib="foo")
sums = wp.zeros_like(fa)
test.assertEqual(fa.dtype, sums.dtype)
test.assertEqual(fa.ndim, 2)
test.assertEqual(sums.ndim, 1)
test.assertEqual(fa.shape, sums.shape)
test.assertEqual(fa.size, sums.size)
wp.launch(fa_generic_sums_kernel, dim=fa.size, inputs=[fa, sums], device=device)
assert_np_equal(sums.numpy(), np.array(expected_sums, dtype=nptype))
# test indexed
indices = wp.array(data=np.arange(0, n, 2, dtype=np.int32), device=device)
ifa = fa[indices]
sums = wp.zeros_like(ifa)
test.assertEqual(ifa.dtype, sums.dtype)
test.assertEqual(ifa.ndim, 2)
test.assertEqual(sums.ndim, 1)
test.assertEqual(ifa.shape, sums.shape)
test.assertEqual(ifa.size, sums.size)
wp.launch(fa_generic_sums_kernel_indexed, dim=ifa.size, inputs=[ifa, sums], device=device)
assert_np_equal(sums.numpy(), np.array(expected_sums_indexed, dtype=nptype))
# explicit kernel overloads
for T in _fabric_types:
wp.overload(fa_generic_dtype_kernel, [wp.fabricarray(dtype=T), wp.fabricarray(dtype=T)])
wp.overload(fa_generic_dtype_kernel_indexed, [wp.indexedfabricarray(dtype=T), wp.indexedfabricarray(dtype=T)])
wp.overload(fa_generic_array_kernel, [wp.fabricarray(dtype=T), wp.fabricarray(dtype=T)])
wp.overload(fa_generic_array_kernel, [wp.indexedfabricarray(dtype=T), wp.indexedfabricarray(dtype=T)])
wp.overload(fa_generic_sums_kernel, [wp.fabricarrayarray(dtype=T), wp.array(dtype=T)])
wp.overload(fa_generic_sums_kernel_indexed, [wp.indexedfabricarrayarray(dtype=T), wp.array(dtype=T)])
def register(parent):
devices = get_test_devices()
class TestFabricArray(parent):
pass
# fabric arrays
add_function_test(TestFabricArray, "test_fabricarray_kernel", test_fabricarray_kernel, devices=devices)
add_function_test(TestFabricArray, "test_fabricarray_empty", test_fabricarray_empty, devices=devices)
add_function_test(
TestFabricArray, "test_fabricarray_generic_dtype", test_fabricarray_generic_dtype, devices=devices
)
add_function_test(
TestFabricArray, "test_fabricarray_generic_array", test_fabricarray_generic_array, devices=devices
)
add_function_test(TestFabricArray, "test_fabricarray_fill_scalar", test_fabricarray_fill_scalar, devices=devices)
add_function_test(TestFabricArray, "test_fabricarray_fill_vector", test_fabricarray_fill_vector, devices=devices)
add_function_test(TestFabricArray, "test_fabricarray_fill_matrix", test_fabricarray_fill_matrix, devices=devices)
# fabric arrays of arrays
add_function_test(TestFabricArray, "test_fabricarrayarray", test_fabricarrayarray, devices=devices)
return TestFabricArray
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_fabricarray.py |
# This file is used to test reloading module references.
import warp as wp
wp.init()
@wp.func
def more_magic():
return 2.0
| warp-main | warp/tests/test_reference_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.
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)]
arr_np = randvals((10, 5), dtype)
arr = wp.array(arr_np, dtype=wptype, requires_grad=True, device=device)
assert_np_equal(arr.numpy(), arr_np, tol=tol)
def test_unary_ops(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_unary(
inputs: wp.array(dtype=wptype, ndim=2),
outputs: wp.array(dtype=wptype, ndim=2),
):
for i in range(10):
i0 = inputs[0, i]
i1 = inputs[1, i]
i2 = inputs[2, i]
i3 = inputs[3, i]
i4 = inputs[4, i]
# multiply outputs by 2 so we've got something to backpropagate:
outputs[0, i] = wptype(2.0) * (+i0)
outputs[1, i] = wptype(2.0) * (-i1)
outputs[2, i] = wptype(2.0) * wp.sign(i2)
outputs[3, i] = wptype(2.0) * wp.abs(i3)
outputs[4, i] = wptype(2.0) * wp.step(i4)
kernel = getkernel(check_unary, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
if dtype in np_float_types:
inputs = wp.array(np.random.randn(5, 10).astype(dtype), dtype=wptype, requires_grad=True, device=device)
else:
inputs = wp.array(
np.random.randint(-2, 3, size=(5, 10), dtype=dtype), dtype=wptype, requires_grad=True, device=device
)
outputs = wp.zeros_like(inputs)
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
assert_np_equal(outputs.numpy()[0], 2 * inputs.numpy()[0], tol=tol)
assert_np_equal(outputs.numpy()[1], -2 * inputs.numpy()[1], tol=tol)
expected = 2 * np.sign(inputs.numpy()[2])
expected[expected == 0] = 2
assert_np_equal(outputs.numpy()[2], expected, tol=tol)
assert_np_equal(outputs.numpy()[3], 2 * np.abs(inputs.numpy()[3]), tol=tol)
assert_np_equal(outputs.numpy()[4], 2 * (1 - np.heaviside(inputs.numpy()[4], 1)), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
# grad of 2x:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device)
tape.backward(loss=out)
expected_grads = np.zeros_like(inputs.numpy())
expected_grads[0, i] = 2
assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol)
tape.zero()
# grad of -2x:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device)
tape.backward(loss=out)
expected_grads = np.zeros_like(inputs.numpy())
expected_grads[1, i] = -2
assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol)
tape.zero()
# grad of 2 * sign(x):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 2, i], outputs=[out], device=device)
tape.backward(loss=out)
expected_grads = np.zeros_like(inputs.numpy())
assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol)
tape.zero()
# grad of 2 * abs(x):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 3, i], outputs=[out], device=device)
tape.backward(loss=out)
expected_grads = np.zeros_like(inputs.numpy())
expected_grads[3, i] = 2 * np.sign(inputs.numpy()[3, i])
assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol)
tape.zero()
# grad of 2 * step(x):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 4, i], outputs=[out], device=device)
tape.backward(loss=out)
expected_grads = np.zeros_like(inputs.numpy())
assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol)
tape.zero()
def test_nonzero(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_nonzero(
inputs: wp.array(dtype=wptype),
outputs: wp.array(dtype=wptype),
):
for i in range(10):
i0 = inputs[i]
outputs[i] = wp.nonzero(i0)
kernel = getkernel(check_nonzero, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
inputs = wp.array(np.random.randint(-2, 3, size=10).astype(dtype), dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(inputs)
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
assert_np_equal(outputs.numpy(), (inputs.numpy() != 0))
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
# grad should just be zero:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[out], device=device)
tape.backward(loss=out)
expected_grads = np.zeros_like(inputs.numpy())
assert_np_equal(tape.gradients[inputs].numpy(), expected_grads, tol=tol)
tape.zero()
def test_binary_ops(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)]
def check_binary_ops(
in1: wp.array(dtype=wptype, ndim=2),
in2: wp.array(dtype=wptype, ndim=2),
outputs: wp.array(dtype=wptype, ndim=2),
):
for i in range(10):
i0 = in1[0, i]
i1 = in1[1, i]
i2 = in1[2, i]
i3 = in1[3, i]
i4 = in1[4, i]
i5 = in1[5, i]
i6 = in1[6, i]
i7 = in1[7, i]
j0 = in2[0, i]
j1 = in2[1, i]
j2 = in2[2, i]
j3 = in2[3, i]
j4 = in2[4, i]
j5 = in2[5, i]
j6 = in2[6, i]
j7 = in2[7, i]
outputs[0, i] = wptype(2) * wp.mul(i0, j0)
outputs[1, i] = wptype(2) * wp.div(i1, j1)
outputs[2, i] = wptype(2) * wp.add(i2, j2)
outputs[3, i] = wptype(2) * wp.sub(i3, j3)
outputs[4, i] = wptype(2) * wp.mod(i4, j4)
outputs[5, i] = wptype(2) * wp.min(i5, j5)
outputs[6, i] = wptype(2) * wp.max(i6, j6)
outputs[7, i] = wptype(2) * wp.floordiv(i7, j7)
kernel = getkernel(check_binary_ops, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
vals1 = randvals([8, 10], dtype)
if dtype in [np_unsigned_int_types]:
vals2 = vals1 + randvals([8, 10], dtype)
else:
vals2 = np.abs(randvals([8, 10], dtype))
in1 = wp.array(vals1, dtype=wptype, requires_grad=True, device=device)
in2 = wp.array(vals2, dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(in1)
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
assert_np_equal(outputs.numpy()[0], 2 * in1.numpy()[0] * in2.numpy()[0], tol=tol)
if dtype in np_float_types:
assert_np_equal(outputs.numpy()[1], 2 * in1.numpy()[1] / (in2.numpy()[1]), tol=tol)
else:
assert_np_equal(outputs.numpy()[1], 2 * (in1.numpy()[1] // (in2.numpy()[1])), tol=tol)
assert_np_equal(outputs.numpy()[2], 2 * (in1.numpy()[2] + (in2.numpy()[2])), tol=tol)
assert_np_equal(outputs.numpy()[3], 2 * (in1.numpy()[3] - (in2.numpy()[3])), tol=tol)
# ...so this is actually the desired behaviour right? Looks like wp.mod doesn't behave like
# python's % operator or np.mod()...
assert_np_equal(
outputs.numpy()[4],
2
* (
(in1.numpy()[4])
- (in2.numpy()[4]) * np.sign(in1.numpy()[4]) * np.floor(np.abs(in1.numpy()[4]) / (in2.numpy()[4]))
),
tol=tol,
)
assert_np_equal(outputs.numpy()[5], 2 * np.minimum(in1.numpy()[5], in2.numpy()[5]), tol=tol)
assert_np_equal(outputs.numpy()[6], 2 * np.maximum(in1.numpy()[6], in2.numpy()[6]), tol=tol)
assert_np_equal(outputs.numpy()[7], 2 * np.floor_divide(in1.numpy()[7], in2.numpy()[7]), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
# multiplication:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[0, i] = 2.0 * in2.numpy()[0, i]
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[0, i] = 2.0 * in1.numpy()[0, i]
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# division:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[1, i] = 2.0 / (in2.numpy()[1, i])
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
# y = x1/x2
# dy/dx2 = -x1/x2^2
expected[1, i] = (-2.0) * (in1.numpy()[1, i] / (in2.numpy()[1, i] ** 2))
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# addition:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 2, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[2, i] = 2.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[2, i] = 2.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# subtraction:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 3, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[3, i] = 2.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[3, i] = -2.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# modulus. unless at discontinuities,
# d/dx1( x1 % x2 ) == 1
# d/dx2( x1 % x2 ) == 0
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 4, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[4, i] = 2.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[4, i] = 0.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# min
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 5, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[5, i] = 2.0 if (in1.numpy()[5, i] < in2.numpy()[5, i]) else 0.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[5, i] = 2.0 if (in2.numpy()[5, i] < in1.numpy()[5, i]) else 0.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# max
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 6, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[6, i] = 2.0 if (in1.numpy()[6, i] > in2.numpy()[6, i]) else 0.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[6, i] = 2.0 if (in2.numpy()[6, i] > in1.numpy()[6, i]) else 0.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# floor_divide. Returns integers so gradient is zero
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 7, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
def test_special_funcs(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)]
def check_special_funcs(
inputs: wp.array(dtype=wptype, ndim=2),
outputs: wp.array(dtype=wptype, ndim=2),
):
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(10):
outputs[0, i] = wptype(2) * wp.log(inputs[0, i])
outputs[1, i] = wptype(2) * wp.log2(inputs[1, i])
outputs[2, i] = wptype(2) * wp.log10(inputs[2, i])
outputs[3, i] = wptype(2) * wp.exp(inputs[3, i])
outputs[4, i] = wptype(2) * wp.atan(inputs[4, i])
outputs[5, i] = wptype(2) * wp.sin(inputs[5, i])
outputs[6, i] = wptype(2) * wp.cos(inputs[6, i])
outputs[7, i] = wptype(2) * wp.sqrt(inputs[7, i])
outputs[8, i] = wptype(2) * wp.tan(inputs[8, i])
outputs[9, i] = wptype(2) * wp.sinh(inputs[9, i])
outputs[10, i] = wptype(2) * wp.cosh(inputs[10, i])
outputs[11, i] = wptype(2) * wp.tanh(inputs[11, i])
outputs[12, i] = wptype(2) * wp.acos(inputs[12, i])
outputs[13, i] = wptype(2) * wp.asin(inputs[13, i])
kernel = getkernel(check_special_funcs, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
invals = np.random.randn(14, 10).astype(dtype)
invals[[0, 1, 2, 7]] = 0.1 + np.abs(invals[[0, 1, 2, 7]])
invals[12] = np.clip(invals[12], -0.9, 0.9)
invals[13] = np.clip(invals[13], -0.9, 0.9)
inputs = wp.array(invals, dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(inputs)
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
assert_np_equal(outputs.numpy()[0], 2 * np.log(inputs.numpy()[0]), tol=tol)
assert_np_equal(outputs.numpy()[1], 2 * np.log2(inputs.numpy()[1]), tol=tol)
assert_np_equal(outputs.numpy()[2], 2 * np.log10(inputs.numpy()[2]), tol=tol)
assert_np_equal(outputs.numpy()[3], 2 * np.exp(inputs.numpy()[3]), tol=tol)
assert_np_equal(outputs.numpy()[4], 2 * np.arctan(inputs.numpy()[4]), tol=tol)
assert_np_equal(outputs.numpy()[5], 2 * np.sin(inputs.numpy()[5]), tol=tol)
assert_np_equal(outputs.numpy()[6], 2 * np.cos(inputs.numpy()[6]), tol=tol)
assert_np_equal(outputs.numpy()[7], 2 * np.sqrt(inputs.numpy()[7]), tol=tol)
assert_np_equal(outputs.numpy()[8], 2 * np.tan(inputs.numpy()[8]), tol=tol)
assert_np_equal(outputs.numpy()[9], 2 * np.sinh(inputs.numpy()[9]), tol=tol)
assert_np_equal(outputs.numpy()[10], 2 * np.cosh(inputs.numpy()[10]), tol=tol)
assert_np_equal(outputs.numpy()[11], 2 * np.tanh(inputs.numpy()[11]), tol=tol)
assert_np_equal(outputs.numpy()[12], 2 * np.arccos(inputs.numpy()[12]), tol=tol)
assert_np_equal(outputs.numpy()[13], 2 * np.arcsin(inputs.numpy()[13]), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
# log:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[0, i] = 2.0 / inputs.numpy()[0, i]
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# log2:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[1, i] = 2.0 / (inputs.numpy()[1, i] * np.log(2.0))
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# log10:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 2, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[2, i] = 2.0 / (inputs.numpy()[2, i] * np.log(10.0))
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# exp:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 3, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[3, i] = outputs.numpy()[3, i]
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# arctan:
# looks like the autodiff formula in warp was wrong? Was (1 + x^2) rather than
# 1/(1 + x^2)
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 4, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[4, i] = 2.0 / (inputs.numpy()[4, i] ** 2 + 1)
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# sin:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 5, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[5, i] = np.cos(inputs.numpy()[5, i]) * 2
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# cos:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 6, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[6, i] = -np.sin(inputs.numpy()[6, i]) * 2.0
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# sqrt:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 7, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[7, i] = 1.0 / (np.sqrt(inputs.numpy()[7, i]))
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# tan:
# looks like there was a bug in autodiff formula here too - gradient was zero if cos(x) > 0
# (should have been "if(cosx != 0)")
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 8, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[8, i] = 2.0 / (np.cos(inputs.numpy()[8, i]) ** 2)
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=200 * tol)
tape.zero()
# sinh:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 9, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[9, i] = 2.0 * np.cosh(inputs.numpy()[9, i])
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# cosh:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 10, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[10, i] = 2.0 * np.sinh(inputs.numpy()[10, i])
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# tanh:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 11, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[11, i] = 2.0 / (np.cosh(inputs.numpy()[11, i]) ** 2)
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# arccos:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 12, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[12, i] = -2.0 / np.sqrt(1 - inputs.numpy()[12, i] ** 2)
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=tol)
tape.zero()
# arcsin:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 13, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(inputs.numpy())
expected[13, i] = 2.0 / np.sqrt(1 - inputs.numpy()[13, i] ** 2)
assert_np_equal(tape.gradients[inputs].numpy(), expected, tol=6 * tol)
tape.zero()
def test_special_funcs_2arg(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)]
def check_special_funcs_2arg(
in1: wp.array(dtype=wptype, ndim=2),
in2: wp.array(dtype=wptype, ndim=2),
outputs: wp.array(dtype=wptype, ndim=2),
):
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(10):
outputs[0, i] = wptype(2) * wp.pow(in1[0, i], in2[0, i])
outputs[1, i] = wptype(2) * wp.atan2(in1[1, i], in2[1, i])
kernel = getkernel(check_special_funcs_2arg, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
in1 = wp.array(np.abs(randvals([2, 10], dtype)), dtype=wptype, requires_grad=True, device=device)
in2 = wp.array(randvals([2, 10], dtype), dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(in1)
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
assert_np_equal(outputs.numpy()[0], 2.0 * np.power(in1.numpy()[0], in2.numpy()[0]), tol=tol)
assert_np_equal(outputs.numpy()[1], 2.0 * np.arctan2(in1.numpy()[1], in2.numpy()[1]), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
# pow:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[0, i] = 2.0 * in2.numpy()[0, i] * np.power(in1.numpy()[0, i], in2.numpy()[0, i] - 1)
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=5 * tol)
expected[0, i] = 2.0 * np.power(in1.numpy()[0, i], in2.numpy()[0, i]) * np.log(in1.numpy()[0, i])
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
# atan2:
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(in1.numpy())
expected[1, i] = 2.0 * in2.numpy()[1, i] / (in1.numpy()[1, i] ** 2 + in2.numpy()[1, i] ** 2)
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[1, i] = -2.0 * in1.numpy()[1, i] / (in1.numpy()[1, i] ** 2 + in2.numpy()[1, i] ** 2)
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
tape.zero()
def test_float_to_int(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_float_to_int(
inputs: wp.array(dtype=wptype, ndim=2),
outputs: wp.array(dtype=wptype, ndim=2),
):
for i in range(10):
outputs[0, i] = wp.round(inputs[0, i])
outputs[1, i] = wp.rint(inputs[1, i])
outputs[2, i] = wp.trunc(inputs[2, i])
outputs[3, i] = wp.floor(inputs[3, i])
outputs[4, i] = wp.ceil(inputs[4, i])
kernel = getkernel(check_float_to_int, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
inputs = wp.array(np.random.randn(5, 10).astype(dtype), dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(inputs)
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
assert_np_equal(outputs.numpy()[0], np.round(inputs.numpy()[0]))
assert_np_equal(outputs.numpy()[1], np.rint(inputs.numpy()[1]))
assert_np_equal(outputs.numpy()[2], np.trunc(inputs.numpy()[2]))
assert_np_equal(outputs.numpy()[3], np.floor(inputs.numpy()[3]))
assert_np_equal(outputs.numpy()[4], np.ceil(inputs.numpy()[4]))
# all the gradients should be zero as these functions are piecewise constant:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(10):
for j in range(5):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[inputs], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, j, i], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(tape.gradients[inputs].numpy(), np.zeros_like(inputs.numpy()), tol=tol)
tape.zero()
def test_interp(test, device, dtype, register_kernels=False):
np.random.seed(123)
tol = {
np.float16: 1.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def check_interp(
in1: wp.array(dtype=wptype, ndim=2),
in2: wp.array(dtype=wptype, ndim=2),
in3: wp.array(dtype=wptype, ndim=2),
outputs: wp.array(dtype=wptype, ndim=2),
):
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(10):
outputs[0, i] = wptype(2) * wp.smoothstep(in1[0, i], in2[0, i], in3[0, i])
outputs[1, i] = wptype(2) * wp.lerp(in1[1, i], in2[1, i], in3[1, i])
kernel = getkernel(check_interp, suffix=dtype.__name__)
output_select_kernel = get_select_kernel2(wptype)
if register_kernels:
return
e0 = randvals([2, 10], dtype)
e1 = e0 + randvals([2, 10], dtype) + 0.1
in1 = wp.array(e0, dtype=wptype, requires_grad=True, device=device)
in2 = wp.array(e1, dtype=wptype, requires_grad=True, device=device)
in3 = wp.array(randvals([2, 10], dtype), dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(in1)
wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device)
edge0 = in1.numpy()[0]
edge1 = in2.numpy()[0]
t_smoothstep = in3.numpy()[0]
x = np.clip((t_smoothstep - edge0) / (edge1 - edge0), 0, 1)
smoothstep_expected = 2.0 * x * x * (3 - 2 * x)
assert_np_equal(outputs.numpy()[0], smoothstep_expected, tol=tol)
a = in1.numpy()[1]
b = in2.numpy()[1]
t = in3.numpy()[1]
assert_np_equal(outputs.numpy()[1], 2.0 * (a * (1 - t) + b * t), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(10):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 0, i], outputs=[out], device=device)
tape.backward(loss=out)
# e0 = in1
# e1 = in2
# t = in3
# x = clamp((t - e0) / (e1 - e0), 0,1)
# dx/dt = 1 / (e1 - e0) if e0 < t < e1 else 0
# y = x * x * (3 - 2 * x)
# y = 3 * x * x - 2 * x * x * x
# dy/dx = 6 * ( x - x^2 )
dydx = 6 * x * (1 - x)
# dy/in1 = dy/dx dx/de0 de0/din1
dxde0 = (t_smoothstep - edge1) / ((edge1 - edge0) ** 2)
dxde0[x == 0] = 0
dxde0[x == 1] = 0
expected_grads = np.zeros_like(in1.numpy())
expected_grads[0, i] = 2.0 * dydx[i] * dxde0[i]
assert_np_equal(tape.gradients[in1].numpy(), expected_grads, tol=tol)
# dy/in2 = dy/dx dx/de1 de1/din2
dxde1 = (edge0 - t_smoothstep) / ((edge1 - edge0) ** 2)
dxde1[x == 0] = 0
dxde1[x == 1] = 0
expected_grads = np.zeros_like(in1.numpy())
expected_grads[0, i] = 2.0 * dydx[i] * dxde1[i]
assert_np_equal(tape.gradients[in2].numpy(), expected_grads, tol=tol)
# dy/in3 = dy/dx dx/dt dt/din3
dxdt = 1.0 / (edge1 - edge0)
dxdt[x == 0] = 0
dxdt[x == 1] = 0
expected_grads = np.zeros_like(in1.numpy())
expected_grads[0, i] = 2.0 * dydx[i] * dxdt[i]
assert_np_equal(tape.gradients[in3].numpy(), expected_grads, tol=tol)
tape.zero()
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, 1, i], outputs=[out], device=device)
tape.backward(loss=out)
# y = a*(1-t) + b*t
# a = in1
# b = in2
# t = in3
# y = in1*( 1 - in3 ) + in2*in3
# dy/din1 = (1-in3)
expected_grads = np.zeros_like(in1.numpy())
expected_grads[1, i] = 2.0 * (1 - in3.numpy()[1, i])
assert_np_equal(tape.gradients[in1].numpy(), expected_grads, tol=tol)
# dy/din2 = in3
expected_grads = np.zeros_like(in1.numpy())
expected_grads[1, i] = 2.0 * in3.numpy()[1, i]
assert_np_equal(tape.gradients[in2].numpy(), expected_grads, tol=tol)
# dy/din3 = 8*in2 - 1.5*4*in1
expected_grads = np.zeros_like(in1.numpy())
expected_grads[1, i] = 2.0 * (in2.numpy()[1, i] - in1.numpy()[1, i])
assert_np_equal(tape.gradients[in3].numpy(), expected_grads, tol=tol)
tape.zero()
def test_clamp(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-6,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def check_clamp(
in1: wp.array(dtype=wptype),
in2: wp.array(dtype=wptype),
in3: wp.array(dtype=wptype),
outputs: wp.array(dtype=wptype),
):
for i in range(100):
# multiply output by 2 so we've got something to backpropagate:
outputs[i] = wptype(2) * wp.clamp(in1[i], in2[i], in3[i])
kernel = getkernel(check_clamp, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
in1 = wp.array(randvals([100], dtype), dtype=wptype, requires_grad=True, device=device)
starts = randvals([100], dtype)
diffs = np.abs(randvals([100], dtype))
in2 = wp.array(starts, dtype=wptype, requires_grad=True, device=device)
in3 = wp.array(starts + diffs, dtype=wptype, requires_grad=True, device=device)
outputs = wp.zeros_like(in1)
wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device)
assert_np_equal(2 * np.clip(in1.numpy(), in2.numpy(), in3.numpy()), outputs.numpy(), tol=tol)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
if dtype in np_float_types:
for i in range(100):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[in1, in2, in3], outputs=[outputs], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outputs, i], outputs=[out], device=device)
tape.backward(loss=out)
t = in1.numpy()[i]
lower = in2.numpy()[i]
upper = in3.numpy()[i]
expected = np.zeros_like(in1.numpy())
if t < lower:
expected[i] = 2.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
expected[i] = 0.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
assert_np_equal(tape.gradients[in3].numpy(), expected, tol=tol)
elif t > upper:
expected[i] = 2.0
assert_np_equal(tape.gradients[in3].numpy(), expected, tol=tol)
expected[i] = 0.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
else:
expected[i] = 2.0
assert_np_equal(tape.gradients[in1].numpy(), expected, tol=tol)
expected[i] = 0.0
assert_np_equal(tape.gradients[in2].numpy(), expected, tol=tol)
assert_np_equal(tape.gradients[in3].numpy(), expected, tol=tol)
tape.zero()
def register(parent):
devices = get_test_devices()
class TestArithmetic(parent):
pass
# these unary ops only make sense for signed values:
for dtype in np_signed_int_types + np_float_types:
add_function_test_register_kernel(
TestArithmetic, f"test_unary_ops_{dtype.__name__}", test_unary_ops, devices=devices, dtype=dtype
)
for dtype in np_float_types:
add_function_test_register_kernel(
TestArithmetic, f"test_special_funcs_{dtype.__name__}", test_special_funcs, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestArithmetic,
f"test_special_funcs_2arg_{dtype.__name__}",
test_special_funcs_2arg,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestArithmetic, f"test_interp_{dtype.__name__}", test_interp, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestArithmetic, f"test_float_to_int_{dtype.__name__}", test_float_to_int, devices=devices, dtype=dtype
)
for dtype in np_scalar_types:
add_function_test_register_kernel(
TestArithmetic, f"test_clamp_{dtype.__name__}", test_clamp, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestArithmetic, f"test_nonzero_{dtype.__name__}", test_nonzero, devices=devices, dtype=dtype
)
add_function_test(TestArithmetic, f"test_arrays_{dtype.__name__}", test_arrays, devices=devices, dtype=dtype)
add_function_test_register_kernel(
TestArithmetic, f"test_binary_ops_{dtype.__name__}", test_binary_ops, devices=devices, dtype=dtype
)
return TestArithmetic
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_arithmetic.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 sys
import numpy as np
import warp as wp
# default test mode (see get_test_devices())
# "basic" - only run on CPU and first GPU device
# "unique" - run on CPU and all unique GPU arches
# "all" - run on all devices
test_mode = "basic"
def get_test_devices(mode=None):
if mode is None:
global test_mode
mode = test_mode
devices = []
# only run on CPU and first GPU device
if mode == "basic":
if wp.is_cpu_available():
devices.append(wp.get_device("cpu"))
if wp.is_cuda_available():
devices.append(wp.get_device("cuda:0"))
# run on CPU and all unique GPU arches
elif mode == "unique":
if wp.is_cpu_available():
devices.append(wp.get_device("cpu"))
cuda_devices = wp.get_cuda_devices()
unique_cuda_devices = {}
for d in cuda_devices:
if d.arch not in unique_cuda_devices:
unique_cuda_devices[d.arch] = d
devices.extend(list(unique_cuda_devices.values()))
# run on all devices
elif mode == "all":
devices = wp.get_devices()
return devices
# redirects and captures all stdout output (including from C-libs)
class StdOutCapture:
def begin(self):
# save original
self.saved = sys.stdout
self.target = os.dup(self.saved.fileno())
# create temporary capture stream
import io, tempfile
self.tempfile = io.TextIOWrapper(
tempfile.TemporaryFile(buffering=0), encoding="utf-8", errors="replace", newline="", write_through=True
)
os.dup2(self.tempfile.fileno(), self.saved.fileno())
sys.stdout = self.tempfile
def end(self):
os.dup2(self.target, self.saved.fileno())
os.close(self.target)
self.tempfile.seek(0)
res = self.tempfile.buffer.read()
self.tempfile.close()
sys.stdout = self.saved
return str(res.decode("utf-8"))
class CheckOutput:
def __init__(self, test):
self.test = test
def __enter__(self):
# wp.force_load()
self.capture = StdOutCapture()
self.capture.begin()
def __exit__(self, exc_type, exc_value, traceback):
# ensure any stdout output is flushed
wp.synchronize()
s = self.capture.end()
if s != "":
print(s.rstrip())
# fail if test produces unexpected output (e.g.: from wp.expect_eq() builtins)
# we allow strings starting of the form "Module xxx load on device xxx"
# for lazy loaded modules
if s != "" and not s.startswith("Module"):
self.test.fail(f"Unexpected output:\n'{s.rstrip()}'")
def assert_array_equal(result, expect):
a = result.numpy()
b = expect.numpy()
if (a == b).all() == False:
raise AssertionError(f"Unexpected result, got: {a} expected: {b}")
def assert_np_equal(result, expect, tol=0.0):
a = result.flatten()
b = expect.flatten()
if tol == 0.0:
if (a == b).all() == False:
raise AssertionError(f"Unexpected result, got: {a} expected: {b}")
else:
delta = a - b
err = np.max(np.abs(delta))
if err > tol:
raise AssertionError(
f"Maximum expected error exceeds tolerance got: {a}, expected: {b}, with err: {err} > {tol}"
)
def create_test_func(func, device, **kwargs):
# pass args to func
def test_func(self):
with CheckOutput(self):
func(self, device, **kwargs)
return test_func
def sanitize_identifier(s):
"""replace all non-identifier characters with '_'"""
s = str(s)
if s.isidentifier():
return s
else:
import re
return re.sub("\W|^(?=\d)", "_", s)
def add_function_test(cls, name, func, devices=None, **kwargs):
if devices is None:
setattr(cls, name, create_test_func(func, None, **kwargs))
else:
for device in devices:
setattr(cls, name + "_" + sanitize_identifier(device), create_test_func(func, device, **kwargs))
def add_kernel_test(cls, kernel, dim, name=None, expect=None, inputs=None, devices=None):
def test_func(self, device):
args = []
if inputs:
args.extend(inputs)
if expect:
# allocate outputs to match results
result = wp.array(expect, dtype=int, device=device)
output = wp.zeros_like(result)
args.append(output)
# force load so that we don't generate any log output during launch
kernel.module.load(device)
with CheckOutput(self):
wp.launch(kernel, dim=dim, inputs=args, device=device)
# check output values
if expect:
assert_array_equal(output, result)
if name is None:
name = kernel.key
# device is required for kernel tests, so use all devices if none were given
if devices is None:
devices = get_test_devices()
# register test func with class for the given devices
for d in devices:
# use a lambda to forward the device to the inner test function
test_lambda = lambda test, device=d: test_func(test, device)
setattr(cls, name + "_" + sanitize_identifier(d), test_lambda)
# helper that first calls the test function to generate all kernel permuations
# so that compilation is done in one-shot instead of per-test
def add_function_test_register_kernel(cls, name, func, devices=None, **kwargs):
func(None, None, **kwargs, register_kernels=True)
add_function_test(cls, name, func, devices=devices, **kwargs)
| warp-main | warp/tests/test_base.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.kernel
def sample_mesh_query(
mesh: wp.uint64,
query_points: wp.array(dtype=wp.vec3),
query_faces: wp.array(dtype=int),
query_signs: wp.array(dtype=float),
query_dist: wp.array(dtype=float),
):
tid = wp.tid()
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = 10012.0
p = query_points[tid]
wp.mesh_query_point(mesh, p, max_dist, sign, face_index, face_u, face_v)
cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
query_signs[tid] = sign
query_faces[tid] = face_index
query_dist[tid] = wp.length(cp - p)
@wp.kernel
def sample_mesh_query_no_sign(
mesh: wp.uint64,
query_points: wp.array(dtype=wp.vec3),
query_faces: wp.array(dtype=int),
query_dist: wp.array(dtype=float),
):
tid = wp.tid()
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
max_dist = 10012.0
p = query_points[tid]
wp.mesh_query_point_no_sign(mesh, p, max_dist, face_index, face_u, face_v)
cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
query_faces[tid] = face_index
query_dist[tid] = wp.length(cp - p)
@wp.kernel
def sample_mesh_query_sign_normal(
mesh: wp.uint64,
query_points: wp.array(dtype=wp.vec3),
query_faces: wp.array(dtype=int),
query_signs: wp.array(dtype=float),
query_dist: wp.array(dtype=float),
):
tid = wp.tid()
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = 10012.0
p = query_points[tid]
wp.mesh_query_point_sign_normal(mesh, p, max_dist, sign, face_index, face_u, face_v)
cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
query_signs[tid] = sign
query_faces[tid] = face_index
query_dist[tid] = wp.length(cp - p)
@wp.kernel
def sample_mesh_query_sign_winding_number(
mesh: wp.uint64,
query_points: wp.array(dtype=wp.vec3),
query_faces: wp.array(dtype=int),
query_signs: wp.array(dtype=float),
query_dist: wp.array(dtype=float),
):
tid = wp.tid()
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = 10012.0
p = query_points[tid]
wp.mesh_query_point_sign_winding_number(mesh, p, max_dist, sign, face_index, face_u, face_v)
cp = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
query_signs[tid] = sign
query_faces[tid] = face_index
query_dist[tid] = wp.length(cp - p)
@wp.func
def triangle_closest_point(a: wp.vec3, b: wp.vec3, c: wp.vec3, p: wp.vec3):
ab = b - a
ac = c - a
ap = p - a
d1 = wp.dot(ab, ap)
d2 = wp.dot(ac, ap)
if d1 <= 0.0 and d2 <= 0.0:
return wp.vec2(1.0, 0.0)
bp = p - b
d3 = wp.dot(ab, bp)
d4 = wp.dot(ac, bp)
if d3 >= 0.0 and d4 <= d3:
return wp.vec2(0.0, 1.0)
vc = d1 * d4 - d3 * d2
v = d1 / (d1 - d3)
if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0:
return wp.vec2(1.0 - v, v)
cp = p - c
d5 = wp.dot(ab, cp)
d6 = wp.dot(ac, cp)
if d6 >= 0.0 and d5 <= d6:
return wp.vec2(0.0, 0.0)
vb = d5 * d2 - d1 * d6
w = d2 / (d2 - d6)
if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0:
return wp.vec2(1.0 - w, 0.0)
va = d3 * d6 - d5 * d4
w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0:
return wp.vec2(0.0, 1.0 - w)
denom = 1.0 / (va + vb + vc)
v = vb * denom
w = vc * denom
u = 1.0 - v - w
return wp.vec2(u, v)
@wp.func
def solid_angle(v0: wp.vec3, v1: wp.vec3, v2: wp.vec3, p: wp.vec3):
a = v0 - p
b = v1 - p
c = v2 - p
a_len = wp.length(a)
b_len = wp.length(b)
c_len = wp.length(c)
det = wp.dot(a, wp.cross(b, c))
den = a_len * b_len * c_len + wp.dot(a, b) * c_len + wp.dot(b, c) * a_len + wp.dot(c, a) * b_len
return 2.0 * wp.atan2(det, den)
@wp.kernel
def sample_mesh_brute(
tri_points: wp.array(dtype=wp.vec3),
tri_indices: wp.array(dtype=int),
tri_count: int,
query_points: wp.array(dtype=wp.vec3),
query_faces: wp.array(dtype=int),
query_signs: wp.array(dtype=float),
query_dist: wp.array(dtype=float),
):
tid = wp.tid()
min_face = int(0)
min_dist = float(1.0e6)
sum_solid_angle = float(0.0)
p = query_points[tid]
for i in range(0, tri_count):
a = tri_points[tri_indices[i * 3 + 0]]
b = tri_points[tri_indices[i * 3 + 1]]
c = tri_points[tri_indices[i * 3 + 2]]
sum_solid_angle += solid_angle(a, b, c, p)
bary = triangle_closest_point(a, b, c, p)
u = bary[0]
v = bary[1]
cp = u * a + v * b + (1.0 - u - v) * c
cp_dist = wp.length(cp - p)
if cp_dist < min_dist:
min_dist = cp_dist
min_face = i
# for an inside point, the sum of the solid angle should be 4PI
# for an outside point, the sum should be 0
query_faces[tid] = min_face
query_signs[tid] = sum_solid_angle
query_dist[tid] = min_dist
# constructs a grid of evenly spaced particles
def particle_grid(dim_x, dim_y, dim_z, lower, radius, jitter):
points = np.meshgrid(np.linspace(0, dim_x, dim_x), np.linspace(0, dim_y, dim_y), np.linspace(0, dim_z, dim_z))
points_t = np.array((points[0], points[1], points[2])).T * radius * 2.0 + np.array(lower)
points_t = points_t + np.random.rand(*points_t.shape) * radius * jitter
return points_t.reshape((-1, 3))
# triangulate a list of polygon face indices
def triangulate(face_counts, face_indices):
num_tris = np.sum(np.subtract(face_counts, 2))
num_tri_vtx = num_tris * 3
tri_indices = np.zeros(num_tri_vtx, dtype=int)
ctr = 0
wedgeIdx = 0
for nb in face_counts:
for i in range(nb - 2):
tri_indices[ctr] = face_indices[wedgeIdx]
tri_indices[ctr + 1] = face_indices[wedgeIdx + i + 1]
tri_indices[ctr + 2] = face_indices[wedgeIdx + i + 2]
ctr += 3
wedgeIdx += nb
return tri_indices
def test_mesh_query_point(test, device):
from pxr import Usd, UsdGeom
mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/spiky.usd")))
mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/Cube/Cube"))
mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get()
mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get()
tri_indices = triangulate(mesh_counts, mesh_indices)
mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device)
mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device)
# create mesh
mesh = wp.Mesh(points=mesh_points, velocities=None, indices=mesh_indices, support_winding_number=True)
p = particle_grid(32, 32, 32, np.array([-1.1, -1.1, -1.1]), 0.05, 0.0)
query_count = len(p)
query_points = wp.array(p, dtype=wp.vec3, device=device)
signs_query = wp.zeros(query_count, dtype=float, device=device)
faces_query = wp.zeros(query_count, dtype=int, device=device)
dist_query = wp.zeros(query_count, dtype=float, device=device)
faces_query_no_sign = wp.zeros(query_count, dtype=int, device=device)
dist_query_no_sign = wp.zeros(query_count, dtype=float, device=device)
signs_query_normal = wp.zeros(query_count, dtype=float, device=device)
faces_query_normal = wp.zeros(query_count, dtype=int, device=device)
dist_query_normal = wp.zeros(query_count, dtype=float, device=device)
signs_query_winding_number = wp.zeros(query_count, dtype=float, device=device)
faces_query_winding_number = wp.zeros(query_count, dtype=int, device=device)
dist_query_winding_number = wp.zeros(query_count, dtype=float, device=device)
signs_brute = wp.zeros(query_count, dtype=float, device=device)
faces_brute = wp.zeros(query_count, dtype=int, device=device)
dist_brute = wp.zeros(query_count, dtype=float, device=device)
wp.launch(
kernel=sample_mesh_query,
dim=query_count,
inputs=[mesh.id, query_points, faces_query, signs_query, dist_query],
device=device,
)
wp.launch(
kernel=sample_mesh_query_no_sign,
dim=query_count,
inputs=[mesh.id, query_points, faces_query_no_sign, dist_query_no_sign],
device=device,
)
wp.launch(
kernel=sample_mesh_query_sign_normal,
dim=query_count,
inputs=[mesh.id, query_points, faces_query_normal, signs_query_normal, dist_query_normal],
device=device,
)
wp.launch(
kernel=sample_mesh_query_sign_winding_number,
dim=query_count,
inputs=[
mesh.id,
query_points,
faces_query_winding_number,
signs_query_winding_number,
dist_query_winding_number,
],
device=device,
)
wp.launch(
kernel=sample_mesh_brute,
dim=query_count,
inputs=[
mesh_points,
mesh_indices,
int(len(mesh_indices) / 3),
query_points,
faces_brute,
signs_brute,
dist_brute,
],
device=device,
)
signs_query = signs_query.numpy()
faces_query = faces_query.numpy()
dist_query = dist_query.numpy()
faces_query_no_sign = faces_query_no_sign.numpy()
dist_query_no_sign = dist_query_no_sign.numpy()
signs_query_normal = signs_query_normal.numpy()
faces_query_normal = faces_query_normal.numpy()
dist_query_normal = dist_query_normal.numpy()
signs_query_winding_number = signs_query_winding_number.numpy()
faces_query_winding_number = faces_query_winding_number.numpy()
dist_query_winding_number = dist_query_winding_number.numpy()
signs_brute = signs_brute.numpy()
faces_brute = faces_brute.numpy()
dist_brute = dist_brute.numpy()
query_points = query_points.numpy()
inside_query = [[0.0, 0.0, 0.0]]
inside_query_normal = [[0.0, 0.0, 0.0]]
inside_query_winding_number = [[0.0, 0.0, 0.0]]
inside_brute = [[0.0, 0.0, 0.0]]
for i in range(query_count):
if signs_query[i] < 0.0:
inside_query.append(query_points[i].tolist())
if signs_query_normal[i] < 0.0:
inside_query_normal.append(query_points[i].tolist())
if signs_query_winding_number[i] < 0.0:
inside_query_winding_number.append(query_points[i].tolist())
if signs_brute[i] > math.pi * 2.0:
inside_brute.append(query_points[i].tolist())
inside_query = np.array(inside_query)
inside_query_normal = np.array(inside_query_normal)
inside_query_winding_number = np.array(inside_query_winding_number)
inside_brute = np.array(inside_brute)
# import warp.render
# stage = warp.render.UsdRenderer("tests/outputs/test_mesh_query_point.usd")
# radius = 0.1
# stage.begin_frame(0.0)
# stage.render_mesh(points=mesh_points.numpy(), indices=mesh_indices.numpy(), name="mesh")
# stage.render_points(points=inside_query, radius=radius, name="query")
# stage.render_points(points=inside_brute, radius=radius, name="brute")
# stage.render_points(points=query_points, radius=radius, name="all")
# stage.end_frame()
# stage.save()
test.assertTrue(len(inside_query) == len(inside_brute))
test.assertTrue(len(inside_query_normal) == len(inside_brute))
test.assertTrue(len(inside_query_winding_number) == len(inside_brute))
tolerance = 1.5e-4
dist_error = np.max(np.abs(dist_query - dist_brute))
sign_error = np.max(np.abs(inside_query - inside_brute))
test.assertTrue(dist_error < tolerance, f"mesh_query_point dist_error is {dist_error} which is >= {tolerance}")
test.assertTrue(sign_error < tolerance, f"mesh_query_point sign_error is {sign_error} which is >= {tolerance}")
dist_error = np.max(np.abs(dist_query_no_sign - dist_brute))
test.assertTrue(
dist_error < tolerance, f"mesh_query_point_no_sign dist_error is {dist_error} which is >= {tolerance}"
)
dist_error = np.max(np.abs(dist_query_normal - dist_brute))
sign_error = np.max(np.abs(inside_query_normal - inside_brute))
test.assertTrue(
dist_error < tolerance, f"mesh_query_point_sign_normal dist_error is {dist_error} which is >= {tolerance}"
)
test.assertTrue(
sign_error < tolerance, f"mesh_query_point_sign_normal sign_error is {sign_error} which is >= {tolerance}"
)
dist_error = np.max(np.abs(dist_query_winding_number - dist_brute))
sign_error = np.max(np.abs(inside_query_winding_number - inside_brute))
test.assertTrue(
dist_error < tolerance,
f"mesh_query_point_sign_winding_number dist_error is {dist_error} which is >= {tolerance}",
)
test.assertTrue(
sign_error < tolerance,
f"mesh_query_point_sign_winding_number sign_error is {sign_error} which is >= {tolerance}",
)
@wp.kernel
def mesh_query_point_loss(
mesh: wp.uint64,
query_points: wp.array(dtype=wp.vec3),
projected_points: wp.array(dtype=wp.vec3),
loss: wp.array(dtype=float),
):
tid = wp.tid()
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = 10012.0
p = query_points[tid]
wp.mesh_query_point(mesh, p, max_dist, sign, face_index, face_u, face_v)
q = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
projected_points[tid] = q
dist = wp.length(wp.sub(p, q))
loss[tid] = dist
def test_adj_mesh_query_point(test, device):
from pxr import Usd, UsdGeom
mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/torus.usda")))
mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/World/Torus"))
mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get()
mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get()
tri_indices = triangulate(mesh_counts, mesh_indices)
mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device)
mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device)
# test tri
# print("Testing Single Triangle")
# mesh_points = wp.array(np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]), dtype=wp.vec3, device=device)
# mesh_indices = wp.array(np.array([0,1,2]), dtype=int, device=device)
# create mesh
mesh = wp.Mesh(points=mesh_points, velocities=None, indices=mesh_indices, support_winding_number=True)
# p = particle_grid(32, 32, 32, np.array([-5.0, -5.0, -5.0]), 0.1, 0.1)*100.0
p = wp.vec3(50.0, 50.0, 50.0)
tape = wp.Tape()
# analytic gradients
with tape:
query_points = wp.array(p, dtype=wp.vec3, device=device, requires_grad=True)
projected_points = wp.zeros(n=1, dtype=wp.vec3, device=device)
loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True)
wp.launch(
kernel=mesh_query_point_loss, dim=1, inputs=[mesh.id, query_points, projected_points, loss], device=device
)
tape.backward(loss=loss)
analytic = tape.gradients[query_points].numpy().flatten()
# numeric gradients
eps = 1.0e-3
loss_values = []
numeric = np.zeros(3)
offset_query_points = [
wp.vec3(p[0] - eps, p[1], p[2]),
wp.vec3(p[0] + eps, p[1], p[2]),
wp.vec3(p[0], p[1] - eps, p[2]),
wp.vec3(p[0], p[1] + eps, p[2]),
wp.vec3(p[0], p[1], p[2] - eps),
wp.vec3(p[0], p[1], p[2] + eps),
]
for i in range(6):
q = offset_query_points[i]
query_points = wp.array(q, dtype=wp.vec3, device=device)
projected_points = wp.zeros(n=1, dtype=wp.vec3, device=device)
loss = wp.zeros(n=1, dtype=float, device=device)
wp.launch(
kernel=mesh_query_point_loss, dim=1, inputs=[mesh.id, query_points, projected_points, loss], device=device
)
loss_values.append(loss.numpy()[0])
for i in range(3):
l_0 = loss_values[i * 2]
l_1 = loss_values[i * 2 + 1]
gradient = (l_1 - l_0) / (2.0 * eps)
numeric[i] = gradient
error = ((analytic - numeric) * (analytic - numeric)).sum(axis=0)
tolerance = 1.0e-3
test.assertTrue(error < tolerance, f"error is {error} which is >= {tolerance}")
def register(parent):
devices = get_test_devices()
class TestMeshQuery(parent):
pass
# USD import failures should not count as a test failure
try:
from pxr import Usd, UsdGeom
have_usd = True
except:
have_usd = False
if have_usd:
add_function_test(TestMeshQuery, "test_mesh_query_point", test_mesh_query_point, devices=devices)
add_function_test(TestMeshQuery, "test_adj_mesh_query_point", test_adj_mesh_query_point, devices=devices)
return TestMeshQuery
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_mesh_query_point.py |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import warp as wp
import numpy as np
wp.config.mode = "release"
wp.config.verbose = True
wp.config.verify_cuda = True
wp.init()
n = 100000
num_runs = 16
def test_for_type(dtype, device):
dtype_str = dtype.__name__
if dtype == int:
values = np.random.randint(-1e6, 1e6, n, dtype=dtype)
else:
values = np.random.uniform(-1, 1, n)
results_ref = np.cumsum(values)
in_values = wp.array(values, dtype=dtype, device=device)
out_values_inc = wp.zeros(len(values), dtype=dtype, device=device)
out_values_exc = wp.zeros(len(values), dtype=dtype, device=device)
wp.utils.array_scan(in_values, out_values_inc, True)
wp.utils.array_scan(in_values, out_values_exc, False)
tolerance = 0 if dtype == int else 1e-3
results_inc = out_values_inc.numpy().squeeze()
results_exc = out_values_exc.numpy().squeeze()
error_inc = np.max(np.abs(results_inc - results_ref)) / abs(results_ref[-1])
error_exc = max(np.max(np.abs(results_exc[1:] - results_ref[:-1])), abs(results_exc[0])) / abs(results_ref[-2])
if error_inc > tolerance:
print(f"FAIL! Max error in inclusive scan for {dtype_str}: {error_inc}")
else:
print(f"PASS! Max error in inclusive scan for {dtype_str}: {error_inc}")
if error_exc > tolerance:
print(f"FAIL! Max error in exclusive scan for {dtype_str}: {error_exc}")
# else:
# print(f"PASS! Max error in exclusive scan for {dtype_str}: {error_exc}")
np.random.seed(1008)
for device in ("cuda", "cpu"):
print(f"\n\nTesting {device}")
for i in range(num_runs):
print(f"Run: {i+1}")
print("---------")
test_for_type(int, device)
test_for_type(float, device)
| warp-main | warp/tests/test_array_scan.py |
from .test_all import run
ret = run()
import sys
sys.exit(ret)
| warp-main | warp/tests/__main__.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.kernel
def scalar_grad(x: wp.array(dtype=float), y: wp.array(dtype=float)):
y[0] = x[0] ** 2.0
def test_scalar_grad(test, device):
x = wp.array([3.0], dtype=float, device=device, requires_grad=True)
y = wp.zeros_like(x)
tape = wp.Tape()
with tape:
wp.launch(scalar_grad, dim=1, inputs=[x, y], device=device)
tape.backward(y)
assert_np_equal(tape.gradients[x].numpy(), np.array(6.0))
@wp.kernel
def for_loop_grad(n: int, x: wp.array(dtype=float), s: wp.array(dtype=float)):
sum = float(0.0)
for i in range(n):
sum = sum + x[i] * 2.0
s[0] = sum
def test_for_loop_grad(test, device):
n = 32
val = np.ones(n, dtype=np.float32)
x = wp.array(val, device=device, requires_grad=True)
sum = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(for_loop_grad, dim=1, inputs=[n, x, sum], device=device)
# ensure forward pass outputs correct
assert_np_equal(sum.numpy(), 2.0 * np.sum(x.numpy()))
tape.backward(loss=sum)
# ensure forward pass outputs persist
assert_np_equal(sum.numpy(), 2.0 * np.sum(x.numpy()))
# ensure gradients correct
assert_np_equal(tape.gradients[x].numpy(), 2.0 * val)
def test_for_loop_graph_grad(test, device):
n = 32
val = np.ones(n, dtype=np.float32)
x = wp.array(val, device=device, requires_grad=True)
sum = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
wp.force_load()
wp.capture_begin()
tape = wp.Tape()
with tape:
wp.launch(for_loop_grad, dim=1, inputs=[n, x, sum], device=device)
tape.backward(loss=sum)
graph = wp.capture_end()
wp.capture_launch(graph)
wp.synchronize()
# ensure forward pass outputs persist
assert_np_equal(sum.numpy(), 2.0 * np.sum(x.numpy()))
# ensure gradients correct
assert_np_equal(x.grad.numpy(), 2.0 * val)
wp.capture_launch(graph)
wp.synchronize()
@wp.kernel
def for_loop_nested_if_grad(n: int, x: wp.array(dtype=float), s: wp.array(dtype=float)):
sum = float(0.0)
for i in range(n):
if i < 16:
if i < 8:
sum = sum + x[i] * 2.0
else:
sum = sum + x[i] * 4.0
else:
if i < 24:
sum = sum + x[i] * 6.0
else:
sum = sum + x[i] * 8.0
s[0] = sum
def test_for_loop_nested_if_grad(test, device):
n = 32
val = np.ones(n, dtype=np.float32)
# fmt: off
expected_val = [
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0,
6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0,
8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0,
]
expected_grad = [
2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0,
4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0,
6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0, 6.0,
8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0,
]
# fmt: on
x = wp.array(val, device=device, requires_grad=True)
sum = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(for_loop_nested_if_grad, dim=1, inputs=[n, x, sum], device=device)
assert_np_equal(sum.numpy(), np.sum(expected_val))
tape.backward(loss=sum)
assert_np_equal(sum.numpy(), np.sum(expected_val))
assert_np_equal(tape.gradients[x].numpy(), np.array(expected_grad))
@wp.kernel
def for_loop_grad_nested(n: int, x: wp.array(dtype=float), s: wp.array(dtype=float)):
sum = float(0.0)
for i in range(n):
for j in range(n):
sum = sum + x[i * n + j] * float(i * n + j) + 1.0
s[0] = sum
def test_for_loop_nested_for_grad(test, device):
x = wp.zeros(9, dtype=float, device=device, requires_grad=True)
s = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(for_loop_grad_nested, dim=1, inputs=[3, x, s], device=device)
tape.backward(s)
assert_np_equal(s.numpy(), np.array([9.0]))
assert_np_equal(tape.gradients[x].numpy(), np.arange(0.0, 9.0, 1.0))
# differentiating thought most while loops is not supported
# since doing things like i = i + 1 breaks adjointing
# @wp.kernel
# def while_loop_grad(n: int,
# x: wp.array(dtype=float),
# c: wp.array(dtype=int),
# s: wp.array(dtype=float)):
# tid = wp.tid()
# while i < n:
# s[0] = s[0] + x[i]*2.0
# i = i + 1
# def test_while_loop_grad(test, device):
# n = 32
# x = wp.array(np.ones(n, dtype=np.float32), device=device, requires_grad=True)
# c = wp.zeros(1, dtype=int, device=device)
# sum = wp.zeros(1, dtype=wp.float32, device=device)
# tape = wp.Tape()
# with tape:
# wp.launch(while_loop_grad, dim=1, inputs=[n, x, c, sum], device=device)
# tape.backward(loss=sum)
# assert_np_equal(sum.numpy(), 2.0*np.sum(x.numpy()))
# assert_np_equal(tape.gradients[x].numpy(), 2.0*np.ones_like(x.numpy()))
@wp.kernel
def preserve_outputs(
n: int, x: wp.array(dtype=float), c: wp.array(dtype=float), s1: wp.array(dtype=float), s2: wp.array(dtype=float)
):
tid = wp.tid()
# plain store
c[tid] = x[tid] * 2.0
# atomic stores
wp.atomic_add(s1, 0, x[tid] * 3.0)
wp.atomic_sub(s2, 0, x[tid] * 2.0)
# tests that outputs from the forward pass are
# preserved by the backward pass, i.e.: stores
# are omitted during the forward reply
def test_preserve_outputs_grad(test, device):
n = 32
val = np.ones(n, dtype=np.float32)
x = wp.array(val, device=device, requires_grad=True)
c = wp.zeros_like(x)
s1 = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
s2 = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(preserve_outputs, dim=n, inputs=[n, x, c, s1, s2], device=device)
# ensure forward pass results are correct
assert_np_equal(x.numpy(), val)
assert_np_equal(c.numpy(), val * 2.0)
assert_np_equal(s1.numpy(), np.array(3.0 * n))
assert_np_equal(s2.numpy(), np.array(-2.0 * n))
# run backward on first loss
tape.backward(loss=s1)
# ensure inputs, copy and sum are unchanged by backwards pass
assert_np_equal(x.numpy(), val)
assert_np_equal(c.numpy(), val * 2.0)
assert_np_equal(s1.numpy(), np.array(3.0 * n))
assert_np_equal(s2.numpy(), np.array(-2.0 * n))
# ensure gradients are correct
assert_np_equal(tape.gradients[x].numpy(), 3.0 * val)
# run backward on second loss
tape.zero()
tape.backward(loss=s2)
assert_np_equal(x.numpy(), val)
assert_np_equal(c.numpy(), val * 2.0)
assert_np_equal(s1.numpy(), np.array(3.0 * n))
assert_np_equal(s2.numpy(), np.array(-2.0 * n))
# ensure gradients are correct
assert_np_equal(tape.gradients[x].numpy(), -2.0 * val)
def gradcheck(func, func_name, inputs, device, eps=1e-4, tol=1e-2):
"""
Checks that the gradient of the Warp kernel is correct by comparing it to the
numerical gradient computed using finite differences.
"""
module = wp.get_module(func.__module__)
kernel = wp.Kernel(func=func, key=func_name, module=module)
def f(xs):
# call the kernel without taping for finite differences
wp_xs = [wp.array(xs[i], ndim=1, dtype=inputs[i].dtype, device=device) for i in range(len(inputs))]
output = wp.zeros(1, dtype=wp.float32, device=device)
wp.launch(kernel, dim=1, inputs=wp_xs, outputs=[output], device=device)
return output.numpy()[0]
# compute numerical gradient
numerical_grad = []
np_xs = []
for i in range(len(inputs)):
np_xs.append(inputs[i].numpy().flatten().copy())
numerical_grad.append(np.zeros_like(np_xs[-1]))
inputs[i].requires_grad = True
for i in range(len(np_xs)):
for j in range(len(np_xs[i])):
np_xs[i][j] += eps
y1 = f(np_xs)
np_xs[i][j] -= 2 * eps
y2 = f(np_xs)
np_xs[i][j] += eps
numerical_grad[i][j] = (y1 - y2) / (2 * eps)
# compute analytical gradient
tape = wp.Tape()
output = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
with tape:
wp.launch(kernel, dim=1, inputs=inputs, outputs=[output], device=device)
tape.backward(loss=output)
# compare gradients
for i in range(len(inputs)):
grad = tape.gradients[inputs[i]]
assert_np_equal(grad.numpy(), numerical_grad[i], tol=tol)
tape.zero()
def test_vector_math_grad(test, device):
np.random.seed(123)
# test unary operations
for dim, vec_type in [(2, wp.vec2), (3, wp.vec3), (4, wp.vec4), (4, wp.quat)]:
def check_length(vs: wp.array(dtype=vec_type), out: wp.array(dtype=float)):
out[0] = wp.length(vs[0])
def check_length_sq(vs: wp.array(dtype=vec_type), out: wp.array(dtype=float)):
out[0] = wp.length_sq(vs[0])
def check_normalize(vs: wp.array(dtype=vec_type), out: wp.array(dtype=float)):
out[0] = wp.length_sq(wp.normalize(vs[0])) # compress to scalar output
# run the tests with 5 different random inputs
for _ in range(5):
x = wp.array(np.random.randn(1, dim).astype(np.float32), dtype=vec_type, device=device)
gradcheck(check_length, f"check_length_{vec_type.__name__}", [x], device)
gradcheck(check_length_sq, f"check_length_sq_{vec_type.__name__}", [x], device)
gradcheck(check_normalize, f"check_normalize_{vec_type.__name__}", [x], device)
def test_matrix_math_grad(test, device):
np.random.seed(123)
# test unary operations
for dim, mat_type in [(2, wp.mat22), (3, wp.mat33), (4, wp.mat44)]:
def check_determinant(vs: wp.array(dtype=mat_type), out: wp.array(dtype=float)):
out[0] = wp.determinant(vs[0])
def check_trace(vs: wp.array(dtype=mat_type), out: wp.array(dtype=float)):
out[0] = wp.trace(vs[0])
# run the tests with 5 different random inputs
for _ in range(5):
x = wp.array(np.random.randn(1, dim, dim).astype(np.float32), ndim=1, dtype=mat_type, device=device)
gradcheck(check_determinant, f"check_length_{mat_type.__name__}", [x], device)
gradcheck(check_trace, f"check_length_sq_{mat_type.__name__}", [x], device)
def test_3d_math_grad(test, device):
np.random.seed(123)
# test binary operations
def check_cross(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
out[0] = wp.length(wp.cross(vs[0], vs[1]))
def check_dot(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
out[0] = wp.dot(vs[0], vs[1])
def check_mat33(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
a = vs[0]
b = vs[1]
c = wp.cross(a, b)
m = wp.mat33(a[0], b[0], c[0], a[1], b[1], c[1], a[2], b[2], c[2])
out[0] = wp.determinant(m)
def check_trace_diagonal(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
a = vs[0]
b = vs[1]
c = wp.cross(a, b)
m = wp.mat33(
1.0 / (a[0] + 10.0),
0.0,
0.0,
0.0,
1.0 / (b[1] + 10.0),
0.0,
0.0,
0.0,
1.0 / (c[2] + 10.0),
)
out[0] = wp.trace(m)
def check_rot_rpy(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
v = vs[0]
q = wp.quat_rpy(v[0], v[1], v[2])
out[0] = wp.length(wp.quat_rotate(q, vs[1]))
def check_rot_axis_angle(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
v = wp.normalize(vs[0])
q = wp.quat_from_axis_angle(v, 0.5)
out[0] = wp.length(wp.quat_rotate(q, vs[1]))
def check_rot_quat_inv(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
v = vs[0]
q = wp.normalize(wp.quat(v[0], v[1], v[2], 1.0))
out[0] = wp.length(wp.quat_rotate_inv(q, vs[1]))
# run the tests with 5 different random inputs
for _ in range(5):
x = wp.array(np.random.randn(2, 3).astype(np.float32), dtype=wp.vec3, device=device, requires_grad=True)
gradcheck(check_cross, "check_cross_3d", [x], device)
gradcheck(check_dot, "check_dot_3d", [x], device)
gradcheck(check_mat33, "check_mat33_3d", [x], device, eps=2e-2)
gradcheck(check_trace_diagonal, "check_trace_diagonal_3d", [x], device)
gradcheck(check_rot_rpy, "check_rot_rpy_3d", [x], device)
gradcheck(check_rot_axis_angle, "check_rot_axis_angle_3d", [x], device)
gradcheck(check_rot_quat_inv, "check_rot_quat_inv_3d", [x], device)
def test_multi_valued_function_grad(test, device):
np.random.seed(123)
@wp.func
def multi_valued(x: float, y: float, z: float):
return wp.sin(x), wp.cos(y) * z, wp.sqrt(z) / wp.abs(x)
# test multi-valued functions
def check_multi_valued(vs: wp.array(dtype=wp.vec3), out: wp.array(dtype=float)):
tid = wp.tid()
v = vs[tid]
a, b, c = multi_valued(v[0], v[1], v[2])
out[tid] = a + b + c
# run the tests with 5 different random inputs
for _ in range(5):
x = wp.array(np.random.randn(2, 3).astype(np.float32), dtype=wp.vec3, device=device, requires_grad=True)
gradcheck(check_multi_valued, "check_multi_valued_3d", [x], device)
def test_mesh_grad(test, device):
pos = wp.array(
[
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
],
dtype=wp.vec3,
device=device,
requires_grad=True,
)
indices = wp.array(
[0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2],
dtype=wp.int32,
device=device,
)
mesh = wp.Mesh(points=pos, indices=indices)
@wp.func
def compute_triangle_area(mesh_id: wp.uint64, tri_id: int):
mesh = wp.mesh_get(mesh_id)
i, j, k = mesh.indices[tri_id * 3 + 0], mesh.indices[tri_id * 3 + 1], mesh.indices[tri_id * 3 + 2]
a = mesh.points[i]
b = mesh.points[j]
c = mesh.points[k]
return wp.length(wp.cross(b - a, c - a)) * 0.5
def compute_area(mesh_id: wp.uint64, out: wp.array(dtype=wp.float32)):
wp.atomic_add(out, 0, compute_triangle_area(mesh_id, wp.tid()))
module = wp.get_module(compute_area.__module__)
kernel = wp.Kernel(func=compute_area, key="compute_area", module=module)
num_tris = int(len(indices) / 3)
# compute analytical gradient
tape = wp.Tape()
output = wp.zeros(1, dtype=wp.float32, device=device, requires_grad=True)
with tape:
wp.launch(kernel, dim=num_tris, inputs=[mesh.id], outputs=[output], device=device)
tape.backward(loss=output)
ad_grad = mesh.points.grad.numpy()
# compute finite differences
eps = 1e-3
pos_np = pos.numpy()
fd_grad = np.zeros_like(ad_grad)
for i in range(len(pos)):
for j in range(3):
pos_np[i, j] += eps
pos = wp.array(pos_np, dtype=wp.vec3, device=device)
mesh = wp.Mesh(points=pos, indices=indices)
output.zero_()
wp.launch(kernel, dim=num_tris, inputs=[mesh.id], outputs=[output], device=device)
f1 = output.numpy()[0]
pos_np[i, j] -= 2 * eps
pos = wp.array(pos_np, dtype=wp.vec3, device=device)
mesh = wp.Mesh(points=pos, indices=indices)
output.zero_()
wp.launch(kernel, dim=num_tris, inputs=[mesh.id], outputs=[output], device=device)
f2 = output.numpy()[0]
pos_np[i, j] += eps
fd_grad[i, j] = (f1 - f2) / (2 * eps)
assert np.allclose(ad_grad, fd_grad, atol=1e-3)
# atomic add function that memorizes which thread incremented the counter
# so that the correct counter value per thread can be used in the replay
# phase of the backward pass
@wp.func
def reversible_increment(
counter: wp.array(dtype=int),
counter_index: int,
value: int,
thread_values: wp.array(dtype=int),
tid: int
):
next_index = wp.atomic_add(counter, counter_index, value)
thread_values[tid] = next_index
return next_index
@wp.func_replay(reversible_increment)
def replay_reversible_increment(
counter: wp.array(dtype=int),
counter_index: int,
value: int,
thread_values: wp.array(dtype=int),
tid: int
):
return thread_values[tid]
def test_custom_replay_grad(test, device):
num_threads = 128
counter = wp.zeros(1, dtype=wp.int32, device=device)
thread_ids = wp.zeros(num_threads, dtype=wp.int32, device=device)
inputs = wp.array(np.arange(num_threads, dtype=np.float32), device=device, requires_grad=True)
outputs = wp.zeros_like(inputs)
@wp.kernel
def run_atomic_add(
input: wp.array(dtype=float),
counter: wp.array(dtype=int),
thread_values: wp.array(dtype=int),
output: wp.array(dtype=float)
):
tid = wp.tid()
idx = reversible_increment(counter, 0, 1, thread_values, tid)
output[idx] = input[idx] ** 2.0
tape = wp.Tape()
with tape:
wp.launch(run_atomic_add, dim=num_threads, inputs=[inputs, counter, thread_ids], outputs=[outputs], device=device)
tape.backward(grads={outputs: wp.array(np.ones(num_threads, dtype=np.float32), device=device)})
assert_np_equal(inputs.grad.numpy(), 2.0 * inputs.numpy(), tol=1e-4)
@wp.func
def overload_fn(x: float, y: float):
return x * 3.0 + y / 3.0, y ** 2.5
@wp.func_grad(overload_fn)
def overload_fn_grad(x: float, y: float, adj_ret0: float, adj_ret1: float):
wp.adjoint[x] += x * adj_ret0 * 42.0 + y * adj_ret1 * 10.0
wp.adjoint[y] += y * adj_ret1 * 3.0
@wp.struct
class MyStruct:
scalar: float
vec: wp.vec3
@wp.func
def overload_fn(x: MyStruct):
return x.vec[0] * x.vec[1] * x.vec[2] * 4.0, wp.length(x.vec), x.scalar ** 0.5
@wp.func_grad(overload_fn)
def overload_fn_grad(x: MyStruct, adj_ret0: float, adj_ret1: float, adj_ret2: float):
wp.adjoint[x.scalar] += x.scalar * adj_ret0 * 10.0
wp.adjoint[x.vec][0] += adj_ret0 * x.vec[1] * x.vec[2] * 20.0
wp.adjoint[x.vec][1] += adj_ret1 * x.vec[0] * x.vec[2] * 30.0
wp.adjoint[x.vec][2] += adj_ret2 * x.vec[0] * x.vec[1] * 40.0
@wp.kernel
def run_overload_float_fn(
xs: wp.array(dtype=float),
ys: wp.array(dtype=float),
output0: wp.array(dtype=float),
output1: wp.array(dtype=float)
):
i = wp.tid()
out0, out1 = overload_fn(xs[i], ys[i])
output0[i] = out0
output1[i] = out1
@wp.kernel
def run_overload_struct_fn(xs: wp.array(dtype=MyStruct), output: wp.array(dtype=float)):
i = wp.tid()
out0, out1, out2 = overload_fn(xs[i])
output[i] = out0 + out1 + out2
def test_custom_overload_grad(test, device):
dim = 3
xs_float = wp.array(np.arange(1.0, dim + 1.0), dtype=wp.float32, requires_grad=True)
ys_float = wp.array(np.arange(10.0, dim + 10.0), dtype=wp.float32, requires_grad=True)
out0_float = wp.zeros(dim)
out1_float = wp.zeros(dim)
tape = wp.Tape()
with tape:
wp.launch(
run_overload_float_fn,
dim=dim,
inputs=[xs_float, ys_float],
outputs=[out0_float, out1_float])
tape.backward(grads={
out0_float: wp.array(np.ones(dim), dtype=wp.float32),
out1_float: wp.array(np.ones(dim), dtype=wp.float32)})
assert_np_equal(xs_float.grad.numpy(), xs_float.numpy() * 42.0 + ys_float.numpy() * 10.0)
assert_np_equal(ys_float.grad.numpy(), ys_float.numpy() * 3.0)
x0 = MyStruct()
x0.vec = wp.vec3(1., 2., 3.)
x0.scalar = 4.
x1 = MyStruct()
x1.vec = wp.vec3(5., 6., 7.)
x1.scalar = -1.0
x2 = MyStruct()
x2.vec = wp.vec3(8., 9., 10.)
x2.scalar = 19.0
xs_struct = wp.array([x0, x1, x2], dtype=MyStruct, requires_grad=True)
out_struct = wp.zeros(dim)
tape = wp.Tape()
with tape:
wp.launch(
run_overload_struct_fn,
dim=dim,
inputs=[xs_struct],
outputs=[out_struct])
tape.backward(grads={out_struct: wp.array(np.ones(dim), dtype=wp.float32)})
xs_struct_np = xs_struct.numpy()
struct_grads = xs_struct.grad.numpy()
# fmt: off
assert_np_equal(
np.array([g[0] for g in struct_grads]),
np.array([g[0] * 10.0 for g in xs_struct_np]))
assert_np_equal(
np.array([g[1][0] for g in struct_grads]),
np.array([g[1][1] * g[1][2] * 20.0 for g in xs_struct_np]))
assert_np_equal(
np.array([g[1][1] for g in struct_grads]),
np.array([g[1][0] * g[1][2] * 30.0 for g in xs_struct_np]))
assert_np_equal(
np.array([g[1][2] for g in struct_grads]),
np.array([g[1][0] * g[1][1] * 40.0 for g in xs_struct_np]))
# fmt: on
def register(parent):
devices = get_test_devices()
class TestGrad(parent):
pass
# add_function_test(TestGrad, "test_while_loop_grad", test_while_loop_grad, devices=devices)
add_function_test(TestGrad, "test_for_loop_nested_for_grad", test_for_loop_nested_for_grad, devices=devices)
add_function_test(TestGrad, "test_scalar_grad", test_scalar_grad, devices=devices)
add_function_test(TestGrad, "test_for_loop_grad", test_for_loop_grad, devices=devices)
add_function_test(TestGrad, "test_for_loop_graph_grad", test_for_loop_graph_grad, devices=wp.get_cuda_devices())
add_function_test(TestGrad, "test_for_loop_nested_if_grad", test_for_loop_nested_if_grad, devices=devices)
add_function_test(TestGrad, "test_preserve_outputs_grad", test_preserve_outputs_grad, devices=devices)
add_function_test(TestGrad, "test_vector_math_grad", test_vector_math_grad, devices=devices)
add_function_test(TestGrad, "test_matrix_math_grad", test_matrix_math_grad, devices=devices)
add_function_test(TestGrad, "test_3d_math_grad", test_3d_math_grad, devices=devices)
add_function_test(TestGrad, "test_multi_valued_function_grad", test_multi_valued_function_grad, devices=devices)
add_function_test(TestGrad, "test_mesh_grad", test_mesh_grad, devices=devices)
add_function_test(TestGrad, "test_custom_replay_grad", test_custom_replay_grad, devices=devices)
add_function_test(TestGrad, "test_custom_overload_grad", test_custom_overload_grad, devices=devices)
return TestGrad
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=False)
| warp-main | warp/tests/test_grad.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=2.0,
t=1.5,
expected=0.5,
expected_adj_a=-0.75,
expected_adj_b=-0.75,
expected_adj_t=1.5,
),
TestData(
a=-1.0,
b=2.0,
t=-0.25,
expected=0.15625,
expected_adj_a=-0.28125,
expected_adj_b=-0.09375,
expected_adj_t=0.375,
),
TestData(
a=0.0,
b=1.0,
t=9.9,
expected=1.0,
expected_adj_a=0.0,
expected_adj_b=0.0,
expected_adj_t=0.0,
),
TestData(
a=0.0,
b=1.0,
t=-9.9,
expected=0.0,
expected_adj_a=0.0,
expected_adj_b=0.0,
expected_adj_t=0.0,
),
),
}
wp.init()
def test_smoothstep(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.smoothstep(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_smoothstep{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 TestSmoothstep(parent):
pass
add_function_test(TestSmoothstep, "test_smoothstep", test_smoothstep, devices=devices)
return TestSmoothstep
if __name__ == "__main__":
_ = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_smoothstep.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.
from typing import NamedTuple
import unittest
import numpy as np
import warp as wp
from warp.tests.test_base import *
wp.init()
class ScalarFloatValues(NamedTuple):
degrees: wp.float32 = None
radians: wp.float32 = None
@wp.kernel
def scalar_float_kernel(
i: int,
x: wp.array(dtype=wp.float32),
out: wp.array(dtype=wp.float32),
):
if i == 0:
out[0] = wp.degrees(x[0])
elif i == 1:
out[0] = wp.radians(x[0])
def test_scalar_math(test, device):
float_values = ScalarFloatValues(
degrees=(0.123,),
radians=(123.0,),
)
float_results_expected = ScalarFloatValues(
degrees=7.047381,
radians=2.146755,
)
adj_float_results_expected = ScalarFloatValues(
degrees=57.29578,
radians=0.017453,
)
for i, values in enumerate(float_values):
x = wp.array(
[values[0]],
dtype=wp.float32,
device=device,
requires_grad=True,
)
out = wp.array(
[0.0],
dtype=wp.float32,
device=device,
requires_grad=True,
)
tape = wp.Tape()
with tape:
wp.launch(
scalar_float_kernel,
dim=1,
inputs=[i, x, out],
device=device,
)
assert_np_equal(
out.numpy(),
np.array([float_results_expected[i]]),
tol=1e-6,
)
tape.backward(out)
assert_np_equal(
tape.gradients[x].numpy(),
np.array([adj_float_results_expected[i]]),
tol=1e-6,
)
def register(parent):
devices = get_test_devices()
class TestMath(parent):
pass
add_function_test(TestMath, "test_scalar_math", test_scalar_math, devices=devices)
return TestMath
if __name__ == "__main__":
_ = register(unittest.TestCase)
unittest.main(verbosity=2)
| warp-main | warp/tests/test_math.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 sys
import unittest
import warp as wp
from warp.tests.test_base import *
# wp.config.mode = "debug"
wp.init()
@wp.kernel
def test_rename():
a = 0
b = 1
a = b
a = 2
wp.expect_eq(a, 2)
wp.expect_eq(b, 1)
@wp.kernel
def test_inplace():
a = 1.0
a += 2.0
wp.expect_eq(a, 3.0)
@wp.kernel
def test_constant(c: float):
a = 0.0
a = c + 1.0
wp.expect_eq(a, 2.0)
@wp.kernel
def test_dynamic_for_rename(n: int):
f0 = int(0.0)
f1 = int(1.0)
for i in range(0, n):
f = f0 + f1
f0 = f1
f1 = f
wp.expect_eq(f1, 89)
@wp.kernel
def test_dynamic_for_inplace(n: int):
a = float(0.0)
for i in range(0, n):
a += 1.0
wp.expect_eq(a, float(n))
@wp.kernel
def test_reassign():
f0 = 1.0
f1 = f0
f1 = f1 + 2.0
wp.expect_eq(f1, 3.0)
wp.expect_eq(f0, 1.0)
@wp.kernel
def test_dynamic_reassign(n: int):
f0 = wp.vec3()
f1 = f0
for i in range(0, n):
f1 = f1 - wp.vec3(2.0, 0.0, 0.0)
wp.expect_eq(f1, wp.vec3(-4.0, 0.0, 0.0))
wp.expect_eq(f0, wp.vec3())
@wp.kernel
def test_range_static_sum(result: wp.array(dtype=int)):
a = int(0)
for i in range(10):
a = a + 1
b = int(0)
for i in range(0, 10):
b = b + 1
c = int(0)
for i in range(0, 20, 2):
c = c + 1
result[0] = a
result[1] = b
result[2] = c
@wp.kernel
def test_range_dynamic_sum(start: int, end: int, step: int, result: wp.array(dtype=int)):
a = int(0)
for i in range(end):
a = a + 1
b = int(0)
for i in range(start, end):
b = b + 1
c = int(0)
for i in range(start, end * step, step):
c = c + 1
d = int(0)
for i in range(end * step, start, -step):
d = d + 1
result[0] = a
result[1] = b
result[2] = c
result[3] = d
@wp.kernel
def test_range_dynamic(start: int, end: int, step: int, result: wp.array(dtype=int)):
output = int(0)
for i in range(start, end, step):
result[output] = i
output += 1
@wp.kernel
def test_range_dynamic_nested(n: int):
sum1 = float(0.0)
sum2 = float(0.0)
sum3 = float(0.0)
for i in range(n):
sum1 = sum1 + 1.0
sum3 = sum3 + 1.0
for j in range(n):
sum2 = sum2 + 1.0
sum3 = sum3 + 1.0
sum3 = sum3 + 1.0
wp.expect_eq(sum1, float(n))
wp.expect_eq(sum2, float(n * n))
wp.expect_eq(sum3, float(n * n + 2 * n))
@wp.kernel
def test_while(n: int):
i = int(0)
while i < n:
i = i + 1
wp.expect_eq(i, n)
@wp.kernel
def test_pass(n: int):
i = int(0)
while i < n:
if False:
pass
else:
i = i + 1
wp.expect_eq(i, n)
@wp.kernel
def test_break(n: int):
a = int(0)
for i in range(0, n):
if a == 5:
break
a += 1
wp.expect_eq(a, 5)
@wp.kernel
def test_break_early(n: int):
a = int(0)
for i in range(0, n):
if i > 5:
a = 1
break
wp.expect_eq(a, 1)
@wp.kernel
def test_break_unroll():
a = int(0)
for i in range(0, 10):
if i > 5:
a = i
break
wp.expect_eq(a, 6)
@wp.kernel
def test_break_multiple(n: int):
a = int(0)
for i in range(0, n):
if i == 6:
a = 1
break
if i == 5:
a = 2
break
if i == 7:
a = 3
break
wp.expect_eq(a, 2)
@wp.kernel
def test_continue(n: int):
a = int(0)
for i in range(0, n):
if i == 5:
continue
a += 1
wp.expect_eq(a, n - 1)
@wp.kernel
def test_continue_unroll():
a = int(0)
for i in range(0, 10):
if i == 5:
continue
a += 1
wp.expect_eq(a, 9)
lower = wp.constant(-3)
upper = wp.constant(3)
step = wp.constant(2)
# test unrolling of loops with constant size params
# we can't easily test if unrolling has occurred
# so just verify correctness at this stage
@wp.kernel
def test_range_constant():
s = 0
for i in range(upper):
s += i
# sum [0, 3)
wp.expect_eq(s, 3)
s = 0
for i in range(lower, upper):
s += i
# sum [-3, 3)
wp.expect_eq(s, -3)
s = 0
for i in range(lower, upper, step):
s += i
# sum [-3, 3)
wp.expect_eq(s, -3)
N = wp.constant(3)
# test a dynamic loop nested between loops expected to be unrolled.
@wp.kernel
def test_range_constant_dynamic_nested(m: int):
s = int(0)
for i in range(N):
for k in range(m):
for j in range(N):
s += 1
wp.expect_eq(s, N * m * N)
def test_unresolved_func(test, device):
# kernel with unresolved function must be in a separate module, otherwise the current module would fail to load
from warp.tests.test_unresolved_func import unresolved_func_kernel
# ensure that an appropriate exception is raised when the bad module gets loaded
with test.assertRaisesRegex(RuntimeError, "Could not find function wp.missing_func"):
wp.launch(unresolved_func_kernel, dim=1, inputs=[], device=device)
# remove all references to the bad module so that subsequent calls to wp.force_load()
# won't try to load it unless we explicitly re-import it again
del wp.context.user_modules["warp.tests.test_unresolved_func"]
del sys.modules["warp.tests.test_unresolved_func"]
def test_unresolved_symbol(test, device):
# kernel with unresolved symbol must be in a separate module, otherwise the current module would fail to load
from warp.tests.test_unresolved_symbol import unresolved_symbol_kernel
# ensure that an appropriate exception is raised when the bad module gets loaded
with test.assertRaisesRegex(KeyError, "Referencing undefined symbol: missing_symbol"):
wp.launch(unresolved_symbol_kernel, dim=1, inputs=[], device=device)
# remove all references to the bad module so that subsequent calls to wp.force_load()
# won't try to load it unless we explicitly re-import it again
del wp.context.user_modules["warp.tests.test_unresolved_symbol"]
del sys.modules["warp.tests.test_unresolved_symbol"]
def register(parent):
class TestCodeGen(parent):
pass
devices = get_test_devices()
add_kernel_test(TestCodeGen, name="test_inplace", kernel=test_inplace, dim=1, devices=devices)
add_kernel_test(TestCodeGen, name="test_rename", kernel=test_rename, dim=1, devices=devices)
add_kernel_test(TestCodeGen, name="test_constant", kernel=test_constant, inputs=[1.0], dim=1, devices=devices)
add_kernel_test(
TestCodeGen, name="test_dynamic_for_rename", kernel=test_dynamic_for_rename, inputs=[10], dim=1, devices=devices
)
add_kernel_test(
TestCodeGen,
name="test_dynamic_for_inplace",
kernel=test_dynamic_for_inplace,
inputs=[10],
dim=1,
devices=devices,
)
add_kernel_test(TestCodeGen, name="test_reassign", kernel=test_reassign, dim=1, devices=devices)
add_kernel_test(
TestCodeGen, name="test_dynamic_reassign", kernel=test_dynamic_reassign, inputs=[2], dim=1, devices=devices
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_forward",
kernel=test_range_dynamic,
dim=1,
inputs=[0, 4, 1],
expect=[0, 1, 2, 3],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_reverse",
kernel=test_range_dynamic,
dim=1,
inputs=[4, 0, -1],
expect=[4, 3, 2, 1],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_foward_step",
kernel=test_range_dynamic,
dim=1,
inputs=[0, 8, 2],
expect=[0, 2, 4, 6],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_reverse_step",
kernel=test_range_dynamic,
dim=1,
inputs=[8, 0, -2],
expect=[8, 6, 4, 2],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_static_sum",
kernel=test_range_static_sum,
dim=1,
expect=[10, 10, 10],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_sum",
kernel=test_range_dynamic_sum,
dim=1,
inputs=[0, 10, 2],
expect=[10, 10, 10, 10],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_sum_zero",
kernel=test_range_dynamic_sum,
dim=1,
inputs=[0, 0, 1],
expect=[0, 0, 0, 0],
devices=devices,
)
add_kernel_test(TestCodeGen, name="test_range_constant", kernel=test_range_constant, dim=1, devices=devices)
add_kernel_test(
TestCodeGen,
name="test_range_constant_dynamic_nested",
kernel=test_range_constant_dynamic_nested,
dim=1,
inputs=[10],
devices=devices,
)
add_kernel_test(
TestCodeGen,
name="test_range_dynamic_nested",
kernel=test_range_dynamic_nested,
dim=1,
inputs=[4],
devices=devices,
)
add_kernel_test(TestCodeGen, name="test_while_zero", kernel=test_while, dim=1, inputs=[0], devices=devices)
add_kernel_test(TestCodeGen, name="test_while_positive", kernel=test_while, dim=1, inputs=[16], devices=devices)
add_kernel_test(TestCodeGen, name="test_pass", kernel=test_pass, dim=1, inputs=[16], devices=devices)
add_kernel_test(TestCodeGen, name="test_break", kernel=test_break, dim=1, inputs=[10], devices=devices)
add_kernel_test(TestCodeGen, name="test_break_early", kernel=test_break_early, dim=1, inputs=[10], devices=devices)
add_kernel_test(TestCodeGen, name="test_break_unroll", kernel=test_break_unroll, dim=1, devices=devices)
add_kernel_test(
TestCodeGen, name="test_break_multiple", kernel=test_break_multiple, dim=1, inputs=[10], devices=devices
)
add_kernel_test(TestCodeGen, name="test_continue", kernel=test_continue, dim=1, inputs=[10], devices=devices)
add_kernel_test(TestCodeGen, name="test_continue_unroll", kernel=test_continue_unroll, dim=1, devices=devices)
add_function_test(TestCodeGen, func=test_unresolved_func, name="test_unresolved_func", devices=devices)
add_function_test(TestCodeGen, func=test_unresolved_symbol, name="test_unresolved_symbol", devices=devices)
return TestCodeGen
if __name__ == "__main__":
c = register(unittest.TestCase)
unittest.main(verbosity=2, failfast=True)
| warp-main | warp/tests/test_codegen.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
import numpy as np
import math
def _usd_add_xform(prim):
from pxr import UsdGeom
prim = UsdGeom.Xform(prim)
prim.ClearXformOpOrder()
t = prim.AddTranslateOp()
r = prim.AddOrientOp()
s = prim.AddScaleOp()
def _usd_set_xform(xform, pos: tuple, rot: tuple, scale: tuple, time):
from pxr import UsdGeom, Gf
xform = UsdGeom.Xform(xform)
xform_ops = xform.GetOrderedXformOps()
xform_ops[0].Set(Gf.Vec3d(float(pos[0]), float(pos[1]), float(pos[2])), time)
xform_ops[1].Set(Gf.Quatf(float(rot[3]), float(rot[0]), float(rot[1]), float(rot[2])), time)
xform_ops[2].Set(Gf.Vec3d(float(scale[0]), float(scale[1]), float(scale[2])), time)
# transforms a cylinder such that it connects the two points pos0, pos1
def _compute_segment_xform(pos0, pos1):
from pxr import Gf
mid = (pos0 + pos1) * 0.5
height = (pos1 - pos0).GetLength()
dir = (pos1 - pos0) / height
rot = Gf.Rotation()
rot.SetRotateInto((0.0, 0.0, 1.0), Gf.Vec3d(dir))
scale = Gf.Vec3f(1.0, 1.0, height)
return (mid, Gf.Quath(rot.GetQuat()), scale)
class UsdRenderer:
"""A USD renderer"""
def __init__(self, stage, up_axis="Y", fps=60, scaling=1.0):
"""Construct a UsdRenderer object
Args:
model: A simulation model
stage (str/Usd.Stage): A USD stage (either in memory or on disk)
up_axis (str): The upfacing axis of the stage
fps: The number of frames per second to use in the USD file
scaling: Scaling factor to use for the entities in the scene
"""
from pxr import Usd, UsdGeom, UsdLux, Sdf, Gf
if isinstance(stage, str):
self.stage = stage = Usd.Stage.CreateNew(stage)
elif isinstance(stage, Usd.Stage):
self.stage = stage
else:
print("Failed to create stage in renderer. Please construct with stage path or stage object.")
self.up_axis = up_axis.upper()
self.fps = float(fps)
self.time = 0.0
self.draw_points = True
self.draw_springs = False
self.draw_triangles = False
self.root = UsdGeom.Xform.Define(stage, "/root")
# mapping from shape ID to UsdGeom class
self._shape_constructors = {}
# optional scaling applied to shape instances (e.g. cubes)
self._shape_custom_scale = {}
# apply scaling
self.root.ClearXformOpOrder()
s = self.root.AddScaleOp()
s.Set(Gf.Vec3d(float(scaling), float(scaling), float(scaling)), 0.0)
self.stage.SetDefaultPrim(self.root.GetPrim())
self.stage.SetStartTimeCode(0.0)
self.stage.SetEndTimeCode(0.0)
self.stage.SetTimeCodesPerSecond(self.fps)
if up_axis == "X":
UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.x)
elif up_axis == "Y":
UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.y)
elif up_axis == "Z":
UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.z)
# add default lights
light_0 = UsdLux.DistantLight.Define(stage, "/light_0")
light_0.GetPrim().CreateAttribute("intensity", Sdf.ValueTypeNames.Float, custom=False).Set(2500.0)
light_0.GetPrim().CreateAttribute("color", Sdf.ValueTypeNames.Color3f, custom=False).Set(
Gf.Vec3f(0.98, 0.85, 0.7)
)
UsdGeom.Xform(light_0.GetPrim()).AddRotateYOp().Set(value=(70.0))
UsdGeom.Xform(light_0.GetPrim()).AddRotateXOp().Set(value=(-45.0))
light_1 = UsdLux.DistantLight.Define(stage, "/light_1")
light_1.GetPrim().CreateAttribute("intensity", Sdf.ValueTypeNames.Float, custom=False).Set(2500.0)
light_1.GetPrim().CreateAttribute("color", Sdf.ValueTypeNames.Color3f, custom=False).Set(
Gf.Vec3f(0.62, 0.82, 0.98)
)
UsdGeom.Xform(light_1.GetPrim()).AddRotateYOp().Set(value=(-70.0))
UsdGeom.Xform(light_1.GetPrim()).AddRotateXOp().Set(value=(-45.0))
def begin_frame(self, time):
self.stage.SetEndTimeCode(time * self.fps)
self.time = time * self.fps
def end_frame(self):
pass
def register_body(self, body_name):
from pxr import UsdGeom
xform = UsdGeom.Xform.Define(self.stage, self.root.GetPath().AppendChild(body_name))
_usd_add_xform(xform)
def _resolve_path(self, name, parent_body=None, is_template=False):
# resolve the path to the prim with the given name and optional parent body
if is_template:
return self.root.GetPath().AppendChild("_template_shapes").AppendChild(name)
if parent_body is None:
return self.root.GetPath().AppendChild(name)
else:
return self.root.GetPath().AppendChild(parent_body).AppendChild(name)
def add_shape_instance(
self,
name: str,
shape,
body,
pos: tuple,
rot: tuple,
scale: tuple = (1.0, 1.0, 1.0),
color: tuple = (1.0, 1.0, 1.0),
):
sdf_path = self._resolve_path(name, body)
instance = self._shape_constructors[shape.name].Define(self.stage, sdf_path)
instance.GetPrim().GetReferences().AddInternalReference(shape)
_usd_add_xform(instance)
if shape.name in self._shape_custom_scale:
cs = self._shape_custom_scale[shape.name]
scale = (scale[0] * cs[0], scale[1] * cs[1], scale[2] * cs[2])
_usd_set_xform(instance, pos, rot, scale, self.time)
def render_plane(
self,
name: str,
pos: tuple,
rot: tuple,
width: float,
length: float,
color: tuple = None,
parent_body: str = None,
is_template: bool = False,
):
"""
Render a plane with the given dimensions.
Args:
name: Name of the plane
pos: Position of the plane
rot: Rotation of the plane
width: Width of the plane
length: Length of the plane
color: Color of the plane
parent_body: Name of the parent body
is_template: Whether the plane is a template
"""
from pxr import UsdGeom, Sdf
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
plane_path = prim_path.AppendChild("plane")
else:
plane_path = self._resolve_path(name, parent_body)
prim_path = plane_path
plane = UsdGeom.Mesh.Get(self.stage, plane_path)
if not plane:
plane = UsdGeom.Mesh.Define(self.stage, plane_path)
plane.CreateDoubleSidedAttr().Set(True)
width = width if width > 0.0 else 100.0
length = length if length > 0.0 else 100.0
points = ((-width, 0.0, -length), (width, 0.0, -length), (width, 0.0, length), (-width, 0.0, length))
normals = ((0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0))
counts = (4,)
indices = [0, 1, 2, 3]
plane.GetPointsAttr().Set(points)
plane.GetNormalsAttr().Set(normals)
plane.GetFaceVertexCountsAttr().Set(counts)
plane.GetFaceVertexIndicesAttr().Set(indices)
_usd_add_xform(plane)
self._shape_constructors[name] = UsdGeom.Mesh
if not is_template:
_usd_set_xform(plane, pos, rot, (1.0, 1.0, 1.0), 0.0)
return prim_path
def render_ground(self, size: float = 100.0):
from pxr import UsdGeom
mesh = UsdGeom.Mesh.Define(self.stage, self.root.GetPath().AppendChild("ground"))
mesh.CreateDoubleSidedAttr().Set(True)
if self.up_axis == "X":
points = ((0.0, -size, -size), (0.0, size, -size), (0.0, size, size), (0.0, -size, size))
normals = ((1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0))
elif self.up_axis == "Y":
points = ((-size, 0.0, -size), (size, 0.0, -size), (size, 0.0, size), (-size, 0.0, size))
normals = ((0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0))
elif self.up_axis == "Z":
points = ((-size, -size, 0.0), (size, -size, 0.0), (size, size, 0.0), (-size, size, 0.0))
normals = ((0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0))
counts = (4,)
indices = [0, 1, 2, 3]
mesh.GetPointsAttr().Set(points)
mesh.GetNormalsAttr().Set(normals)
mesh.GetFaceVertexCountsAttr().Set(counts)
mesh.GetFaceVertexIndicesAttr().Set(indices)
def render_sphere(
self, name: str, pos: tuple, rot: tuple, radius: float, parent_body: str = None, is_template: bool = False
):
"""Debug helper to add a sphere for visualization
Args:
pos: The position of the sphere
radius: The radius of the sphere
name: A name for the USD prim on the stage
"""
from pxr import UsdGeom, Sdf
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
sphere_path = prim_path.AppendChild("sphere")
else:
sphere_path = self._resolve_path(name, parent_body)
prim_path = sphere_path
sphere = UsdGeom.Sphere.Get(self.stage, sphere_path)
if not sphere:
sphere = UsdGeom.Sphere.Define(self.stage, sphere_path)
_usd_add_xform(sphere)
sphere.GetRadiusAttr().Set(radius, self.time)
self._shape_constructors[name] = UsdGeom.Sphere
if not is_template:
_usd_set_xform(sphere, pos, rot, (1.0, 1.0, 1.0), 0.0)
return prim_path
def render_capsule(
self,
name: str,
pos: tuple,
rot: tuple,
radius: float,
half_height: float,
parent_body: str = None,
is_template: bool = False,
):
"""
Debug helper to add a capsule for visualization
Args:
pos: The position of the capsule
radius: The radius of the capsule
half_height: The half height of the capsule
name: A name for the USD prim on the stage
"""
from pxr import UsdGeom, Sdf
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
capsule_path = prim_path.AppendChild("capsule")
else:
capsule_path = self._resolve_path(name, parent_body)
prim_path = capsule_path
capsule = UsdGeom.Capsule.Get(self.stage, capsule_path)
if not capsule:
capsule = UsdGeom.Capsule.Define(self.stage, capsule_path)
_usd_add_xform(capsule)
capsule.GetRadiusAttr().Set(float(radius))
capsule.GetHeightAttr().Set(float(half_height * 2.0))
capsule.GetAxisAttr().Set("Y")
self._shape_constructors[name] = UsdGeom.Capsule
if not is_template:
_usd_set_xform(capsule, pos, rot, (1.0, 1.0, 1.0), 0.0)
return prim_path
def render_cylinder(
self,
name: str,
pos: tuple,
rot: tuple,
radius: float,
half_height: float,
parent_body: str = None,
is_template: bool = False,
):
"""
Debug helper to add a cylinder for visualization
Args:
pos: The position of the cylinder
radius: The radius of the cylinder
half_height: The half height of the cylinder
name: A name for the USD prim on the stage
"""
from pxr import UsdGeom, Sdf
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
cylinder_path = prim_path.AppendChild("cylinder")
else:
cylinder_path = self._resolve_path(name, parent_body)
prim_path = cylinder_path
cylinder = UsdGeom.Cylinder.Get(self.stage, cylinder_path)
if not cylinder:
cylinder = UsdGeom.Cylinder.Define(self.stage, cylinder_path)
_usd_add_xform(cylinder)
cylinder.GetRadiusAttr().Set(float(radius))
cylinder.GetHeightAttr().Set(float(half_height * 2.0))
cylinder.GetAxisAttr().Set("Y")
self._shape_constructors[name] = UsdGeom.Cylinder
if not is_template:
_usd_set_xform(cylinder, pos, rot, (1.0, 1.0, 1.0), 0.0)
return prim_path
def render_cone(
self,
name: str,
pos: tuple,
rot: tuple,
radius: float,
half_height: float,
parent_body: str = None,
is_template: bool = False,
):
"""
Debug helper to add a cone for visualization
Args:
pos: The position of the cone
radius: The radius of the cone
half_height: The half height of the cone
name: A name for the USD prim on the stage
"""
from pxr import UsdGeom, Sdf
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
cone_path = prim_path.AppendChild("cone")
else:
cone_path = self._resolve_path(name, parent_body)
prim_path = cone_path
cone = UsdGeom.Cone.Get(self.stage, cone_path)
if not cone:
cone = UsdGeom.Cone.Define(self.stage, cone_path)
_usd_add_xform(cone)
cone.GetRadiusAttr().Set(float(radius))
cone.GetHeightAttr().Set(float(half_height * 2.0))
cone.GetAxisAttr().Set("Y")
self._shape_constructors[name] = UsdGeom.Cone
if not is_template:
_usd_set_xform(cone, pos, rot, (1.0, 1.0, 1.0), 0.0)
return prim_path
def render_box(
self, name: str, pos: tuple, rot: tuple, extents: tuple, parent_body: str = None, is_template: bool = False
):
"""Debug helper to add a box for visualization
Args:
pos: The position of the sphere
extents: The radius of the sphere
name: A name for the USD prim on the stage
"""
from pxr import UsdGeom, Sdf, Gf, Vt
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
cube_path = prim_path.AppendChild("cube")
else:
cube_path = self._resolve_path(name, parent_body)
prim_path = cube_path
cube = UsdGeom.Cube.Get(self.stage, cube_path)
if not cube:
cube = UsdGeom.Cube.Define(self.stage, cube_path)
_usd_add_xform(cube)
self._shape_constructors[name] = UsdGeom.Cube
self._shape_custom_scale[name] = extents
if not is_template:
_usd_set_xform(cube, pos, rot, extents, 0.0)
return prim_path
def render_ref(self, name: str, path: str, pos: tuple, rot: tuple, scale: tuple):
from pxr import UsdGeom
ref_path = "/root/" + name
ref = UsdGeom.Xform.Get(self.stage, ref_path)
if not ref:
ref = UsdGeom.Xform.Define(self.stage, ref_path)
ref.GetPrim().GetReferences().AddReference(path)
_usd_add_xform(ref)
# update transform
_usd_set_xform(ref, pos, rot, scale, self.time)
def render_mesh(
self,
name: str,
points,
indices,
colors=None,
pos=(0.0, 0.0, 0.0),
rot=(0.0, 0.0, 0.0, 1.0),
scale=(1.0, 1.0, 1.0),
update_topology=False,
parent_body: str = None,
is_template: bool = False,
):
from pxr import UsdGeom, Sdf
if is_template:
prim_path = self._resolve_path(name, parent_body, is_template)
blueprint = UsdGeom.Scope.Define(self.stage, prim_path)
blueprint_prim = blueprint.GetPrim()
blueprint_prim.SetInstanceable(True)
blueprint_prim.SetSpecifier(Sdf.SpecifierClass)
mesh_path = prim_path.AppendChild("mesh")
else:
mesh_path = self._resolve_path(name, parent_body)
prim_path = mesh_path
mesh = UsdGeom.Mesh.Get(self.stage, mesh_path)
if not mesh:
mesh = UsdGeom.Mesh.Define(self.stage, mesh_path)
UsdGeom.Primvar(mesh.GetDisplayColorAttr()).SetInterpolation("vertex")
_usd_add_xform(mesh)
# force topology update on first frame
update_topology = True
mesh.GetPointsAttr().Set(points, self.time)
if update_topology:
idxs = np.array(indices).reshape(-1, 3)
mesh.GetFaceVertexIndicesAttr().Set(idxs, self.time)
mesh.GetFaceVertexCountsAttr().Set([3] * len(idxs), self.time)
if colors:
mesh.GetDisplayColorAttr().Set(colors, self.time)
self._shape_constructors[name] = UsdGeom.Mesh
self._shape_custom_scale[name] = scale
if not is_template:
_usd_set_xform(mesh, pos, rot, scale, self.time)
return prim_path
def render_line_list(self, name, vertices, indices, color, radius):
"""Debug helper to add a line list as a set of capsules
Args:
vertices: The vertices of the line-strip
color: The color of the line
time: The time to update at
"""
from pxr import UsdGeom, Gf
num_lines = int(len(indices) / 2)
if num_lines < 1:
return
# look up rope point instancer
instancer_path = self.root.GetPath().AppendChild(name)
instancer = UsdGeom.PointInstancer.Get(self.stage, instancer_path)
if not instancer:
instancer = UsdGeom.PointInstancer.Define(self.stage, instancer_path)
instancer_capsule = UsdGeom.Capsule.Define(self.stage, instancer.GetPath().AppendChild("capsule"))
instancer_capsule.GetRadiusAttr().Set(radius)
instancer.CreatePrototypesRel().SetTargets([instancer_capsule.GetPath()])
# instancer.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Float3Array, "constant", 1)
line_positions = []
line_rotations = []
line_scales = []
for i in range(num_lines):
pos0 = vertices[indices[i * 2 + 0]]
pos1 = vertices[indices[i * 2 + 1]]
(pos, rot, scale) = _compute_segment_xform(
Gf.Vec3f(float(pos0[0]), float(pos0[1]), float(pos0[2])),
Gf.Vec3f(float(pos1[0]), float(pos1[1]), float(pos1[2])),
)
line_positions.append(pos)
line_rotations.append(rot)
line_scales.append(scale)
# line_colors.append(Gf.Vec3f((float(i)/num_lines, 0.5, 0.5)))
instancer.GetPositionsAttr().Set(line_positions, self.time)
instancer.GetOrientationsAttr().Set(line_rotations, self.time)
instancer.GetScalesAttr().Set(line_scales, self.time)
instancer.GetProtoIndicesAttr().Set([0] * num_lines, self.time)
# instancer.GetPrimvar("displayColor").Set(line_colors, time)
def render_line_strip(self, name: str, vertices, color: tuple, radius: float = 0.01):
from pxr import UsdGeom, Gf
num_lines = int(len(vertices) - 1)
if num_lines < 1:
return
# look up rope point instancer
instancer_path = self.root.GetPath().AppendChild(name)
instancer = UsdGeom.PointInstancer.Get(self.stage, instancer_path)
if not instancer:
instancer = UsdGeom.PointInstancer.Define(self.stage, instancer_path)
instancer_capsule = UsdGeom.Capsule.Define(self.stage, instancer.GetPath().AppendChild("capsule"))
instancer_capsule.GetRadiusAttr().Set(radius)
instancer.CreatePrototypesRel().SetTargets([instancer_capsule.GetPath()])
line_positions = []
line_rotations = []
line_scales = []
for i in range(num_lines):
pos0 = vertices[i]
pos1 = vertices[i + 1]
(pos, rot, scale) = _compute_segment_xform(
Gf.Vec3f(float(pos0[0]), float(pos0[1]), float(pos0[2])),
Gf.Vec3f(float(pos1[0]), float(pos1[1]), float(pos1[2])),
)
line_positions.append(pos)
line_rotations.append(rot)
line_scales.append(scale)
instancer.GetPositionsAttr().Set(line_positions, self.time)
instancer.GetOrientationsAttr().Set(line_rotations, self.time)
instancer.GetScalesAttr().Set(line_scales, self.time)
instancer.GetProtoIndicesAttr().Set([0] * num_lines, self.time)
instancer_capsule = UsdGeom.Capsule.Get(self.stage, instancer.GetPath().AppendChild("capsule"))
instancer_capsule.GetDisplayColorAttr().Set([Gf.Vec3f(color)], self.time)
def render_points(self, name: str, points, radius, colors=None):
from pxr import UsdGeom, Gf
instancer_path = self.root.GetPath().AppendChild(name)
instancer = UsdGeom.PointInstancer.Get(self.stage, instancer_path)
radius_is_scalar = np.isscalar(radius)
if not instancer:
if colors is None:
instancer = UsdGeom.PointInstancer.Define(self.stage, instancer_path)
instancer_sphere = UsdGeom.Sphere.Define(self.stage, instancer.GetPath().AppendChild("sphere"))
if radius_is_scalar:
instancer_sphere.GetRadiusAttr().Set(radius)
else:
instancer_sphere.GetRadiusAttr().Set(1.0)
instancer.GetScalesAttr().Set(np.tile(radius, (3, 1)).T)
instancer.CreatePrototypesRel().SetTargets([instancer_sphere.GetPath()])
instancer.CreateProtoIndicesAttr().Set([0] * len(points))
# set identity rotations
quats = [Gf.Quath(1.0, 0.0, 0.0, 0.0)] * len(points)
instancer.GetOrientationsAttr().Set(quats, self.time)
else:
from pxr import Sdf
instancer = UsdGeom.Points.Define(self.stage, instancer_path)
instancer.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Float3Array, "vertex", 1)
if radius_is_scalar:
instancer.GetWidthsAttr().Set([radius] * len(points))
else:
instancer.GetWidthsAttr().Set(radius)
if colors is None:
instancer.GetPositionsAttr().Set(points, self.time)
else:
instancer.GetPointsAttr().Set(points, self.time)
instancer.GetDisplayColorAttr().Set(colors, self.time)
def update_body_transforms(self, body_q):
from pxr import UsdGeom, Sdf
if isinstance(body_q, wp.array):
body_q = body_q.numpy()
with Sdf.ChangeBlock():
for b in range(self.model.body_count):
node_name = self.body_names[b]
node = UsdGeom.Xform(self.stage.GetPrimAtPath(self.root.GetPath().AppendChild(node_name)))
# unpack rigid transform
X_sb = wp.transform_expand(body_q[b])
_usd_set_xform(node, X_sb.p, X_sb.q, (1.0, 1.0, 1.0), self.time)
def save(self):
try:
self.stage.Save()
return True
except:
print("Failed to save USD stage")
return False
| warp-main | warp/render/render_usd.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 .utils import bourke_color_map
from .render_usd import UsdRenderer
from .render_opengl import OpenGLRenderer
| warp-main | warp/render/__init__.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 typing import Union
import numpy as np
import warp as wp
def bourke_color_map(low, high, v):
c = [1.0, 1.0, 1.0]
if v < low:
v = low
if v > high:
v = high
dv = high - low
if v < (low + 0.25 * dv):
c[0] = 0.0
c[1] = 4.0 * (v - low) / dv
elif v < (low + 0.5 * dv):
c[0] = 0.0
c[2] = 1.0 + 4.0 * (low + 0.25 * dv - v) / dv
elif v < (low + 0.75 * dv):
c[0] = 4.0 * (v - low - 0.5 * dv) / dv
c[2] = 0.0
else:
c[1] = 1.0 + 4.0 * (low + 0.75 * dv - v) / dv
c[2] = 0.0
return c
def tab10_color_map(i):
# matplotlib "tab10" colors
colors = [
[31, 119, 180],
[255, 127, 14],
[44, 160, 44],
[214, 39, 40],
[148, 103, 189],
[140, 86, 75],
[227, 119, 194],
[127, 127, 127],
[188, 189, 34],
[23, 190, 207],
]
num_colors = len(colors)
return [c / 255.0 for c in colors[i % num_colors]]
# triangulate mesh around given surface with given thickness
@wp.kernel
def solidify_mesh_kernel(
indices: wp.array(dtype=int, ndim=2),
vertices: wp.array(dtype=wp.vec3, ndim=1),
thickness: wp.array(dtype=float, ndim=1),
# outputs
out_vertices: wp.array(dtype=wp.vec3, ndim=1),
out_indices: wp.array(dtype=int, ndim=2),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
vi = vertices[i]
vj = vertices[j]
vk = vertices[k]
normal = wp.normalize(wp.cross(vj - vi, vk - vi))
ti = normal * thickness[i]
tj = normal * thickness[j]
tk = normal * thickness[k]
# wedge vertices
vi0 = vi + ti
vi1 = vi - ti
vj0 = vj + tj
vj1 = vj - tj
vk0 = vk + tk
vk1 = vk - tk
i0 = i * 2
i1 = i * 2 + 1
j0 = j * 2
j1 = j * 2 + 1
k0 = k * 2
k1 = k * 2 + 1
out_vertices[i0] = vi0
out_vertices[i1] = vi1
out_vertices[j0] = vj0
out_vertices[j1] = vj1
out_vertices[k0] = vk0
out_vertices[k1] = vk1
oid = tid * 8
out_indices[oid + 0, 0] = i0
out_indices[oid + 0, 1] = j0
out_indices[oid + 0, 2] = k0
out_indices[oid + 1, 0] = j0
out_indices[oid + 1, 1] = k1
out_indices[oid + 1, 2] = k0
out_indices[oid + 2, 0] = j0
out_indices[oid + 2, 1] = j1
out_indices[oid + 2, 2] = k1
out_indices[oid + 3, 0] = j0
out_indices[oid + 3, 1] = i1
out_indices[oid + 3, 2] = j1
out_indices[oid + 4, 0] = j0
out_indices[oid + 4, 1] = i0
out_indices[oid + 4, 2] = i1
out_indices[oid + 5, 0] = j1
out_indices[oid + 5, 1] = i1
out_indices[oid + 5, 2] = k1
out_indices[oid + 6, 0] = i1
out_indices[oid + 6, 1] = i0
out_indices[oid + 6, 2] = k0
out_indices[oid + 7, 0] = i1
out_indices[oid + 7, 1] = k0
out_indices[oid + 7, 2] = k1
def solidify_mesh(faces: np.ndarray, vertices: np.ndarray, thickness: Union[list, float]):
"""
Triangulate mesh around given surface with given thickness.
:param faces: array of face indices (Nx3)
:param vertices: array of vertex positions (Mx3)
:param thickness: array of thickness values (Mx1) or single thickness value
:return: tuple of (faces, vertices)
"""
faces = np.array(faces).reshape(-1, 3)
out_faces = wp.zeros((len(faces) * 8, 3), dtype=wp.int32)
out_vertices = wp.zeros(len(vertices) * 2, dtype=wp.vec3)
if not isinstance(thickness, np.ndarray) and not isinstance(thickness, list):
thickness = [thickness] * len(vertices)
wp.launch(
solidify_mesh_kernel,
dim=len(faces),
inputs=[wp.array(faces, dtype=int), wp.array(vertices, dtype=wp.vec3), wp.array(thickness, dtype=float)],
outputs=[out_vertices, out_faces],
)
faces = out_faces.numpy()
vertices = out_vertices.numpy()
return faces, vertices
| warp-main | warp/render/utils.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 sys
import time
import warp as wp
from .utils import tab10_color_map
from collections import defaultdict
from typing import List, Tuple, Union, Optional
import numpy as np
import ctypes
Mat44 = Union[List[float], List[List[float]], np.ndarray]
wp.set_module_options({"enable_backward": False})
shape_vertex_shader = """
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoord;
// column vectors of the instance transform matrix
layout (location = 3) in vec4 aInstanceTransform0;
layout (location = 4) in vec4 aInstanceTransform1;
layout (location = 5) in vec4 aInstanceTransform2;
layout (location = 6) in vec4 aInstanceTransform3;
// colors to use for the checkerboard pattern
layout (location = 7) in vec3 aObjectColor1;
layout (location = 8) in vec3 aObjectColor2;
uniform mat4 view;
uniform mat4 model;
uniform mat4 projection;
out vec3 Normal;
out vec3 FragPos;
out vec2 TexCoord;
out vec3 ObjectColor1;
out vec3 ObjectColor2;
void main()
{
mat4 transform = model * mat4(aInstanceTransform0, aInstanceTransform1, aInstanceTransform2, aInstanceTransform3);
vec4 worldPos = transform * vec4(aPos, 1.0);
gl_Position = projection * view * worldPos;
FragPos = vec3(worldPos);
Normal = mat3(transpose(inverse(transform))) * aNormal;
TexCoord = aTexCoord;
ObjectColor1 = aObjectColor1;
ObjectColor2 = aObjectColor2;
}
"""
shape_fragment_shader = """
#version 330 core
out vec4 FragColor;
in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoord;
in vec3 ObjectColor1;
in vec3 ObjectColor2;
uniform vec3 viewPos;
uniform vec3 lightColor;
uniform vec3 sunDirection;
void main()
{
float ambientStrength = 0.3;
vec3 ambient = ambientStrength * lightColor;
vec3 norm = normalize(Normal);
float diff = max(dot(norm, sunDirection), 0.0);
vec3 diffuse = diff * lightColor;
vec3 lightDir2 = normalize(vec3(1.0, 0.3, -0.3));
diff = max(dot(norm, lightDir2), 0.0);
diffuse += diff * lightColor * 0.3;
float specularStrength = 0.5;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-sunDirection, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
vec3 specular = specularStrength * spec * lightColor;
reflectDir = reflect(-lightDir2, norm);
spec = pow(max(dot(viewDir, reflectDir), 0.0), 64);
specular += specularStrength * spec * lightColor * 0.3;
// checkerboard pattern
float u = TexCoord.x;
float v = TexCoord.y;
// blend the checkerboard pattern dependent on the gradient of the texture coordinates
// to void Moire patterns
vec2 grad = abs(dFdx(TexCoord)) + abs(dFdy(TexCoord));
float blendRange = 1.5;
float blendFactor = max(grad.x, grad.y) * blendRange;
float scale = 2.0;
float checker = mod(floor(u * scale) + floor(v * scale), 2.0);
checker = mix(checker, 0.5, smoothstep(0.0, 1.0, blendFactor));
vec3 checkerColor = mix(ObjectColor1, ObjectColor2, checker);
vec3 result = (ambient + diffuse + specular) * checkerColor;
FragColor = vec4(result, 1.0);
}
"""
grid_vertex_shader = """
#version 330 core
uniform mat4 view;
uniform mat4 model;
uniform mat4 projection;
in vec3 position;
void main() {
gl_Position = projection * view * model * vec4(position, 1.0);
}
"""
# Fragment shader source code
grid_fragment_shader = """
#version 330 core
out vec4 outColor;
void main() {
outColor = vec4(0.5, 0.5, 0.5, 1.0);
}
"""
sky_vertex_shader = """
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
layout (location = 2) in vec2 aTexCoord;
uniform mat4 view;
uniform mat4 model;
uniform mat4 projection;
uniform vec3 viewPos;
out vec3 FragPos;
out vec2 TexCoord;
void main()
{
vec4 worldPos = vec4(aPos + viewPos, 1.0);
gl_Position = projection * view * worldPos;
FragPos = vec3(worldPos);
TexCoord = aTexCoord;
}
"""
sky_fragment_shader = """
#version 330 core
out vec4 FragColor;
in vec3 FragPos;
in vec2 TexCoord;
uniform vec3 color1;
uniform vec3 color2;
uniform vec3 sunDirection;
void main()
{
float y = tanh(FragPos.y*0.01)*0.5+0.5;
float height = sqrt(1.0-y);
float s = pow(0.5, 1.0 / 10.0);
s = 1.0 - clamp(s, 0.75, 1.0);
vec3 haze = mix(vec3(1.0), color2 * 1.3, s);
vec3 sky = mix(color1, haze, height / 1.3);
float diff = max(dot(sunDirection, normalize(FragPos)), 0.0);
vec3 sun = pow(diff, 32) * vec3(1.0, 0.8, 0.6) * 0.5;
FragColor = vec4(sky + sun, 1.0);
}
"""
frame_vertex_shader = """
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
out vec2 TexCoord;
void main() {
gl_Position = vec4(aPos, 1.0);
TexCoord = aTexCoord;
}
"""
frame_fragment_shader = """
#version 330 core
in vec2 TexCoord;
out vec4 FragColor;
uniform sampler2D textureSampler;
void main() {
FragColor = texture(textureSampler, TexCoord);
}
"""
@wp.kernel
def update_vbo_transforms(
instance_id: wp.array(dtype=int),
instance_body: wp.array(dtype=int),
instance_transforms: wp.array(dtype=wp.transform),
instance_scalings: wp.array(dtype=wp.vec3),
body_q: wp.array(dtype=wp.transform),
# outputs
vbo_transforms: wp.array(dtype=wp.mat44),
):
tid = wp.tid()
i = instance_id[tid]
X_ws = instance_transforms[i]
if instance_body:
body = instance_body[i]
if body >= 0:
if body_q:
X_ws = body_q[body] * X_ws
else:
return
p = wp.transform_get_translation(X_ws)
q = wp.transform_get_rotation(X_ws)
s = instance_scalings[i]
rot = wp.quat_to_matrix(q)
# transposed definition
vbo_transforms[tid] = wp.mat44(
rot[0, 0] * s[0],
rot[1, 0] * s[0],
rot[2, 0] * s[0],
0.0,
rot[0, 1] * s[1],
rot[1, 1] * s[1],
rot[2, 1] * s[1],
0.0,
rot[0, 2] * s[2],
rot[1, 2] * s[2],
rot[2, 2] * s[2],
0.0,
p[0],
p[1],
p[2],
1.0,
)
@wp.kernel
def update_vbo_vertices(
points: wp.array(dtype=wp.vec3),
# outputs
vbo_vertices: wp.array(dtype=float, ndim=2),
):
tid = wp.tid()
p = points[tid]
vbo_vertices[tid, 0] = p[0]
vbo_vertices[tid, 1] = p[1]
vbo_vertices[tid, 2] = p[2]
@wp.kernel
def update_points_positions(
instance_positions: wp.array(dtype=wp.vec3),
instance_scalings: wp.array(dtype=wp.vec3),
# outputs
vbo_transforms: wp.array(dtype=wp.mat44),
):
tid = wp.tid()
p = instance_positions[tid]
s = wp.vec3(1.0)
if instance_scalings:
s = instance_scalings[tid]
# transposed definition
# fmt: off
vbo_transforms[tid] = wp.mat44(
s[0], 0.0, 0.0, 0.0,
0.0, s[1], 0.0, 0.0,
0.0, 0.0, s[2], 0.0,
p[0], p[1], p[2], 1.0)
# fmt: on
@wp.kernel
def update_line_transforms(
lines: wp.array(dtype=wp.vec3, ndim=2),
# outputs
vbo_transforms: wp.array(dtype=wp.mat44),
):
tid = wp.tid()
p0 = lines[tid, 0]
p1 = lines[tid, 1]
p = 0.5 * (p0 + p1)
d = p1 - p0
s = wp.length(d)
axis = wp.normalize(d)
y_up = wp.vec3(0.0, 1.0, 0.0)
angle = wp.acos(wp.dot(axis, y_up))
axis = wp.normalize(wp.cross(axis, y_up))
q = wp.quat_from_axis_angle(axis, -angle)
rot = wp.quat_to_matrix(q)
# transposed definition
# fmt: off
vbo_transforms[tid] = wp.mat44(
rot[0, 0], rot[1, 0], rot[2, 0], 0.0,
s * rot[0, 1], s * rot[1, 1], s * rot[2, 1], 0.0,
rot[0, 2], rot[1, 2], rot[2, 2], 0.0,
p[0], p[1], p[2], 1.0,
)
# fmt: on
@wp.kernel
def compute_gfx_vertices(
indices: wp.array(dtype=int, ndim=2),
vertices: wp.array(dtype=wp.vec3, ndim=1),
# outputs
gfx_vertices: wp.array(dtype=float, ndim=2),
):
tid = wp.tid()
v0 = vertices[indices[tid, 0]]
v1 = vertices[indices[tid, 1]]
v2 = vertices[indices[tid, 2]]
i = tid * 3
j = i + 1
k = i + 2
gfx_vertices[i, 0] = v0[0]
gfx_vertices[i, 1] = v0[1]
gfx_vertices[i, 2] = v0[2]
gfx_vertices[j, 0] = v1[0]
gfx_vertices[j, 1] = v1[1]
gfx_vertices[j, 2] = v1[2]
gfx_vertices[k, 0] = v2[0]
gfx_vertices[k, 1] = v2[1]
gfx_vertices[k, 2] = v2[2]
n = wp.normalize(wp.cross(v1 - v0, v2 - v0))
gfx_vertices[i, 3] = n[0]
gfx_vertices[i, 4] = n[1]
gfx_vertices[i, 5] = n[2]
gfx_vertices[j, 3] = n[0]
gfx_vertices[j, 4] = n[1]
gfx_vertices[j, 5] = n[2]
gfx_vertices[k, 3] = n[0]
gfx_vertices[k, 4] = n[1]
gfx_vertices[k, 5] = n[2]
@wp.kernel
def compute_average_normals(
indices: wp.array(dtype=int, ndim=2),
vertices: wp.array(dtype=wp.vec3),
# outputs
normals: wp.array(dtype=wp.vec3),
faces_per_vertex: wp.array(dtype=int),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
v0 = vertices[i]
v1 = vertices[j]
v2 = vertices[k]
n = wp.normalize(wp.cross(v1 - v0, v2 - v0))
wp.atomic_add(normals, i, n)
wp.atomic_add(faces_per_vertex, i, 1)
wp.atomic_add(normals, j, n)
wp.atomic_add(faces_per_vertex, j, 1)
wp.atomic_add(normals, k, n)
wp.atomic_add(faces_per_vertex, k, 1)
@wp.kernel
def assemble_gfx_vertices(
vertices: wp.array(dtype=wp.vec3, ndim=1),
normals: wp.array(dtype=wp.vec3),
faces_per_vertex: wp.array(dtype=int),
# outputs
gfx_vertices: wp.array(dtype=float, ndim=2),
):
tid = wp.tid()
v = vertices[tid]
n = normals[tid] / float(faces_per_vertex[tid])
gfx_vertices[tid, 0] = v[0]
gfx_vertices[tid, 1] = v[1]
gfx_vertices[tid, 2] = v[2]
gfx_vertices[tid, 3] = n[0]
gfx_vertices[tid, 4] = n[1]
gfx_vertices[tid, 5] = n[2]
@wp.kernel
def copy_frame(
input_img: wp.array(dtype=wp.uint8),
width: int,
height: int,
# outputs
output_img: wp.array(dtype=float, ndim=3),
):
w, v = wp.tid()
pixel = v * width + w
pixel *= 3
r = float(input_img[pixel + 0])
g = float(input_img[pixel + 1])
b = float(input_img[pixel + 2])
# flip vertically (OpenGL coordinates start at bottom)
v = height - v - 1
output_img[v, w, 0] = r / 255.0
output_img[v, w, 1] = g / 255.0
output_img[v, w, 2] = b / 255.0
@wp.kernel
def copy_frame_tiles(
input_img: wp.array(dtype=wp.uint8),
positions: wp.array(dtype=int, ndim=2),
screen_width: int,
screen_height: int,
tile_height: int,
# outputs
output_img: wp.array(dtype=float, ndim=4),
):
tile, x, y = wp.tid()
p = positions[tile]
qx = x + p[0]
qy = y + p[1]
pixel = qy * screen_width + qx
# flip vertically (OpenGL coordinates start at bottom)
y = tile_height - y - 1
if qx >= screen_width or qy >= screen_height:
output_img[tile, y, x, 0] = 0.0
output_img[tile, y, x, 1] = 0.0
output_img[tile, y, x, 2] = 0.0
return # prevent out-of-bounds access
pixel *= 3
r = float(input_img[pixel + 0])
g = float(input_img[pixel + 1])
b = float(input_img[pixel + 2])
output_img[tile, y, x, 0] = r / 255.0
output_img[tile, y, x, 1] = g / 255.0
output_img[tile, y, x, 2] = b / 255.0
@wp.kernel
def copy_frame_tile(
input_img: wp.array(dtype=wp.uint8),
offset_x: int,
offset_y: int,
screen_width: int,
screen_height: int,
tile_height: int,
# outputs
output_img: wp.array(dtype=float, ndim=4),
):
tile, x, y = wp.tid()
qx = x + offset_x
qy = y + offset_y
pixel = qy * screen_width + qx
# flip vertically (OpenGL coordinates start at bottom)
y = tile_height - y - 1
if qx >= screen_width or qy >= screen_height:
output_img[tile, y, x, 0] = 0.0
output_img[tile, y, x, 1] = 0.0
output_img[tile, y, x, 2] = 0.0
return # prevent out-of-bounds access
pixel *= 3
r = float(input_img[pixel + 0])
g = float(input_img[pixel + 1])
b = float(input_img[pixel + 2])
output_img[tile, y, x, 0] = r / 255.0
output_img[tile, y, x, 1] = g / 255.0
output_img[tile, y, x, 2] = b / 255.0
def check_gl_error():
from pyglet import gl
error = gl.glGetError()
if error != gl.GL_NO_ERROR:
print(f"OpenGL error: {error}")
class ShapeInstancer:
"""
Handles instanced rendering for a mesh.
Note the vertices must be in the 8-dimensional format:
[3D point, 3D normal, UV texture coordinates]
"""
def __init__(self, shape_shader, device):
self.shape_shader = shape_shader
self.device = device
self.face_count = 0
self.vao = None
self.instance_transform_gl_buffer = None
self.instance_color1_buffer = None
self.instance_color2_buffer = None
self.color1 = (1.0, 1.0, 1.0)
self.color2 = (0.0, 0.0, 0.0)
self.num_instances = 0
self.transforms = None
self.scalings = None
self._instance_transform_cuda_buffer = None
def __del__(self):
from pyglet import gl
if self.instance_transform_gl_buffer is not None:
try:
gl.glDeleteBuffers(1, self.instance_transform_gl_buffer)
gl.glDeleteBuffers(1, self.instance_color1_buffer)
gl.glDeleteBuffers(1, self.instance_color2_buffer)
except gl.GLException:
pass
if self.vao is not None:
try:
gl.glDeleteVertexArrays(1, self.vao)
gl.glDeleteBuffers(1, self.vbo)
gl.glDeleteBuffers(1, self.ebo)
except gl.GLException:
pass
def register_shape(self, vertices, indices, color1=(1.0, 1.0, 1.0), color2=(0.0, 0.0, 0.0)):
from pyglet import gl
if color1 is not None and color2 is None:
color2 = np.clip(np.array(color1) + 0.25, 0.0, 1.0)
self.color1 = color1
self.color2 = color2
gl.glUseProgram(self.shape_shader.id)
# Create VAO, VBO, and EBO
self.vao = gl.GLuint()
gl.glGenVertexArrays(1, self.vao)
gl.glBindVertexArray(self.vao)
self.vbo = gl.GLuint()
gl.glGenBuffers(1, self.vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices.ctypes.data, gl.GL_STATIC_DRAW)
self.ebo = gl.GLuint()
gl.glGenBuffers(1, self.ebo)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ebo)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ctypes.data, gl.GL_STATIC_DRAW)
# Set up vertex attributes
vertex_stride = vertices.shape[1] * vertices.itemsize
# positions
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(0)
# normals
gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(3 * vertices.itemsize))
gl.glEnableVertexAttribArray(1)
# uv coordinates
gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(6 * vertices.itemsize))
gl.glEnableVertexAttribArray(2)
gl.glBindVertexArray(0)
self.face_count = len(indices)
def allocate_instances(self, positions, rotations=None, colors1=None, colors2=None, scalings=None):
from pyglet import gl
gl.glBindVertexArray(self.vao)
self.num_instances = len(positions)
# Create instance buffer and bind it as an instanced array
if self.instance_transform_gl_buffer is None:
self.instance_transform_gl_buffer = gl.GLuint()
gl.glGenBuffers(1, self.instance_transform_gl_buffer)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.instance_transform_gl_buffer)
self.instance_ids = wp.array(np.arange(self.num_instances), dtype=wp.int32, device=self.device)
if rotations is None:
self.instance_transforms = wp.array(
[(*pos, 0.0, 0.0, 0.0, 1.0) for pos in positions], dtype=wp.transform, device=self.device
)
else:
self.instance_transforms = wp.array(
[(*pos, *rot) for pos, rot in zip(positions, rotations)], dtype=wp.transform, device=self.device
)
if scalings is None:
self.instance_scalings = wp.array(
np.tile((1.0, 1.0, 1.0), (self.num_instances, 1)), dtype=wp.vec3, device=self.device
)
else:
self.instance_scalings = wp.array(scalings, dtype=wp.vec3, device=self.device)
vbo_transforms = wp.zeros(dtype=wp.mat44, shape=(self.num_instances,), device=self.device)
wp.launch(
update_vbo_transforms,
dim=self.num_instances,
inputs=[
self.instance_ids,
None,
self.instance_transforms,
self.instance_scalings,
None,
],
outputs=[
vbo_transforms,
],
device=self.device,
)
vbo_transforms = vbo_transforms.numpy()
gl.glBufferData(gl.GL_ARRAY_BUFFER, vbo_transforms.nbytes, vbo_transforms.ctypes.data, gl.GL_DYNAMIC_DRAW)
# Create CUDA buffer for instance transforms
self._instance_transform_cuda_buffer = wp.RegisteredGLBuffer(
int(self.instance_transform_gl_buffer.value), self.device
)
if colors1 is None:
colors1 = np.tile(self.color1, (self.num_instances, 1))
if colors2 is None:
colors2 = np.tile(self.color2, (self.num_instances, 1))
colors1 = np.array(colors1, dtype=np.float32)
colors2 = np.array(colors2, dtype=np.float32)
# create buffer for checkerboard colors
if self.instance_color1_buffer is None:
self.instance_color1_buffer = gl.GLuint()
gl.glGenBuffers(1, self.instance_color1_buffer)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.instance_color1_buffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, colors1.nbytes, colors1.ctypes.data, gl.GL_STATIC_DRAW)
if self.instance_color2_buffer is None:
self.instance_color2_buffer = gl.GLuint()
gl.glGenBuffers(1, self.instance_color2_buffer)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.instance_color2_buffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, colors2.nbytes, colors2.ctypes.data, gl.GL_STATIC_DRAW)
# Set up instance attribute pointers
matrix_size = vbo_transforms[0].nbytes
gl.glBindVertexArray(self.vao)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.instance_transform_gl_buffer)
# we can only send vec4s to the shader, so we need to split the instance transforms matrix into its column vectors
for i in range(4):
gl.glVertexAttribPointer(
3 + i, 4, gl.GL_FLOAT, gl.GL_FALSE, matrix_size, ctypes.c_void_p(i * matrix_size // 4)
)
gl.glEnableVertexAttribArray(3 + i)
gl.glVertexAttribDivisor(3 + i, 1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.instance_color1_buffer)
gl.glVertexAttribPointer(7, 3, gl.GL_FLOAT, gl.GL_FALSE, colors1[0].nbytes, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(7)
gl.glVertexAttribDivisor(7, 1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.instance_color2_buffer)
gl.glVertexAttribPointer(8, 3, gl.GL_FLOAT, gl.GL_FALSE, colors2[0].nbytes, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(8)
gl.glVertexAttribDivisor(8, 1)
gl.glBindVertexArray(0)
def update_instances(self, transforms: wp.array = None, scalings: wp.array = None, colors1=None, colors2=None):
from pyglet import gl
if transforms is not None:
if transforms.device.is_cuda:
wp_transforms = transforms
else:
wp_transforms = transforms.to(self.device)
self.transforms = wp_transforms
if scalings is not None:
if transforms.device.is_cuda:
wp_scalings = scalings
else:
wp_scalings = scalings.to(self.device)
self.scalings = wp_scalings
if transforms is not None or scalings is not None:
gl.glBindVertexArray(self.vao)
vbo_transforms = self._instance_transform_cuda_buffer.map(dtype=wp.mat44, shape=(self.num_instances,))
wp.launch(
update_vbo_transforms,
dim=self.num_instances,
inputs=[
self.instance_ids,
None,
self.instance_transforms,
self.instance_scalings,
None,
],
outputs=[
vbo_transforms,
],
device=self.device,
)
self._instance_transform_cuda_buffer.unmap()
def render(self):
from pyglet import gl
gl.glUseProgram(self.shape_shader.id)
gl.glBindVertexArray(self.vao)
gl.glDrawElementsInstanced(gl.GL_TRIANGLES, self.face_count, gl.GL_UNSIGNED_INT, None, self.num_instances)
gl.glBindVertexArray(0)
# scope exposes VBO transforms to be set directly by a warp kernel
def __enter__(self):
from pyglet import gl
gl.glBindVertexArray(self.vao)
self.vbo_transforms = self._instance_transform_cuda_buffer.map(dtype=wp.mat44, shape=(self.num_instances,))
return self
def __exit__(self, exc_type, exc_value, traceback):
self._instance_transform_cuda_buffer.unmap()
def str_buffer(string: str):
return ctypes.c_char_p(string.encode("utf-8"))
def arr_pointer(arr: np.ndarray):
return arr.astype(np.float32).ctypes.data_as(ctypes.POINTER(ctypes.c_float))
class OpenGLRenderer:
"""
OpenGLRenderer is a simple OpenGL renderer for rendering 3D shapes and meshes.
"""
# number of segments to use for rendering spheres, capsules, cones and cylinders
default_num_segments = 32
def __init__(
self,
title="Warp sim",
scaling=1.0,
fps=60,
up_axis="Y",
screen_width=1024,
screen_height=768,
near_plane=0.01,
far_plane=1000.0,
camera_fov=45.0,
background_color=(0.53, 0.8, 0.92),
draw_grid=True,
draw_sky=True,
draw_axis=True,
show_info=True,
render_wireframe=False,
axis_scale=1.0,
vsync=False,
headless=False,
enable_backface_culling=True,
):
try:
import pyglet
# disable error checking for performance
pyglet.options["debug_gl"] = False
from pyglet import gl
from pyglet.math import Vec3 as PyVec3
from pyglet.graphics.shader import Shader, ShaderProgram
except ImportError:
raise Exception("OpenGLRenderer requires pyglet (version >= 2.0) to be installed.")
self.camera_near_plane = near_plane
self.camera_far_plane = far_plane
self.camera_fov = camera_fov
self.background_color = background_color
self.draw_grid = draw_grid
self.draw_sky = draw_sky
self.draw_axis = draw_axis
self.show_info = show_info
self.render_wireframe = render_wireframe
self.enable_backface_culling = enable_backface_culling
self._device = wp.get_cuda_device()
self._title = title
self.window = pyglet.window.Window(
width=screen_width, height=screen_height, caption=title, resizable=True, vsync=vsync, visible=not headless
)
self.app = pyglet.app
# making window current opengl rendering context
self.window.switch_to()
self.screen_width, self.screen_height = self.window.get_framebuffer_size()
self._camera_pos = PyVec3(0.0, 2.0, 10.0)
self._camera_front = PyVec3(0.0, 0.0, -1.0)
self._camera_up = PyVec3(0.0, 1.0, 0.0)
self._camera_speed = 0.04
if isinstance(up_axis, int):
self._camera_axis = up_axis
else:
self._camera_axis = "XYZ".index(up_axis.upper())
self._yaw, self._pitch = -90.0, 0.0
self._last_x, self._last_y = self.screen_width // 2, self.screen_height // 2
self._first_mouse = True
self._left_mouse_pressed = False
self._keys_pressed = defaultdict(bool)
self.update_view_matrix()
self.update_projection_matrix()
self._frame_dt = 1.0 / fps
self.time = 0.0
self._start_time = time.time()
self.clock_time = 0.0
self._paused = False
self._frame_speed = 0.0
self.skip_rendering = False
self._skip_frame_counter = 0
self._fps_update = 0.0
self._fps_render = 0.0
self._fps_alpha = 0.1 # low pass filter rate to update FPS stats
self._body_name = {}
self._shapes = []
self._shape_geo_hash = {}
self._shape_gl_buffers = {}
self._shape_instances = defaultdict(list)
self._instances = {}
self._instance_shape = {}
self._instance_gl_buffers = {}
self._instance_transform_gl_buffer = None
self._instance_transform_cuda_buffer = None
self._instance_color1_buffer = None
self._instance_color2_buffer = None
self._instance_count = 0
self._wp_instance_ids = None
self._instance_ids = None
self._inverse_instance_ids = None
self._wp_instance_transforms = None
self._wp_instance_scalings = None
self._wp_instance_bodies = None
self._update_shape_instances = False
self._add_shape_instances = False
# additional shape instancer used for points and line rendering
self._shape_instancers = {}
# instancer for the arrow shapes sof the coordinate system axes
self._axis_instancer = None
# toggle tiled rendering
self._tiled_rendering = False
self._tile_instances = None
self._tile_ncols = 0
self._tile_nrows = 0
self._tile_width = 0
self._tile_height = 0
self._tile_viewports = None
self._tile_view_matrices = None
self._tile_projection_matrices = None
self._frame_texture = None
self._frame_fbo = None
self._frame_pbo = None
self.window.push_handlers(on_draw=self._draw)
self.window.push_handlers(on_resize=self._window_resize_callback)
self.window.push_handlers(on_key_press=self._key_press_callback)
self._key_handler = pyglet.window.key.KeyStateHandler()
self.window.push_handlers(self._key_handler)
self.window.on_mouse_scroll = self._scroll_callback
self.window.on_mouse_drag = self._mouse_drag_callback
gl.glClearColor(*self.background_color, 1)
gl.glEnable(gl.GL_DEPTH_TEST)
self._shape_shader = ShaderProgram(
Shader(shape_vertex_shader, "vertex"), Shader(shape_fragment_shader, "fragment")
)
self._grid_shader = ShaderProgram(
Shader(grid_vertex_shader, "vertex"), Shader(grid_fragment_shader, "fragment")
)
self._sun_direction = np.array((-0.2, 0.8, 0.3))
self._sun_direction /= np.linalg.norm(self._sun_direction)
with self._shape_shader:
gl.glUniform3f(
gl.glGetUniformLocation(self._shape_shader.id, str_buffer("sunDirection")), *self._sun_direction
)
gl.glUniform3f(gl.glGetUniformLocation(self._shape_shader.id, str_buffer("lightColor")), 1, 1, 1)
self._loc_shape_model = gl.glGetUniformLocation(self._shape_shader.id, str_buffer("model"))
self._loc_shape_view = gl.glGetUniformLocation(self._shape_shader.id, str_buffer("view"))
self._loc_shape_projection = gl.glGetUniformLocation(self._shape_shader.id, str_buffer("projection"))
self._loc_shape_view_pos = gl.glGetUniformLocation(self._shape_shader.id, str_buffer("viewPos"))
gl.glUniform3f(self._loc_shape_view_pos, 0, 0, 10)
# create grid data
limit = 10.0
ticks = np.linspace(-limit, limit, 21)
grid_vertices = []
for i in ticks:
if self._camera_axis == 0:
grid_vertices.extend([0, -limit, i, 0, limit, i])
grid_vertices.extend([0, i, -limit, 0, i, limit])
elif self._camera_axis == 1:
grid_vertices.extend([-limit, 0, i, limit, 0, i])
grid_vertices.extend([i, 0, -limit, i, 0, limit])
elif self._camera_axis == 2:
grid_vertices.extend([-limit, i, 0, limit, i, 0])
grid_vertices.extend([i, -limit, 0, i, limit, 0])
grid_vertices = np.array(grid_vertices, dtype=np.float32)
self._grid_vertex_count = len(grid_vertices) // 3
with self._grid_shader:
self._grid_vao = gl.GLuint()
gl.glGenVertexArrays(1, self._grid_vao)
gl.glBindVertexArray(self._grid_vao)
self._grid_vbo = gl.GLuint()
gl.glGenBuffers(1, self._grid_vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._grid_vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, grid_vertices.nbytes, grid_vertices.ctypes.data, gl.GL_STATIC_DRAW)
self._loc_grid_view = gl.glGetUniformLocation(self._grid_shader.id, str_buffer("view"))
self._loc_grid_model = gl.glGetUniformLocation(self._grid_shader.id, str_buffer("model"))
self._loc_grid_projection = gl.glGetUniformLocation(self._grid_shader.id, str_buffer("projection"))
self._loc_grid_pos_attribute = gl.glGetAttribLocation(self._grid_shader.id, str_buffer("position"))
gl.glVertexAttribPointer(self._loc_grid_pos_attribute, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glEnableVertexAttribArray(self._loc_grid_pos_attribute)
# create sky data
self._sky_shader = ShaderProgram(Shader(sky_vertex_shader, "vertex"), Shader(sky_fragment_shader, "fragment"))
with self._sky_shader:
self._loc_sky_view = gl.glGetUniformLocation(self._sky_shader.id, str_buffer("view"))
self._loc_sky_model = gl.glGetUniformLocation(self._sky_shader.id, str_buffer("model"))
self._loc_sky_projection = gl.glGetUniformLocation(self._sky_shader.id, str_buffer("projection"))
self._loc_sky_color1 = gl.glGetUniformLocation(self._sky_shader.id, str_buffer("color1"))
self._loc_sky_color2 = gl.glGetUniformLocation(self._sky_shader.id, str_buffer("color2"))
gl.glUniform3f(self._loc_sky_color1, *background_color)
# glUniform3f(self._loc_sky_color2, *np.clip(np.array(background_color)+0.5, 0.0, 1.0))
gl.glUniform3f(self._loc_sky_color2, 0.8, 0.4, 0.05)
self._loc_sky_view_pos = gl.glGetUniformLocation(self._sky_shader.id, str_buffer("viewPos"))
gl.glUniform3f(
gl.glGetUniformLocation(self._sky_shader.id, str_buffer("sunDirection")), *self._sun_direction
)
# Create VAO, VBO, and EBO
self._sky_vao = gl.GLuint()
gl.glGenVertexArrays(1, self._sky_vao)
gl.glBindVertexArray(self._sky_vao)
vertices, indices = self._create_sphere_mesh(self.camera_far_plane * 0.9, 32, 32, reverse_winding=True)
self._sky_tri_count = len(indices)
self._sky_vbo = gl.GLuint()
gl.glGenBuffers(1, self._sky_vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._sky_vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices.ctypes.data, gl.GL_STATIC_DRAW)
self._sky_ebo = gl.GLuint()
gl.glGenBuffers(1, self._sky_ebo)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._sky_ebo)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ctypes.data, gl.GL_STATIC_DRAW)
# Set up vertex attributes
vertex_stride = vertices.shape[1] * vertices.itemsize
# positions
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(0)
# normals
gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(3 * vertices.itemsize))
gl.glEnableVertexAttribArray(1)
# uv coordinates
gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(6 * vertices.itemsize))
gl.glEnableVertexAttribArray(2)
gl.glBindVertexArray(0)
self._last_time = time.time()
self._last_begin_frame_time = self._last_time
self._last_end_frame_time = self._last_time
# create arrow shapes for the coordinate system axes
vertices, indices = self._create_arrow_mesh(
base_radius=0.02 * axis_scale, base_height=0.85 * axis_scale, cap_height=0.15 * axis_scale
)
self._axis_instancer = ShapeInstancer(self._shape_shader, self._device)
self._axis_instancer.register_shape(vertices, indices)
sqh = np.sqrt(0.5)
self._axis_instancer.allocate_instances(
positions=[(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)],
rotations=[(0.0, 0.0, 0.0, 1.0), (0.0, 0.0, -sqh, sqh), (sqh, 0.0, 0.0, sqh)],
colors1=[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)],
colors2=[(0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)],
)
# create frame buffer for rendering to a texture
self._frame_texture = None
self._frame_fbo = None
self._setup_framebuffer()
# fmt: off
# set up VBO for the quad that is rendered to the user window with the texture
self._frame_vertices = np.array([
# Positions TexCoords
-1.0, -1.0, 0.0, 0.0,
1.0, -1.0, 1.0, 0.0,
1.0, 1.0, 1.0, 1.0,
-1.0, 1.0, 0.0, 1.0
], dtype=np.float32)
# fmt: on
self._frame_indices = np.array([0, 1, 2, 2, 3, 0], dtype=np.uint32)
self._frame_vao = gl.GLuint()
gl.glGenVertexArrays(1, self._frame_vao)
gl.glBindVertexArray(self._frame_vao)
self._frame_vbo = gl.GLuint()
gl.glGenBuffers(1, self._frame_vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._frame_vbo)
gl.glBufferData(
gl.GL_ARRAY_BUFFER, self._frame_vertices.nbytes, self._frame_vertices.ctypes.data, gl.GL_STATIC_DRAW
)
self._frame_ebo = gl.GLuint()
gl.glGenBuffers(1, self._frame_ebo)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._frame_ebo)
gl.glBufferData(
gl.GL_ELEMENT_ARRAY_BUFFER, self._frame_indices.nbytes, self._frame_indices.ctypes.data, gl.GL_STATIC_DRAW
)
gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 4 * self._frame_vertices.itemsize, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(0)
gl.glVertexAttribPointer(
1, 2, gl.GL_FLOAT, gl.GL_FALSE, 4 * self._frame_vertices.itemsize, ctypes.c_void_p(2 * vertices.itemsize)
)
gl.glEnableVertexAttribArray(1)
self._frame_shader = ShaderProgram(
Shader(frame_vertex_shader, "vertex"), Shader(frame_fragment_shader, "fragment")
)
gl.glUseProgram(self._frame_shader.id)
self._frame_loc_texture = gl.glGetUniformLocation(self._frame_shader.id, str_buffer("textureSampler"))
# Unbind the VBO and VAO
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
gl.glBindVertexArray(0)
# update model matrix
self.scaling = scaling
check_gl_error()
# create text to render stats on the screen
self._info_label = pyglet.text.Label(
"",
font_name="Arial",
font_size=12,
color=(255, 255, 255, 255),
x=10,
y=10,
anchor_x="left",
anchor_y="top",
multiline=True,
width=400,
)
# set up our own event handling so we can synchronously render frames
# by calling update() in a loop
from pyglet.window import Window
Window._enable_event_queue = False
self.window.switch_to()
self.window.dispatch_pending_events()
platform_event_loop = self.app.platform_event_loop
platform_event_loop.start()
# start event loop
self.app.event_loop.dispatch_event("on_enter")
@property
def paused(self):
return self._paused
@paused.setter
def paused(self, value):
self._paused = value
if value:
self.window.set_caption(f"{self._title} (paused)")
else:
self.window.set_caption(self._title)
@property
def has_exit(self):
return self.app.event_loop.has_exit
def clear(self):
from pyglet import gl
self.app.event_loop.dispatch_event("on_exit")
self.app.platform_event_loop.stop()
if self._instance_transform_gl_buffer is not None:
try:
gl.glDeleteBuffers(1, self._instance_transform_gl_buffer)
gl.glDeleteBuffers(1, self._instance_color1_buffer)
gl.glDeleteBuffers(1, self._instance_color2_buffer)
except gl.GLException:
pass
for vao, vbo, ebo, _, vertex_cuda_buffer in self._shape_gl_buffers.values():
try:
gl.glDeleteVertexArrays(1, vao)
gl.glDeleteBuffers(1, vbo)
gl.glDeleteBuffers(1, ebo)
except gl.GLException:
pass
self._body_name.clear()
self._shapes.clear()
self._shape_geo_hash.clear()
self._shape_gl_buffers.clear()
self._shape_instances.clear()
self._instances.clear()
self._instance_shape.clear()
self._instance_gl_buffers.clear()
self._instance_transform_gl_buffer = None
self._instance_transform_cuda_buffer = None
self._instance_color1_buffer = None
self._instance_color2_buffer = None
self._wp_instance_ids = None
self._wp_instance_transforms = None
self._wp_instance_scalings = None
self._wp_instance_bodies = None
self._update_shape_instances = False
@property
def tiled_rendering(self):
return self._tiled_rendering
@tiled_rendering.setter
def tiled_rendering(self, value):
if value:
assert self._tile_instances is not None, "Tiled rendering is not set up. Call setup_tiled_rendering first."
self._tiled_rendering = value
def setup_tiled_rendering(
self,
instances: List[List[int]],
rescale_window: bool = False,
tile_width: Optional[int] = None,
tile_height: Optional[int] = None,
tile_ncols: Optional[int] = None,
tile_nrows: Optional[int] = None,
tile_positions: Optional[List[Tuple[int]]] = None,
tile_sizes: Optional[List[Tuple[int]]] = None,
projection_matrices: Optional[List[Mat44]] = None,
view_matrices: Optional[List[Mat44]] = None,
):
"""
Set up tiled rendering where the render buffer is split into multiple tiles that can visualize
different shape instances of the scene with different view and projection matrices.
See `get_pixels` which allows to retrieve the pixels of for each tile.
:param instances: A list of lists of shape instance ids. Each list of shape instance ids
will be rendered into a separate tile.
:param rescale_window: If True, the window will be resized to fit the tiles.
:param tile_width: The width of each tile in pixels (optional).
:param tile_height: The height of each tile in pixels (optional).
:param tile_ncols: The number of tiles rendered horizontally (optional). Will be considered
if `tile_width` is set to compute the tile positions, unless `tile_positions` is defined.
:param tile_positions: A list of (x, y) tuples specifying the position of each tile in pixels.
If None, the tiles will be arranged in a square grid, or, if `tile_ncols` and `tile_nrows`
is set, in a grid with the specified number of columns and rows.
:param tile_sizes: A list of (width, height) tuples specifying the size of each tile in pixels.
If None, the tiles will have the same size as specified by `tile_width` and `tile_height`.
:param projection_matrices: A list of projection matrices for each tile (each view matrix is
either a flattened 16-dimensional array or a 4x4 matrix).
If the entire array is None, or only a view instances, the projection matrices for all, or these
instances, respectively, will be derived from the current render settings.
:param view_matrices: A list of view matrices for each tile (each view matrix is either a flattened
16-dimensional array or a 4x4 matrix).
If the entire array is None, or only a view instances, the view matrices for all, or these
instances, respectively, will be derived from the current camera settings and be
updated when the camera is moved.
"""
assert len(instances) > 0 and all(isinstance(i, list) for i in instances), "Invalid tile instances."
self._tile_instances = instances
n = len(self._tile_instances)
if tile_positions is None or tile_sizes is None:
if tile_ncols is None or tile_nrows is None:
# try to fit the tiles into a square
self._tile_ncols = int(np.ceil(np.sqrt(n)))
self._tile_nrows = int(np.ceil(n / float(self._tile_ncols)))
else:
self._tile_ncols = tile_ncols
self._tile_nrows = tile_nrows
self._tile_width = tile_width or max(32, self.screen_width // self._tile_ncols)
self._tile_height = tile_height or max(32, self.screen_height // self._tile_nrows)
self._tile_viewports = [
(i * self._tile_width, j * self._tile_height, self._tile_width, self._tile_height)
for i in range(self._tile_ncols)
for j in range(self._tile_nrows)
]
if rescale_window:
self.window.set_size(self._tile_width * self._tile_ncols, self._tile_height * self._tile_nrows)
else:
assert (
len(tile_positions) == n and len(tile_sizes) == n
), "Number of tiles does not match number of instances."
self._tile_ncols = None
self._tile_nrows = None
self._tile_width = None
self._tile_height = None
if all([tile_sizes[i][0] == tile_sizes[0][0] for i in range(n)]):
# tiles all have the same width
self._tile_width = tile_sizes[0][0]
if all([tile_sizes[i][1] == tile_sizes[0][1] for i in range(n)]):
# tiles all have the same height
self._tile_height = tile_sizes[0][1]
self._tile_viewports = [(x, y, w, h) for (x, y), (w, h) in zip(tile_positions, tile_sizes)]
if projection_matrices is None:
projection_matrices = [None] * n
self._tile_projection_matrices = []
for i, p in enumerate(projection_matrices):
if p is None:
w, h = self._tile_viewports[i][2:]
self._tile_projection_matrices.append(
self.compute_projection_matrix(
self.camera_fov, w / h, self.camera_near_plane, self.camera_far_plane
)
)
else:
self._tile_projection_matrices.append(np.array(p).flatten())
if view_matrices is None:
self._tile_view_matrices = [None] * n
else:
self._tile_view_matrices = [np.array(m).flatten() for m in view_matrices]
self._tiled_rendering = True
def update_tile(
self,
tile_id,
instances: Optional[List[int]] = None,
projection_matrix: Optional[Mat44] = None,
view_matrix: Optional[Mat44] = None,
tile_size: Optional[Tuple[int]] = None,
tile_position: Optional[Tuple[int]] = None,
):
"""
Update the shape instances, projection matrix, view matrix, tile size, or tile position
for a given tile given its index.
:param tile_id: The index of the tile to update.
:param instances: A list of shape instance ids (optional).
:param projection_matrix: A projection matrix (optional).
:param view_matrix: A view matrix (optional).
:param tile_size: A (width, height) tuple specifying the size of the tile in pixels (optional).
:param tile_position: A (x, y) tuple specifying the position of the tile in pixels (optional).
"""
assert self._tile_instances is not None, "Tiled rendering is not set up. Call setup_tiled_rendering first."
assert tile_id < len(self._tile_instances), "Invalid tile id."
if instances is not None:
self._tile_instances[tile_id] = instances
if projection_matrix is not None:
self._tile_projection_matrices[tile_id] = np.array(projection_matrix).flatten()
if view_matrix is not None:
self._tile_view_matrices[tile_id] = np.array(view_matrix).flatten()
(x, y, w, h) = self._tile_viewports[tile_id]
if tile_size is not None:
w, h = tile_size
if tile_position is not None:
x, y = tile_position
self._tile_viewports[tile_id] = (x, y, w, h)
def _setup_framebuffer(self):
from pyglet import gl
if self._frame_texture is None:
self._frame_texture = gl.GLuint()
gl.glGenTextures(1, self._frame_texture)
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, 0)
gl.glBindTexture(gl.GL_TEXTURE_2D, self._frame_texture)
gl.glTexImage2D(
gl.GL_TEXTURE_2D,
0,
gl.GL_RGB,
self.screen_width,
self.screen_height,
0,
gl.GL_RGB,
gl.GL_UNSIGNED_BYTE,
None,
)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
# create a framebuffer object (FBO)
if self._frame_fbo is None:
self._frame_fbo = gl.GLuint()
gl.glGenFramebuffers(1, self._frame_fbo)
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self._frame_fbo)
# attach the texture to the FBO as its color attachment
gl.glFramebufferTexture2D(
gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, self._frame_texture, 0
)
self._frame_depth_renderbuffer = gl.GLuint()
gl.glGenRenderbuffers(1, self._frame_depth_renderbuffer)
gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self._frame_depth_renderbuffer)
gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT, self.screen_width, self.screen_height)
# attach the depth renderbuffer to the FBO
gl.glFramebufferRenderbuffer(
gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, gl.GL_RENDERBUFFER, self._frame_depth_renderbuffer
)
if gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) != gl.GL_FRAMEBUFFER_COMPLETE:
print("Framebuffer is not complete!")
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
sys.exit(1)
gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0)
else:
# rescale framebuffer
gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, self._frame_depth_renderbuffer)
gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT, self.screen_width, self.screen_height)
gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0)
# unbind the FBO (switch back to the default framebuffer)
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
if self._frame_pbo is None:
self._frame_pbo = gl.GLuint()
gl.glGenBuffers(1, self._frame_pbo) # generate 1 buffer reference
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, self._frame_pbo) # binding to this buffer
# allocate memory for PBO
pixels = np.zeros((self.screen_height, self.screen_width, 3), dtype=np.uint8)
gl.glBufferData(gl.GL_PIXEL_PACK_BUFFER, pixels.nbytes, pixels.ctypes.data, gl.GL_DYNAMIC_DRAW)
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, 0)
@staticmethod
def compute_projection_matrix(
fov: float,
aspect_ratio: float,
near_plane: float,
far_plane: float,
) -> Mat44:
"""
Compute a projection matrix given the field of view, aspect ratio, near plane, and far plane.
:param fov: The field of view in degrees.
:param aspect_ratio: The aspect ratio (width / height).
:param near_plane: The near plane.
:param far_plane: The far plane.
:return: A projection matrix.
"""
from pyglet.math import Mat4 as PyMat4
return np.array(PyMat4.perspective_projection(aspect_ratio, near_plane, far_plane, fov))
def update_projection_matrix(self):
if self.screen_height == 0:
return
aspect_ratio = self.screen_width / self.screen_height
self._projection_matrix = self.compute_projection_matrix(
self.camera_fov, aspect_ratio, self.camera_near_plane, self.camera_far_plane
)
def update_view_matrix(self):
from pyglet.math import Mat4 as PyMat4
cam_pos = self._camera_pos
self._view_matrix = np.array(PyMat4.look_at(cam_pos, cam_pos + self._camera_front, self._camera_up))
def update_model_matrix(self):
from pyglet import gl
# fmt: off
if self._camera_axis == 0:
self._model_matrix = np.array((
0, 0, self._scaling, 0,
self._scaling, 0, 0, 0,
0, self._scaling, 0, 0,
0, 0, 0, 1
))
elif self._camera_axis == 2:
self._model_matrix = np.array((
-self._scaling, 0, 0, 0,
0, 0, self._scaling, 0,
0, self._scaling, 0, 0,
0, 0, 0, 1
))
else:
self._model_matrix = np.array((
self._scaling, 0, 0, 0,
0, self._scaling, 0, 0,
0, 0, self._scaling, 0,
0, 0, 0, 1
))
# fmt: on
ptr = arr_pointer(self._model_matrix)
gl.glUseProgram(self._shape_shader.id)
gl.glUniformMatrix4fv(self._loc_shape_model, 1, gl.GL_FALSE, ptr)
gl.glUseProgram(self._grid_shader.id)
gl.glUniformMatrix4fv(self._loc_grid_model, 1, gl.GL_FALSE, ptr)
gl.glUseProgram(self._sky_shader.id)
gl.glUniformMatrix4fv(self._loc_sky_model, 1, gl.GL_FALSE, ptr)
@property
def num_tiles(self):
return len(self._tile_instances)
@property
def tile_width(self):
return self._tile_width
@property
def tile_height(self):
return self._tile_height
@property
def num_shapes(self):
return len(self._shapes)
@property
def num_instances(self):
return self._instance_count
@property
def scaling(self):
return self._scaling
@scaling.setter
def scaling(self, scaling):
self._scaling = scaling
self.update_model_matrix()
def begin_frame(self, t: float = None):
self._last_begin_frame_time = time.time()
self.time = t or self.clock_time
def end_frame(self):
self._last_end_frame_time = time.time()
if self._add_shape_instances:
self.allocate_shape_instances()
if self._update_shape_instances:
self.update_shape_instances()
self.update()
while self.paused and self.is_running():
self.update()
def update(self):
self.clock_time = time.time() - self._start_time
update_duration = self.clock_time - self._last_time
frame_duration = self._last_end_frame_time - self._last_begin_frame_time
self._last_time = self.clock_time
self._frame_speed = update_duration * 100.0
# self.app.event_loop.idle()
self.app.platform_event_loop.step(self._frame_dt * 1e-3)
if not self.skip_rendering:
self._skip_frame_counter += 1
if self._skip_frame_counter > 100:
self._skip_frame_counter = 0
if frame_duration > 0.0:
if self._fps_update is None:
self._fps_update = 1.0 / frame_duration
else:
update = 1.0 / frame_duration
self._fps_update = (1.0 - self._fps_alpha) * self._fps_update + self._fps_alpha * update
if update_duration > 0.0:
if self._fps_render is None:
self._fps_render = 1.0 / update_duration
else:
update = 1.0 / update_duration
self._fps_render = (1.0 - self._fps_alpha) * self._fps_render + self._fps_alpha * update
self.app.event_loop._redraw_windows(self._frame_dt * 1e-3)
def _draw(self):
from pyglet import gl
# catch key hold events
self._process_inputs()
if self.enable_backface_culling:
gl.glEnable(gl.GL_CULL_FACE)
else:
gl.glDisable(gl.GL_CULL_FACE)
if self._frame_fbo is not None:
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self._frame_fbo)
gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, self._frame_fbo)
gl.glClearColor(*self.background_color, 1)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glBindVertexArray(0)
if not self._tiled_rendering:
if self.draw_grid:
self._draw_grid()
if self.draw_sky:
self._draw_sky()
view_mat_ptr = arr_pointer(self._view_matrix)
projection_mat_ptr = arr_pointer(self._projection_matrix)
gl.glUseProgram(self._shape_shader.id)
gl.glUniformMatrix4fv(self._loc_shape_view, 1, gl.GL_FALSE, view_mat_ptr)
gl.glUniform3f(self._loc_shape_view_pos, *self._camera_pos)
gl.glUniformMatrix4fv(self._loc_shape_view, 1, gl.GL_FALSE, view_mat_ptr)
gl.glUniformMatrix4fv(self._loc_shape_projection, 1, gl.GL_FALSE, projection_mat_ptr)
if self.render_wireframe:
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)
if self._tiled_rendering:
self._render_scene_tiled()
else:
self._render_scene()
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL)
gl.glBindBuffer(gl.GL_PIXEL_UNPACK_BUFFER, 0)
gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glViewport(0, 0, self.screen_width, self.screen_height)
# render frame buffer texture to screen
if self._frame_fbo is not None:
with self._frame_shader:
gl.glActiveTexture(gl.GL_TEXTURE0)
gl.glBindTexture(gl.GL_TEXTURE_2D, self._frame_texture)
gl.glUniform1i(self._frame_loc_texture, 0)
gl.glBindVertexArray(self._frame_vao)
gl.glDrawElements(gl.GL_TRIANGLES, len(self._frame_indices), gl.GL_UNSIGNED_INT, None)
gl.glBindVertexArray(0)
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
# check for OpenGL errors
# check_gl_error()
if self.show_info:
gl.glClear(gl.GL_DEPTH_BUFFER_BIT)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.glEnable(gl.GL_BLEND)
text = f"""Sim Time: {self.time:.1f}
Update FPS: {self._fps_update:.1f}
Render FPS: {self._fps_render:.1f}
Shapes: {len(self._shapes)}
Instances: {len(self._instances)}"""
if self.paused:
text += "\nPaused (press space to resume)"
self._info_label.text = text
self._info_label.y = self.screen_height - 5
self._info_label.draw()
def _draw_grid(self, is_tiled=False):
from pyglet import gl
if not is_tiled:
gl.glUseProgram(self._grid_shader.id)
gl.glUniformMatrix4fv(self._loc_grid_view, 1, gl.GL_FALSE, arr_pointer(self._view_matrix))
gl.glUniformMatrix4fv(self._loc_grid_projection, 1, gl.GL_FALSE, arr_pointer(self._projection_matrix))
gl.glBindVertexArray(self._grid_vao)
gl.glDrawArrays(gl.GL_LINES, 0, self._grid_vertex_count)
gl.glBindVertexArray(0)
def _draw_sky(self, is_tiled=False):
from pyglet import gl
if not is_tiled:
gl.glUseProgram(self._sky_shader.id)
gl.glUniformMatrix4fv(self._loc_sky_view, 1, gl.GL_FALSE, arr_pointer(self._view_matrix))
gl.glUniformMatrix4fv(self._loc_sky_projection, 1, gl.GL_FALSE, arr_pointer(self._projection_matrix))
gl.glUniform3f(self._loc_sky_view_pos, *self._camera_pos)
gl.glBindVertexArray(self._sky_vao)
gl.glDrawElements(gl.GL_TRIANGLES, self._sky_tri_count, gl.GL_UNSIGNED_INT, None)
gl.glBindVertexArray(0)
def _render_scene(self):
from pyglet import gl
start_instance_idx = 0
for shape, (vao, _, _, tri_count, _) in self._shape_gl_buffers.items():
num_instances = len(self._shape_instances[shape])
gl.glBindVertexArray(vao)
gl.glDrawElementsInstancedBaseInstance(
gl.GL_TRIANGLES, tri_count, gl.GL_UNSIGNED_INT, None, num_instances, start_instance_idx
)
start_instance_idx += num_instances
if self.draw_axis:
self._axis_instancer.render()
for instancer in self._shape_instancers.values():
instancer.render()
gl.glBindVertexArray(0)
def _render_scene_tiled(self):
from pyglet import gl
for i, viewport in enumerate(self._tile_viewports):
projection_matrix_ptr = arr_pointer(self._tile_projection_matrices[i])
view_matrix_ptr = arr_pointer(self._tile_view_matrices[i] or self._view_matrix)
gl.glViewport(*viewport)
if self.draw_grid:
gl.glUseProgram(self._grid_shader.id)
gl.glUniformMatrix4fv(self._loc_grid_projection, 1, gl.GL_FALSE, projection_matrix_ptr)
gl.glUniformMatrix4fv(self._loc_grid_view, 1, gl.GL_FALSE, view_matrix_ptr)
self._draw_grid(is_tiled=True)
if self.draw_sky:
gl.glUseProgram(self._sky_shader.id)
gl.glUniformMatrix4fv(self._loc_sky_projection, 1, gl.GL_FALSE, projection_matrix_ptr)
gl.glUniformMatrix4fv(self._loc_sky_view, 1, gl.GL_FALSE, view_matrix_ptr)
self._draw_sky(is_tiled=True)
gl.glUseProgram(self._shape_shader.id)
gl.glUniformMatrix4fv(self._loc_shape_projection, 1, gl.GL_FALSE, projection_matrix_ptr)
gl.glUniformMatrix4fv(self._loc_shape_view, 1, gl.GL_FALSE, view_matrix_ptr)
instances = self._tile_instances[i]
for instance in instances:
shape = self._instance_shape[instance]
vao, _, _, tri_count, _ = self._shape_gl_buffers[shape]
start_instance_idx = self._inverse_instance_ids[instance]
gl.glBindVertexArray(vao)
gl.glDrawElementsInstancedBaseInstance(
gl.GL_TRIANGLES, tri_count, gl.GL_UNSIGNED_INT, None, 1, start_instance_idx
)
if self.draw_axis:
self._axis_instancer.render()
for instancer in self._shape_instancers.values():
instancer.render()
gl.glBindVertexArray(0)
def _mouse_drag_callback(self, x, y, dx, dy, buttons, modifiers):
import pyglet
if buttons & pyglet.window.mouse.LEFT:
sensitivity = 0.1
dx *= sensitivity
dy *= sensitivity
self._yaw += dx
self._pitch += dy
self._pitch = max(min(self._pitch, 89.0), -89.0)
self._camera_front.x = np.cos(np.deg2rad(self._yaw)) * np.cos(np.deg2rad(self._pitch))
self._camera_front.y = np.sin(np.deg2rad(self._pitch))
self._camera_front.z = np.sin(np.deg2rad(self._yaw)) * np.cos(np.deg2rad(self._pitch))
self._camera_front = self._camera_front.normalize()
self.update_view_matrix()
def _scroll_callback(self, x, y, scroll_x, scroll_y):
self.camera_fov -= scroll_y
self.camera_fov = max(min(self.camera_fov, 90.0), 15.0)
self.update_projection_matrix()
def _process_inputs(self):
import pyglet
from pyglet.math import Vec3 as PyVec3
if self._key_handler[pyglet.window.key.W] or self._key_handler[pyglet.window.key.UP]:
self._camera_pos += self._camera_front * (self._camera_speed * self._frame_speed)
self.update_view_matrix()
if self._key_handler[pyglet.window.key.S] or self._key_handler[pyglet.window.key.DOWN]:
self._camera_pos -= self._camera_front * (self._camera_speed * self._frame_speed)
self.update_view_matrix()
if self._key_handler[pyglet.window.key.A] or self._key_handler[pyglet.window.key.LEFT]:
camera_side = PyVec3.cross(self._camera_front, self._camera_up).normalize()
self._camera_pos -= camera_side * (self._camera_speed * self._frame_speed)
self.update_view_matrix()
if self._key_handler[pyglet.window.key.D] or self._key_handler[pyglet.window.key.RIGHT]:
camera_side = PyVec3.cross(self._camera_front, self._camera_up).normalize()
self._camera_pos += camera_side * (self._camera_speed * self._frame_speed)
self.update_view_matrix()
def _key_press_callback(self, symbol, modifiers):
import pyglet
if symbol == pyglet.window.key.ESCAPE:
self.window.close()
if symbol == pyglet.window.key.SPACE:
self.paused = not self.paused
if symbol == pyglet.window.key.TAB:
self.skip_rendering = not self.skip_rendering
if symbol == pyglet.window.key.C:
self.draw_axis = not self.draw_axis
if symbol == pyglet.window.key.G:
self.draw_grid = not self.draw_grid
if symbol == pyglet.window.key.I:
self.show_info = not self.show_info
if symbol == pyglet.window.key.X:
self.render_wireframe = not self.render_wireframe
if symbol == pyglet.window.key.B:
self.enable_backface_culling = not self.enable_backface_culling
def _window_resize_callback(self, width, height):
self._first_mouse = True
self.screen_width, self.screen_height = self.window.get_framebuffer_size()
self.update_projection_matrix()
self._setup_framebuffer()
def register_shape(self, geo_hash, vertices, indices, color1=None, color2=None):
from pyglet import gl
shape = len(self._shapes)
if color1 is None:
color1 = tab10_color_map(len(self._shape_geo_hash))
if color2 is None:
color2 = np.clip(np.array(color1) + 0.25, 0.0, 1.0)
# TODO check if we actually need to store the shape data
self._shapes.append((vertices, indices, color1, color2, geo_hash))
self._shape_geo_hash[geo_hash] = shape
gl.glUseProgram(self._shape_shader.id)
# Create VAO, VBO, and EBO
vao = gl.GLuint()
gl.glGenVertexArrays(1, vao)
gl.glBindVertexArray(vao)
vbo = gl.GLuint()
gl.glGenBuffers(1, vbo)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices.ctypes.data, gl.GL_STATIC_DRAW)
vertex_cuda_buffer = wp.RegisteredGLBuffer(int(vbo.value), self._device)
ebo = gl.GLuint()
gl.glGenBuffers(1, ebo)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices.ctypes.data, gl.GL_STATIC_DRAW)
# Set up vertex attributes
vertex_stride = vertices.shape[1] * vertices.itemsize
# positions
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(0)
# normals
gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(3 * vertices.itemsize))
gl.glEnableVertexAttribArray(1)
# uv coordinates
gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, vertex_stride, ctypes.c_void_p(6 * vertices.itemsize))
gl.glEnableVertexAttribArray(2)
gl.glBindVertexArray(0)
self._shape_gl_buffers[shape] = (vao, vbo, ebo, len(indices), vertex_cuda_buffer)
return shape
def add_shape_instance(
self, name: str, shape: int, body, pos, rot, scale=(1.0, 1.0, 1.0), color1=None, color2=None
):
if color1 is None:
color1 = self._shapes[shape][2]
if color2 is None:
color2 = self._shapes[shape][3]
instance = len(self._instances)
self._shape_instances[shape].append(instance)
body = self._resolve_body_id(body)
self._instances[name] = (instance, body, shape, [*pos, *rot], scale, color1, color2)
self._instance_shape[instance] = shape
self._add_shape_instances = True
self._instance_count = len(self._instances)
return instance
def allocate_shape_instances(self):
from pyglet import gl
self._add_shape_instances = False
self._wp_instance_transforms = wp.array(
[instance[3] for instance in self._instances.values()], dtype=wp.transform, device=self._device
)
self._wp_instance_scalings = wp.array(
[instance[4] for instance in self._instances.values()], dtype=wp.vec3, device=self._device
)
self._wp_instance_bodies = wp.array(
[instance[1] for instance in self._instances.values()], dtype=wp.int32, device=self._device
)
gl.glUseProgram(self._shape_shader.id)
if self._instance_transform_gl_buffer is not None:
gl.glDeleteBuffers(1, self._instance_transform_gl_buffer)
gl.glDeleteBuffers(1, self._instance_color1_buffer)
gl.glDeleteBuffers(1, self._instance_color2_buffer)
# Create instance buffer and bind it as an instanced array
self._instance_transform_gl_buffer = gl.GLuint()
gl.glGenBuffers(1, self._instance_transform_gl_buffer)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._instance_transform_gl_buffer)
transforms = np.tile(np.diag(np.ones(4, dtype=np.float32)), (len(self._instances), 1, 1))
gl.glBufferData(gl.GL_ARRAY_BUFFER, transforms.nbytes, transforms.ctypes.data, gl.GL_DYNAMIC_DRAW)
# Create CUDA buffer for instance transforms
self._instance_transform_cuda_buffer = wp.RegisteredGLBuffer(
int(self._instance_transform_gl_buffer.value), self._device
)
colors1, colors2 = [], []
all_instances = list(self._instances.values())
for shape, instances in self._shape_instances.items():
for i in instances:
if i >= len(all_instances):
continue
instance = all_instances[i]
colors1.append(instance[5])
colors2.append(instance[6])
colors1 = np.array(colors1, dtype=np.float32)
colors2 = np.array(colors2, dtype=np.float32)
# create buffer for checkerboard colors
self._instance_color1_buffer = gl.GLuint()
gl.glGenBuffers(1, self._instance_color1_buffer)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._instance_color1_buffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, colors1.nbytes, colors1.ctypes.data, gl.GL_STATIC_DRAW)
self._instance_color2_buffer = gl.GLuint()
gl.glGenBuffers(1, self._instance_color2_buffer)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._instance_color2_buffer)
gl.glBufferData(gl.GL_ARRAY_BUFFER, colors2.nbytes, colors2.ctypes.data, gl.GL_STATIC_DRAW)
# Set up instance attribute pointers
matrix_size = transforms[0].nbytes
instance_ids = []
inverse_instance_ids = {}
instance_count = 0
for shape, (vao, vbo, ebo, tri_count, vertex_cuda_buffer) in self._shape_gl_buffers.items():
gl.glBindVertexArray(vao)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._instance_transform_gl_buffer)
# we can only send vec4s to the shader, so we need to split the instance transforms matrix into its column vectors
for i in range(4):
gl.glVertexAttribPointer(
3 + i, 4, gl.GL_FLOAT, gl.GL_FALSE, matrix_size, ctypes.c_void_p(i * matrix_size // 4)
)
gl.glEnableVertexAttribArray(3 + i)
gl.glVertexAttribDivisor(3 + i, 1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._instance_color1_buffer)
gl.glVertexAttribPointer(7, 3, gl.GL_FLOAT, gl.GL_FALSE, colors1[0].nbytes, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(7)
gl.glVertexAttribDivisor(7, 1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._instance_color2_buffer)
gl.glVertexAttribPointer(8, 3, gl.GL_FLOAT, gl.GL_FALSE, colors2[0].nbytes, ctypes.c_void_p(0))
gl.glEnableVertexAttribArray(8)
gl.glVertexAttribDivisor(8, 1)
instance_ids.extend(self._shape_instances[shape])
for i in self._shape_instances[shape]:
inverse_instance_ids[i] = instance_count
instance_count += 1
# trigger update to the instance transforms
self._update_shape_instances = True
self._wp_instance_ids = wp.array(instance_ids, dtype=wp.int32, device=self._device)
self._instance_ids = instance_ids
self._inverse_instance_ids = inverse_instance_ids
gl.glBindVertexArray(0)
def update_shape_instance(self, name, pos, rot, color1=None, color2=None):
"""Update the instance transform of the shape
Args:
name: The name of the shape
pos: The position of the shape
rot: The rotation of the shape
"""
if name in self._instances:
i, body, shape, _, scale, old_color1, old_color2 = self._instances[name]
self._instances[name] = (i, body, shape, [*pos, *rot], scale, color1 or old_color1, color2 or old_color2)
self._update_shape_instances = True
return True
return False
def update_shape_instances(self):
with self._shape_shader:
self._update_shape_instances = False
self._wp_instance_transforms = wp.array(
[instance[3] for instance in self._instances.values()], dtype=wp.transform, device=self._device
)
self.update_body_transforms(None)
def update_body_transforms(self, body_tf: wp.array):
if self._instance_transform_cuda_buffer is None:
return
body_q = None
if body_tf is not None:
if body_tf.device.is_cuda:
body_q = body_tf
else:
body_q = body_tf.to(self._device)
vbo_transforms = self._instance_transform_cuda_buffer.map(dtype=wp.mat44, shape=(self._instance_count,))
wp.launch(
update_vbo_transforms,
dim=self._instance_count,
inputs=[
self._wp_instance_ids,
self._wp_instance_bodies,
self._wp_instance_transforms,
self._wp_instance_scalings,
body_q,
],
outputs=[
vbo_transforms,
],
device=self._device,
)
self._instance_transform_cuda_buffer.unmap()
def register_body(self, name):
# register body name and return its ID
if name not in self._body_name:
self._body_name[name] = len(self._body_name)
return self._body_name[name]
def _resolve_body_id(self, body):
if body is None:
return -1
if isinstance(body, int):
return body
return self._body_name[body]
def is_running(self):
return not self.app.event_loop.has_exit
def save(self):
# save just keeps the window open to allow the user to interact with the scene
while not self.app.event_loop.has_exit:
self.update()
if self.app.event_loop.has_exit:
self.clear()
self.app.event_loop.exit()
def get_pixels(self, target_image: wp.array, split_up_tiles=True):
from pyglet import gl
if split_up_tiles:
assert (
self._tile_width is not None and self._tile_height is not None
), "Tile width and height are not set, tiles must all have the same size"
assert all(
vp[2] == self._tile_width for vp in self._tile_viewports
), "Tile widths do not all equal global tile_width, use `get_tile_pixels` instead to retrieve pixels for a single tile"
assert all(
vp[3] == self._tile_height for vp in self._tile_viewports
), "Tile heights do not all equal global tile_height, use `get_tile_pixels` instead to retrieve pixels for a single tile"
assert target_image.shape == (
self.num_tiles,
self._tile_height,
self._tile_width,
3,
), f"Shape of `target_image` array does not match {self.num_tiles} x {self.screen_height} x {self.screen_width} x 3"
else:
assert target_image.shape == (
self.screen_height,
self.screen_width,
3,
), f"Shape of `target_image` array does not match {self.screen_height} x {self.screen_width} x 3"
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, self._frame_pbo)
gl.glBindTexture(gl.GL_TEXTURE_2D, self._frame_texture)
try:
# read screen texture into PBO
gl.glGetTexImage(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, ctypes.c_void_p(0))
except gl.GLException:
# this can happen if the window is closed/being moved to a different display
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, 0)
return False
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, 0)
pbo_buffer = wp.RegisteredGLBuffer(
int(self._frame_pbo.value), self._device, wp.RegisteredGLBuffer.WRITE_DISCARD
)
screen_size = self.screen_height * self.screen_width
img = pbo_buffer.map(dtype=wp.uint8, shape=(screen_size * 3))
img = img.to(target_image.device)
if split_up_tiles:
positions = wp.array(self._tile_viewports, ndim=2, dtype=wp.int32, device=target_image.device)
wp.launch(
copy_frame_tiles,
dim=(self.num_tiles, self._tile_width, self._tile_height),
inputs=[img, positions, self.screen_width, self.screen_height, self._tile_height],
outputs=[target_image],
device=target_image.device,
)
else:
wp.launch(
copy_frame,
dim=(self.screen_width, self.screen_height),
inputs=[img, self.screen_width, self.screen_height],
outputs=[target_image],
device=target_image.device,
)
pbo_buffer.unmap()
return True
def get_tile_pixels(self, tile_id: int, target_image: wp.array):
from pyglet import gl
viewport = self._tile_viewports[tile_id]
assert target_image.shape == (
viewport[3],
viewport[2],
3,
), f"Shape of `target_image` array does not match {viewport[3]} x {viewport[2]} x 3"
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, self._frame_pbo)
gl.glBindTexture(gl.GL_TEXTURE_2D, self._frame_texture)
try:
# read screen texture into PBO
gl.glGetTexImage(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, ctypes.c_void_p(0))
except gl.GLException:
# this can happen if the window is closed/being moved to a different display
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, 0)
return False
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
gl.glBindBuffer(gl.GL_PIXEL_PACK_BUFFER, 0)
pbo_buffer = wp.RegisteredGLBuffer(
int(self._frame_pbo.value), self._device, wp.RegisteredGLBuffer.WRITE_DISCARD
)
screen_size = self.screen_height * self.screen_width
img = pbo_buffer.map(dtype=wp.uint8, shape=(screen_size * 3))
img = img.to(target_image.device)
wp.launch(
copy_frame_tiles,
dim=(self.num_tiles, self._tile_width, self._tile_height),
inputs=[img, viewport[0], viewport[1], self.screen_width, self.screen_height, self._tile_height],
outputs=[target_image],
device=target_image.device,
)
pbo_buffer.unmap()
return True
# def create_image_texture(self, file_path):
# from PIL import Image
# img = Image.open(file_path)
# img_data = np.array(list(img.getdata()), np.uint8)
# texture = glGenTextures(1)
# glBindTexture(GL_TEXTURE_2D, texture)
# glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.width, img.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
# return texture
# def create_check_texture(self, color1=(0, 0.5, 1.0), color2=None, width=default_texture_size, height=default_texture_size):
# if width == 1 and height == 1:
# pixels = np.array([np.array(color1)*255], dtype=np.uint8)
# else:
# pixels = np.zeros((width, height, 3), dtype=np.uint8)
# half_w = width // 2
# half_h = height // 2
# color1 = np.array(np.array(color1)*255, dtype=np.uint8)
# pixels[0:half_w, 0:half_h] = color1
# pixels[half_w:width, half_h:height] = color1
# if color2 is None:
# color2 = np.array(np.clip(np.array(color1, dtype=np.float32) + 50, 0, 255), dtype=np.uint8)
# else:
# color2 = np.array(np.array(color2)*255, dtype=np.uint8)
# pixels[half_w:width, 0:half_h] = color2
# pixels[0:half_w, half_h:height] = color2
# texture = glGenTextures(1)
# glBindTexture(GL_TEXTURE_2D, texture)
# glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels.flatten())
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
# glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
# return texture
def render_plane(
self,
name: str,
pos: tuple,
rot: tuple,
width: float,
length: float,
color: tuple = (1.0, 1.0, 1.0),
color2=None,
parent_body: str = None,
is_template: bool = False,
u_scaling=1.0,
v_scaling=1.0,
):
"""Add a plane for visualization
Args:
name: The name of the plane
pos: The position of the plane
rot: The rotation of the plane
width: The width of the plane
length: The length of the plane
color: The color of the plane
texture: The texture of the plane (optional)
"""
geo_hash = hash(("plane", width, length))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
faces = np.array([0, 1, 2, 2, 3, 0], dtype=np.uint32)
normal = (0.0, 1.0, 0.0)
width = width if width > 0.0 else 100.0
length = length if length > 0.0 else 100.0
aspect = width / length
u = width * aspect * u_scaling
v = length * v_scaling
gfx_vertices = np.array(
[
[-width, 0.0, -length, *normal, 0.0, 0.0],
[-width, 0.0, length, *normal, 0.0, v],
[width, 0.0, length, *normal, u, v],
[width, 0.0, -length, *normal, u, 0.0],
],
dtype=np.float32,
)
shape = self.register_shape(geo_hash, gfx_vertices, faces, color1=color, color2=color2)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_ground(self, size: float = 100.0):
"""Add a ground plane for visualization
Args:
size: The size of the ground plane
"""
color1 = (200 / 255, 200 / 255, 200 / 255)
color2 = (150 / 255, 150 / 255, 150 / 255)
sqh = np.sqrt(0.5)
if self._camera_axis == 0:
q = (0.0, 0.0, -sqh, sqh)
elif self._camera_axis == 1:
q = (0.0, 0.0, 0.0, 1.0)
elif self._camera_axis == 2:
q = (sqh, 0.0, 0.0, sqh)
return self.render_plane(
"ground",
(0.0, 0.0, 0.0),
q,
size,
size,
color1,
color2=color2,
u_scaling=1.0,
v_scaling=1.0,
)
def render_sphere(
self, name: str, pos: tuple, rot: tuple, radius: float, parent_body: str = None, is_template: bool = False
):
"""Add a sphere for visualization
Args:
pos: The position of the sphere
radius: The radius of the sphere
name: A name for the USD prim on the stage
"""
geo_hash = hash(("sphere", radius))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
vertices, indices = self._create_sphere_mesh(radius)
shape = self.register_shape(geo_hash, vertices, indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_capsule(
self,
name: str,
pos: tuple,
rot: tuple,
radius: float,
half_height: float,
parent_body: str = None,
is_template: bool = False,
up_axis: int = 1,
):
"""Add a capsule for visualization
Args:
pos: The position of the capsule
radius: The radius of the capsule
half_height: The half height of the capsule
name: A name for the USD prim on the stage
up_axis: The axis of the capsule that points up (0: x, 1: y, 2: z)
"""
geo_hash = hash(("capsule", radius, half_height))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
vertices, indices = self._create_capsule_mesh(radius, half_height, up_axis=up_axis)
shape = self.register_shape(geo_hash, vertices, indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_cylinder(
self,
name: str,
pos: tuple,
rot: tuple,
radius: float,
half_height: float,
parent_body: str = None,
is_template: bool = False,
up_axis: int = 1,
):
"""Add a cylinder for visualization
Args:
pos: The position of the cylinder
radius: The radius of the cylinder
half_height: The half height of the cylinder
name: A name for the USD prim on the stage
up_axis: The axis of the cylinder that points up (0: x, 1: y, 2: z)
"""
geo_hash = hash(("cylinder", radius, half_height))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
vertices, indices = self._create_cylinder_mesh(radius, half_height, up_axis=up_axis)
shape = self.register_shape(geo_hash, vertices, indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_cone(
self,
name: str,
pos: tuple,
rot: tuple,
radius: float,
half_height: float,
parent_body: str = None,
is_template: bool = False,
up_axis: int = 1,
):
"""Add a cone for visualization
Args:
pos: The position of the cone
radius: The radius of the cone
half_height: The half height of the cone
name: A name for the USD prim on the stage
up_axis: The axis of the cone that points up (0: x, 1: y, 2: z)
"""
geo_hash = hash(("cone", radius, half_height))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
vertices, indices = self._create_cone_mesh(radius, half_height, up_axis=up_axis)
shape = self.register_shape(geo_hash, vertices, indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_box(
self, name: str, pos: tuple, rot: tuple, extents: tuple, parent_body: str = None, is_template: bool = False
):
"""Add a box for visualization
Args:
pos: The position of the box
extents: The extents of the box
name: A name for the USD prim on the stage
"""
geo_hash = hash(("box", tuple(extents)))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
vertices, indices = self._create_box_mesh(extents)
shape = self.register_shape(geo_hash, vertices, indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_mesh(
self,
name: str,
points,
indices,
colors=None,
pos=(0.0, 0.0, 0.0),
rot=(0.0, 0.0, 0.0, 1.0),
scale=(1.0, 1.0, 1.0),
update_topology=False,
parent_body: str = None,
is_template: bool = False,
smooth_shading: bool = True,
):
"""Add a mesh for visualization
Args:
points: The points of the mesh
indices: The indices of the mesh
colors: The colors of the mesh
pos: The position of the mesh
rot: The rotation of the mesh
scale: The scale of the mesh
name: A name for the USD prim on the stage
smooth_shading: Whether to average face normals at each vertex or introduce additional vertices for each face
"""
if colors is None:
colors = np.ones((len(points), 3), dtype=np.float32)
else:
colors = np.array(colors, dtype=np.float32)
points = np.array(points, dtype=np.float32) * np.array(scale, dtype=np.float32)
indices = np.array(indices, dtype=np.int32).reshape((-1, 3))
if name in self._instances:
self.update_shape_instance(name, pos, rot)
shape = self._instances[name][2]
self.update_shape_vertices(shape, points)
return
geo_hash = hash((points.tobytes(), indices.tobytes(), colors.tobytes()))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
if smooth_shading:
normals = wp.zeros(len(points), dtype=wp.vec3)
vertices = wp.array(points, dtype=wp.vec3)
faces_per_vertex = wp.zeros(len(points), dtype=int)
wp.launch(
compute_average_normals,
dim=len(indices),
inputs=[wp.array(indices, dtype=int), vertices],
outputs=[normals, faces_per_vertex],
)
gfx_vertices = wp.zeros((len(points), 8), dtype=float)
wp.launch(
assemble_gfx_vertices,
dim=len(points),
inputs=[vertices, normals, faces_per_vertex],
outputs=[gfx_vertices],
)
gfx_vertices = gfx_vertices.numpy()
gfx_indices = indices.flatten()
else:
gfx_vertices = wp.zeros((len(indices) * 3, 8), dtype=float)
wp.launch(
compute_gfx_vertices,
dim=len(indices),
inputs=[wp.array(indices, dtype=int), wp.array(points, dtype=wp.vec3)],
outputs=[gfx_vertices],
)
gfx_vertices = gfx_vertices.numpy()
gfx_indices = np.arange(len(indices) * 3)
shape = self.register_shape(geo_hash, gfx_vertices, gfx_indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot)
return shape
def render_arrow(
self,
name: str,
pos: tuple,
rot: tuple,
base_radius: float,
base_height: float,
cap_radius: float = None,
cap_height: float = None,
parent_body: str = None,
is_template: bool = False,
up_axis: int = 1,
color: Tuple[float, float, float] = None,
):
"""Add a arrow for visualization
Args:
pos: The position of the arrow
base_radius: The radius of the cylindrical base of the arrow
base_height: The height of the cylindrical base of the arrow
cap_radius: The radius of the conical cap of the arrow
cap_height: The height of the conical cap of the arrow
name: A name for the USD prim on the stage
up_axis: The axis of the arrow that points up (0: x, 1: y, 2: z)
"""
geo_hash = hash(("arrow", base_radius, base_height, cap_radius, cap_height))
if geo_hash in self._shape_geo_hash:
shape = self._shape_geo_hash[geo_hash]
if self.update_shape_instance(name, pos, rot):
return shape
else:
vertices, indices = self._create_arrow_mesh(
base_radius, base_height, cap_radius, cap_height, up_axis=up_axis
)
shape = self.register_shape(geo_hash, vertices, indices)
if not is_template:
body = self._resolve_body_id(parent_body)
self.add_shape_instance(name, shape, body, pos, rot, color1=color, color2=color)
return shape
def render_ref(self, name: str, path: str, pos: tuple, rot: tuple, scale: tuple):
"""
Create a reference (instance) with the given name to the given path.
"""
if path in self._instances:
_, body, shape, _, original_scale, color1, color2 = self._instances[path]
self.add_shape_instance(name, shape, body, pos, rot, scale or original_scale, color1, color2)
return
raise Exception("Cannot create reference to path: " + path)
def render_points(self, name: str, points, radius, colors=None):
"""Add a set of points
Args:
points: The points to render
radius: The radius of the points (scalar or list)
colors: The colors of the points
name: A name for the USD prim on the stage
"""
if len(points) == 0:
return
if isinstance(points, wp.array):
wp_points = points
else:
wp_points = wp.array(points, dtype=wp.vec3, device=self._device)
if name not in self._shape_instancers:
np_points = points.numpy() if isinstance(points, wp.array) else points
instancer = ShapeInstancer(self._shape_shader, self._device)
radius_is_scalar = np.isscalar(radius)
if radius_is_scalar:
vertices, indices = self._create_sphere_mesh(radius)
else:
vertices, indices = self._create_sphere_mesh(1.0)
if colors is None:
color = tab10_color_map(len(self._shape_geo_hash))
else:
color = colors[0]
instancer.register_shape(vertices, indices, color, color)
scalings = None if radius_is_scalar else np.tile(radius, (3, 1)).T
instancer.allocate_instances(np_points, colors1=colors, colors2=colors, scalings=scalings)
self._shape_instancers[name] = instancer
else:
instancer = self._shape_instancers[name]
if len(points) != instancer.num_instances:
np_points = points.numpy() if isinstance(points, wp.array) else points
instancer.allocate_instances(np_points)
with instancer:
wp.launch(
update_points_positions,
dim=len(points),
inputs=[wp_points, instancer.instance_scalings],
outputs=[instancer.vbo_transforms],
device=self._device,
)
def _render_lines(self, name: str, lines, color: tuple, radius: float = 0.01):
if len(lines) == 0:
return
if name not in self._shape_instancers:
instancer = ShapeInstancer(self._shape_shader, self._device)
vertices, indices = self._create_capsule_mesh(radius, 0.5)
if color is None or isinstance(color, list):
color = tab10_color_map(len(self._shape_geo_hash))
instancer.register_shape(vertices, indices, color, color)
instancer.allocate_instances(np.zeros((len(lines), 3)))
self._shape_instancers[name] = instancer
else:
instancer = self._shape_instancers[name]
if len(lines) != instancer.num_instances:
instancer.allocate_instances(np.zeros((len(lines), 3)))
lines_wp = wp.array(lines, dtype=wp.vec3, ndim=2, device=self._device)
with instancer:
wp.launch(
update_line_transforms,
dim=len(lines),
inputs=[lines_wp],
outputs=[instancer.vbo_transforms],
device=self._device,
)
def render_line_list(self, name, vertices, indices, color, radius):
"""Add a line list as a set of capsules
Args:
vertices: The vertices of the line-list
indices: The indices of the line-list
color: The color of the line
radius: The radius of the line
"""
lines = []
for i in range(len(indices) // 2):
lines.append((vertices[indices[2 * i]], vertices[indices[2 * i + 1]]))
lines = np.array(lines)
self._render_lines(name, lines, color, radius)
def render_line_strip(self, name: str, vertices, color: tuple, radius: float = 0.01):
"""Add a line strip as a set of capsules
Args:
vertices: The vertices of the line-strip
color: The color of the line
radius: The radius of the line
"""
lines = []
for i in range(len(vertices) - 1):
lines.append((vertices[i], vertices[i + 1]))
lines = np.array(lines)
self._render_lines(name, lines, color, radius)
def update_shape_vertices(self, shape, points):
if isinstance(points, wp.array):
wp_points = points.to(self._device)
else:
wp_points = wp.array(points, dtype=wp.vec3, device=self._device)
cuda_buffer = self._shape_gl_buffers[shape][4]
vertices_shape = self._shapes[shape][0].shape
vbo_vertices = cuda_buffer.map(dtype=wp.float32, shape=vertices_shape)
wp.launch(
update_vbo_vertices,
dim=vertices_shape[0],
inputs=[wp_points],
outputs=[vbo_vertices],
device=self._device,
)
cuda_buffer.unmap()
@staticmethod
def _create_sphere_mesh(radius=1.0, num_latitudes=default_num_segments, num_longitudes=default_num_segments, reverse_winding=False):
vertices = []
indices = []
for i in range(num_latitudes + 1):
theta = i * np.pi / num_latitudes
sin_theta = np.sin(theta)
cos_theta = np.cos(theta)
for j in range(num_longitudes + 1):
phi = j * 2 * np.pi / num_longitudes
sin_phi = np.sin(phi)
cos_phi = np.cos(phi)
x = cos_phi * sin_theta
y = cos_theta
z = sin_phi * sin_theta
u = float(j) / num_longitudes
v = float(i) / num_latitudes
vertices.append([x * radius, y * radius, z * radius, x, y, z, u, v])
for i in range(num_latitudes):
for j in range(num_longitudes):
first = i * (num_longitudes + 1) + j
second = first + num_longitudes + 1
if reverse_winding:
indices.extend([first, second, first + 1, second, second + 1, first + 1])
else:
indices.extend([first, first + 1, second, second, first + 1, second + 1])
return np.array(vertices, dtype=np.float32), np.array(indices, dtype=np.uint32)
@staticmethod
def _create_capsule_mesh(radius, half_height, up_axis=1, segments=default_num_segments):
vertices = []
indices = []
x_dir, y_dir, z_dir = ((1, 2, 0), (2, 0, 1), (0, 1, 2))[up_axis]
up_vector = np.zeros(3)
up_vector[up_axis] = half_height
for i in range(segments + 1):
theta = i * np.pi / segments
sin_theta = np.sin(theta)
cos_theta = np.cos(theta)
for j in range(segments + 1):
phi = j * 2 * np.pi / segments
sin_phi = np.sin(phi)
cos_phi = np.cos(phi)
z = cos_phi * sin_theta
y = cos_theta
x = sin_phi * sin_theta
u = cos_theta * 0.5 + 0.5
v = cos_phi * sin_theta * 0.5 + 0.5
xyz = x, y, z
x, y, z = xyz[x_dir], xyz[y_dir], xyz[z_dir]
xyz = np.array((x, y, z), dtype=np.float32) * radius
if j < segments // 2:
xyz += up_vector
else:
xyz -= up_vector
vertices.append([*xyz, x, y, z, u, v])
nv = len(vertices)
for i in range(segments + 1):
for j in range(segments + 1):
first = (i * (segments + 1) + j) % nv
second = (first + segments + 1) % nv
indices.extend([first, second, (first + 1) % nv, second, (second + 1) % nv, (first + 1) % nv])
vertex_data = np.array(vertices, dtype=np.float32)
index_data = np.array(indices, dtype=np.uint32)
return vertex_data, index_data
@staticmethod
def _create_cone_mesh(radius, half_height, up_axis=1, segments=default_num_segments):
# render it as a cylinder with zero top radius so we get correct normals on the sides
return OpenGLRenderer._create_cylinder_mesh(radius, half_height, up_axis, segments, 0.0)
@staticmethod
def _create_cylinder_mesh(radius, half_height, up_axis=1, segments=default_num_segments, top_radius=None):
if up_axis not in (0, 1, 2):
raise ValueError("up_axis must be between 0 and 2")
x_dir, y_dir, z_dir = (
(1, 2, 0),
(0, 1, 2),
(2, 0, 1),
)[up_axis]
indices = []
cap_vertices = []
side_vertices = []
# create center cap vertices
position = np.array([0, -half_height, 0])[[x_dir, y_dir, z_dir]]
normal = np.array([0, -1, 0])[[x_dir, y_dir, z_dir]]
cap_vertices.append([*position, *normal, 0.5, 0.5])
cap_vertices.append([*-position, *-normal, 0.5, 0.5])
if top_radius is None:
top_radius = radius
side_slope = -np.arctan2(top_radius - radius, 2 * half_height)
# Create the cylinder base and top vertices
for j in (-1, 1):
center_index = max(j, 0)
if j == 1:
radius = top_radius
for i in range(segments):
theta = 2 * np.pi * i / segments
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
x = cos_theta
y = j * half_height
z = sin_theta
position = np.array([radius * x, y, radius * z])
normal = np.array([x, side_slope, z])
normal = normal / np.linalg.norm(normal)
uv = (i / (segments - 1), (j + 1) / 2)
vertex = np.hstack([position[[x_dir, y_dir, z_dir]], normal[[x_dir, y_dir, z_dir]], uv])
side_vertices.append(vertex)
normal = np.array([0, j, 0])
uv = (cos_theta * 0.5 + 0.5, sin_theta * 0.5 + 0.5)
vertex = np.hstack([position[[x_dir, y_dir, z_dir]], normal[[x_dir, y_dir, z_dir]], uv])
cap_vertices.append(vertex)
indices.extend(
[center_index, i + center_index * segments + 2,
(i + 1) % segments + center_index * segments + 2][::-j]
)
# Create the cylinder side indices
for i in range(segments):
index1 = len(cap_vertices) + i + segments
index2 = len(cap_vertices) + ((i + 1) % segments) + segments
index3 = len(cap_vertices) + i
index4 = len(cap_vertices) + ((i + 1) % segments)
indices.extend([index1, index2, index3, index2, index4, index3])
vertex_data = np.array(np.vstack((cap_vertices, side_vertices)), dtype=np.float32)
index_data = np.array(indices, dtype=np.uint32)
return vertex_data, index_data
@staticmethod
def _create_arrow_mesh(
base_radius, base_height, cap_radius=None, cap_height=None, up_axis=1, segments=default_num_segments
):
if up_axis not in (0, 1, 2):
raise ValueError("up_axis must be between 0 and 2")
if cap_radius is None:
cap_radius = base_radius * 1.8
if cap_height is None:
cap_height = base_height * 0.18
up_vector = np.array([0, 0, 0])
up_vector[up_axis] = 1
base_vertices, base_indices = OpenGLRenderer._create_cylinder_mesh(
base_radius, base_height / 2, up_axis, segments
)
cap_vertices, cap_indices = OpenGLRenderer._create_cone_mesh(cap_radius, cap_height / 2, up_axis, segments)
base_vertices[:, :3] += base_height / 2 * up_vector
# move cap slightly lower to avoid z-fighting
cap_vertices[:, :3] += (base_height + cap_height / 2 - 1e-3 * base_height) * up_vector
vertex_data = np.vstack((base_vertices, cap_vertices))
index_data = np.hstack((base_indices, cap_indices + len(base_vertices)))
return vertex_data, index_data
@staticmethod
def _create_box_mesh(extents):
x_extent, y_extent, z_extent = extents
vertices = [
# Position Normal UV
[-x_extent, -y_extent, -z_extent, -1, 0, 0, 0, 0],
[-x_extent, -y_extent, z_extent, -1, 0, 0, 1, 0],
[-x_extent, y_extent, z_extent, -1, 0, 0, 1, 1],
[-x_extent, y_extent, -z_extent, -1, 0, 0, 0, 1],
[x_extent, -y_extent, -z_extent, 1, 0, 0, 0, 0],
[x_extent, -y_extent, z_extent, 1, 0, 0, 1, 0],
[x_extent, y_extent, z_extent, 1, 0, 0, 1, 1],
[x_extent, y_extent, -z_extent, 1, 0, 0, 0, 1],
[-x_extent, -y_extent, -z_extent, 0, -1, 0, 0, 0],
[-x_extent, -y_extent, z_extent, 0, -1, 0, 1, 0],
[x_extent, -y_extent, z_extent, 0, -1, 0, 1, 1],
[x_extent, -y_extent, -z_extent, 0, -1, 0, 0, 1],
[-x_extent, y_extent, -z_extent, 0, 1, 0, 0, 0],
[-x_extent, y_extent, z_extent, 0, 1, 0, 1, 0],
[x_extent, y_extent, z_extent, 0, 1, 0, 1, 1],
[x_extent, y_extent, -z_extent, 0, 1, 0, 0, 1],
[-x_extent, -y_extent, -z_extent, 0, 0, -1, 0, 0],
[-x_extent, y_extent, -z_extent, 0, 0, -1, 1, 0],
[x_extent, y_extent, -z_extent, 0, 0, -1, 1, 1],
[x_extent, -y_extent, -z_extent, 0, 0, -1, 0, 1],
[-x_extent, -y_extent, z_extent, 0, 0, 1, 0, 0],
[-x_extent, y_extent, z_extent, 0, 0, 1, 1, 0],
[x_extent, y_extent, z_extent, 0, 0, 1, 1, 1],
[x_extent, -y_extent, z_extent, 0, 0, 1, 0, 1],
]
# fmt: off
indices = [
0, 1, 2,
0, 2, 3,
4, 6, 5,
4, 7, 6,
8, 10, 9,
8, 11, 10,
12, 13, 14,
12, 14, 15,
16, 17, 18,
16, 18, 19,
20, 22, 21,
20, 23, 22,
]
# fmt: on
return np.array(vertices, dtype=np.float32), np.array(indices, dtype=np.uint32)
if __name__ == "__main__":
wp.init()
renderer = OpenGLRenderer()
| warp-main | warp/render/render_opengl.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 typing import Any
@wp.kernel
def sgd_step_kernel(
g: wp.array(dtype=Any),
b: wp.array(dtype=Any),
lr: float,
weight_decay: float,
momentum: float,
damping: float,
nesterov: int,
t: int,
params: wp.array(dtype=Any),
):
i = wp.tid()
gt = g[i]
if weight_decay != 0.0:
gt += weight_decay * params[i]
if momentum != 0.0:
bt = b[i]
if t > 0:
bt = momentum * bt + (1.0 - damping) * gt
else:
bt = gt
if nesterov == 1:
gt += momentum * bt
else:
gt = bt
b[i] = bt
params[i] = params[i] - lr * gt
class SGD:
"""An implementation of the Stochastic Gradient Descent Optimizer
It is designed to mimic Pytorch's version.
https://pytorch.org/docs/stable/generated/torch.optim.SGD.html
"""
def __init__(self, params=None, lr=0.001, momentum=0.0, dampening=0.0, weight_decay=0.0, nesterov=False):
self.b = [] # momentum buffer
self.set_params(params)
self.lr = lr
self.momentum = momentum
self.dampening = dampening
self.weight_decay = weight_decay
self.nesterov = nesterov
self.t = 0
def set_params(self, params):
self.params = params
if params is not None and type(params) == list and len(params) > 0:
if len(self.b) != len(params):
self.b = [None] * len(params)
for i in range(len(params)):
param = params[i]
if self.b[i] is None or self.b[i].shape != param.shape or self.b[i].dtype != param.dtype:
self.b[i] = wp.zeros_like(param)
def reset_internal_state(self):
for b_i in self.b:
b_i.zero_()
self.t = 0
def step(self, grad):
assert self.params is not None
for i in range(len(self.params)):
SGD.step_detail(
grad[i], self.b[i], self.lr, self.momentum, self.dampening, self.weight_decay, self.nesterov, self.t, self.params[i]
)
self.t = self.t + 1
@staticmethod
def step_detail(g, b, lr, momentum, dampening, weight_decay, nesterov, t, params):
assert params.dtype == g.dtype
assert params.dtype == b.dtype
assert params.shape == g.shape
kernel_inputs = [g, b, lr, momentum, dampening, weight_decay, int(nesterov), t, params]
wp.launch(
kernel=sgd_step_kernel,
dim=len(params),
inputs=kernel_inputs,
device=params.device,
)
| warp-main | warp/optim/sgd.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 .adam import Adam
from .sgd import SGD
| warp-main | warp/optim/__init__.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
@wp.kernel
def adam_step_kernel_vec3(
g: wp.array(dtype=wp.vec3),
m: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
lr: float,
beta1: float,
beta2: float,
t: float,
eps: float,
params: wp.array(dtype=wp.vec3),
):
i = wp.tid()
m[i] = beta1 * m[i] + (1.0 - beta1) * g[i]
v[i] = beta2 * v[i] + (1.0 - beta2) * wp.cw_mul(g[i], g[i])
mhat = m[i] / (1.0 - wp.pow(beta1, (t + 1.0)))
vhat = v[i] / (1.0 - wp.pow(beta2, (t + 1.0)))
sqrt_vhat = wp.vec3(wp.sqrt(vhat[0]), wp.sqrt(vhat[1]), wp.sqrt(vhat[2]))
eps_vec3 = wp.vec3(eps, eps, eps)
params[i] = params[i] - lr * wp.cw_div(mhat, (sqrt_vhat + eps_vec3))
@wp.kernel
def adam_step_kernel_float(
g: wp.array(dtype=float),
m: wp.array(dtype=float),
v: wp.array(dtype=float),
lr: float,
beta1: float,
beta2: float,
t: float,
eps: float,
params: wp.array(dtype=float),
):
i = wp.tid()
m[i] = beta1 * m[i] + (1.0 - beta1) * g[i]
v[i] = beta2 * v[i] + (1.0 - beta2) * g[i] * g[i]
mhat = m[i] / (1.0 - wp.pow(beta1, (t + 1.0)))
vhat = v[i] / (1.0 - wp.pow(beta2, (t + 1.0)))
params[i] = params[i] - lr * mhat / (wp.sqrt(vhat) + eps)
class Adam:
"""An implementation of the Adam Optimizer
It is designed to mimic Pytorch's version.
https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam
"""
def __init__(self, params=None, lr=0.001, betas=(0.9, 0.999), eps=1e-08):
self.m = [] # first moment
self.v = [] # second moment
self.set_params(params)
self.lr = lr
self.beta1 = betas[0]
self.beta2 = betas[1]
self.eps = eps
self.t = 0
def set_params(self, params):
self.params = params
if params != None and type(params) == list and len(params) > 0:
if len(self.m) != len(params):
self.m = [None] * len(params) # reset first moment
if len(self.v) != len(params):
self.v = [None] * len(params) # reset second moment
for i in range(len(params)):
param = params[i]
if self.m[i] == None or self.m[i].shape != param.shape or self.m[i].dtype != param.dtype:
self.m[i] = wp.zeros_like(param)
if self.v[i] == None or self.v[i].shape != param.shape or self.v[i].dtype != param.dtype:
self.v[i] = wp.zeros_like(param)
def reset_internal_state(self):
for m_i in self.m:
m_i.zero_()
for v_i in self.v:
v_i.zero_()
self.t = 0
def step(self, grad):
assert self.params != None
for i in range(len(self.params)):
Adam.step_detail(
grad[i], self.m[i], self.v[i], self.lr, self.beta1, self.beta2, self.t, self.eps, self.params[i]
)
self.t = self.t + 1
@staticmethod
def step_detail(g, m, v, lr, beta1, beta2, t, eps, params):
assert params.dtype == g.dtype
assert params.dtype == m.dtype
assert params.dtype == v.dtype
assert params.shape == g.shape
kernel_inputs = [g, m, v, lr, beta1, beta2, t, eps, params]
if params.dtype == wp.types.float32:
wp.launch(
kernel=adam_step_kernel_float,
dim=len(params),
inputs=kernel_inputs,
device=params.device,
)
elif params.dtype == wp.types.vec3:
wp.launch(
kernel=adam_step_kernel_vec3,
dim=len(params),
inputs=kernel_inputs,
device=params.device,
)
else:
raise RuntimeError("Params data type not supported in Adam step kernels.")
| warp-main | warp/optim/adam.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.
"""This module contains time-integration objects for simulating
models + state forward in time.
"""
import warp as wp
from .collide import triangle_closest_point_barycentric
from .model import PARTICLE_FLAG_ACTIVE, ModelShapeGeometry, ModelShapeMaterials
from .optimizer import Optimizer
from .particles import eval_particle_forces
from .utils import quat_decompose, quat_twist
@wp.kernel
def integrate_particles(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
f: wp.array(dtype=wp.vec3),
w: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
gravity: wp.vec3,
dt: float,
v_max: float,
x_new: wp.array(dtype=wp.vec3),
v_new: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
x0 = x[tid]
v0 = v[tid]
f0 = f[tid]
inv_mass = w[tid]
# simple semi-implicit Euler. v1 = v0 + a dt, x1 = x0 + v1 dt
v1 = v0 + (f0 * inv_mass + gravity * wp.step(0.0 - inv_mass)) * dt
# enforce velocity limit to prevent instability
v1_mag = wp.length(v1)
if v1_mag > v_max:
v1 *= v_max / v1_mag
x1 = x0 + v1 * dt
x_new[tid] = x1
v_new[tid] = v1
# semi-implicit Euler integration
@wp.kernel
def integrate_bodies(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_f: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
m: wp.array(dtype=float),
I: wp.array(dtype=wp.mat33),
inv_m: wp.array(dtype=float),
inv_I: wp.array(dtype=wp.mat33),
gravity: wp.vec3,
angular_damping: float,
dt: float,
# outputs
body_q_new: wp.array(dtype=wp.transform),
body_qd_new: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
# positions
q = body_q[tid]
qd = body_qd[tid]
f = body_f[tid]
# masses
mass = m[tid]
inv_mass = inv_m[tid] # 1 / mass
inertia = I[tid]
inv_inertia = inv_I[tid] # inverse of 3x3 inertia matrix
# unpack transform
x0 = wp.transform_get_translation(q)
r0 = wp.transform_get_rotation(q)
# unpack spatial twist
w0 = wp.spatial_top(qd)
v0 = wp.spatial_bottom(qd)
# unpack spatial wrench
t0 = wp.spatial_top(f)
f0 = wp.spatial_bottom(f)
x_com = x0 + wp.quat_rotate(r0, body_com[tid])
# linear part
v1 = v0 + (f0 * inv_mass + gravity * wp.nonzero(inv_mass)) * dt
x1 = x_com + v1 * dt
# angular part (compute in body frame)
wb = wp.quat_rotate_inv(r0, w0)
tb = wp.quat_rotate_inv(r0, t0) - wp.cross(wb, inertia * wb) # coriolis forces
w1 = wp.quat_rotate(r0, wb + inv_inertia * tb * dt)
r1 = wp.normalize(r0 + wp.quat(w1, 0.0) * r0 * 0.5 * dt)
# angular damping
w1 *= 1.0 - angular_damping * dt
body_q_new[tid] = wp.transform(x1 - wp.quat_rotate(r1, body_com[tid]), r1)
body_qd_new[tid] = wp.spatial_vector(w1, v1)
@wp.kernel
def eval_springs(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
spring_indices: wp.array(dtype=int),
spring_rest_lengths: wp.array(dtype=float),
spring_stiffness: wp.array(dtype=float),
spring_damping: wp.array(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = spring_indices[tid * 2 + 0]
j = spring_indices[tid * 2 + 1]
ke = spring_stiffness[tid]
kd = spring_damping[tid]
rest = spring_rest_lengths[tid]
xi = x[i]
xj = x[j]
vi = v[i]
vj = v[j]
xij = xi - xj
vij = vi - vj
l = wp.length(xij)
l_inv = 1.0 / l
# normalized spring direction
dir = xij * l_inv
c = l - rest
dcdt = wp.dot(dir, vij)
# damping based on relative velocity.
fs = dir * (ke * c + kd * dcdt)
wp.atomic_sub(f, i, fs)
wp.atomic_add(f, j, fs)
@wp.kernel
def eval_triangles(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
pose: wp.array(dtype=wp.mat22),
activation: wp.array(dtype=float),
materials: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
k_mu = materials[tid, 0]
k_lambda = materials[tid, 1]
k_damp = materials[tid, 2]
k_drag = materials[tid, 3]
k_lift = materials[tid, 4]
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
x0 = x[i] # point zero
x1 = x[j] # point one
x2 = x[k] # point two
v0 = v[i] # vel zero
v1 = v[j] # vel one
v2 = v[k] # vel two
x10 = x1 - x0 # barycentric coordinates (centered at p)
x20 = x2 - x0
v10 = v1 - v0
v20 = v2 - v0
Dm = pose[tid]
inv_rest_area = wp.determinant(Dm) * 2.0 # 1 / det(A) = det(A^-1)
rest_area = 1.0 / inv_rest_area
# scale stiffness coefficients to account for area
k_mu = k_mu * rest_area
k_lambda = k_lambda * rest_area
k_damp = k_damp * rest_area
# F = Xs*Xm^-1
F1 = x10 * Dm[0, 0] + x20 * Dm[1, 0]
F2 = x10 * Dm[0, 1] + x20 * Dm[1, 1]
# dFdt = Vs*Xm^-1
dFdt1 = v10 * Dm[0, 0] + v20 * Dm[1, 0]
dFdt2 = v10 * Dm[0, 1] + v20 * Dm[1, 1]
# deviatoric PK1 + damping term
P1 = F1 * k_mu + dFdt1 * k_damp
P2 = F2 * k_mu + dFdt2 * k_damp
# -----------------------------
# St. Venant-Kirchoff
# # Green strain, F'*F-I
# e00 = dot(f1, f1) - 1.0
# e10 = dot(f2, f1)
# e01 = dot(f1, f2)
# e11 = dot(f2, f2) - 1.0
# E = wp.mat22(e00, e01,
# e10, e11)
# # local forces (deviatoric part)
# T = wp.mul(E, wp.transpose(Dm))
# # spatial forces, F*T
# fq = (f1*T[0,0] + f2*T[1,0])*k_mu*2.0
# fr = (f1*T[0,1] + f2*T[1,1])*k_mu*2.0
# alpha = 1.0
# -----------------------------
# Baraff & Witkin, note this model is not isotropic
# c1 = length(f1) - 1.0
# c2 = length(f2) - 1.0
# f1 = normalize(f1)*c1*k1
# f2 = normalize(f2)*c2*k1
# fq = f1*Dm[0,0] + f2*Dm[0,1]
# fr = f1*Dm[1,0] + f2*Dm[1,1]
# -----------------------------
# Neo-Hookean (with rest stability)
# force = P*Dm'
f1 = P1 * Dm[0, 0] + P2 * Dm[0, 1]
f2 = P1 * Dm[1, 0] + P2 * Dm[1, 1]
alpha = 1.0 + k_mu / k_lambda
# -----------------------------
# Area Preservation
n = wp.cross(x10, x20)
area = wp.length(n) * 0.5
# actuation
act = activation[tid]
# J-alpha
c = area * inv_rest_area - alpha + act
# dJdx
n = wp.normalize(n)
dcdq = wp.cross(x20, n) * inv_rest_area * 0.5
dcdr = wp.cross(n, x10) * inv_rest_area * 0.5
f_area = k_lambda * c
# -----------------------------
# Area Damping
dcdt = dot(dcdq, v1) + dot(dcdr, v2) - dot(dcdq + dcdr, v0)
f_damp = k_damp * dcdt
f1 = f1 + dcdq * (f_area + f_damp)
f2 = f2 + dcdr * (f_area + f_damp)
f0 = f1 + f2
# -----------------------------
# Lift + Drag
vmid = (v0 + v1 + v2) * 0.3333
vdir = wp.normalize(vmid)
f_drag = vmid * (k_drag * area * wp.abs(wp.dot(n, vmid)))
f_lift = n * (k_lift * area * (1.57079 - wp.acos(wp.dot(n, vdir)))) * dot(vmid, vmid)
# note reversed sign due to atomic_add below.. need to write the unary op -
f0 = f0 - f_drag - f_lift
f1 = f1 + f_drag + f_lift
f2 = f2 + f_drag + f_lift
# apply forces
wp.atomic_add(f, i, f0)
wp.atomic_sub(f, j, f1)
wp.atomic_sub(f, k, f2)
# @wp.func
# def triangle_closest_point(a: wp.vec3, b: wp.vec3, c: wp.vec3, p: wp.vec3):
# ab = b - a
# ac = c - a
# ap = p - a
# d1 = wp.dot(ab, ap)
# d2 = wp.dot(ac, ap)
# if (d1 <= 0.0 and d2 <= 0.0):
# return a
# bp = p - b
# d3 = wp.dot(ab, bp)
# d4 = wp.dot(ac, bp)
# if (d3 >= 0.0 and d4 <= d3):
# return b
# vc = d1 * d4 - d3 * d2
# v = d1 / (d1 - d3)
# if (vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0):
# return a + ab * v
# cp = p - c
# d5 = dot(ab, cp)
# d6 = dot(ac, cp)
# if (d6 >= 0.0 and d5 <= d6):
# return c
# vb = d5 * d2 - d1 * d6
# w = d2 / (d2 - d6)
# if (vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0):
# return a + ac * w
# va = d3 * d6 - d5 * d4
# w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
# if (va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0):
# return b + (c - b) * w
# denom = 1.0 / (va + vb + vc)
# v = vb * denom
# w = vc * denom
# return a + ab * v + ac * w
@wp.kernel
def eval_triangles_contact(
# idx : wp.array(dtype=int), # list of indices for colliding particles
num_particles: int, # size of particles
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
pose: wp.array(dtype=wp.mat22),
activation: wp.array(dtype=float),
materials: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
face_no = tid // num_particles # which face
particle_no = tid % num_particles # which particle
k_mu = materials[face_no, 0]
k_lambda = materials[face_no, 1]
k_damp = materials[face_no, 2]
k_drag = materials[face_no, 3]
k_lift = materials[face_no, 4]
# at the moment, just one particle
pos = x[particle_no]
i = indices[face_no, 0]
j = indices[face_no, 1]
k = indices[face_no, 2]
if i == particle_no or j == particle_no or k == particle_no:
return
p = x[i] # point zero
q = x[j] # point one
r = x[k] # point two
# vp = v[i] # vel zero
# vq = v[j] # vel one
# vr = v[k] # vel two
# qp = q-p # barycentric coordinates (centered at p)
# rp = r-p
bary = triangle_closest_point_barycentric(p, q, r, pos)
closest = p * bary[0] + q * bary[1] + r * bary[2]
diff = pos - closest
dist = wp.dot(diff, diff)
n = wp.normalize(diff)
c = wp.min(dist - 0.01, 0.0) # 0 unless within 0.01 of surface
# c = wp.leaky_min(dot(n, x0)-0.01, 0.0, 0.0)
fn = n * c * 1e5
wp.atomic_sub(f, particle_no, fn)
# # apply forces (could do - f / 3 here)
wp.atomic_add(f, i, fn * bary[0])
wp.atomic_add(f, j, fn * bary[1])
wp.atomic_add(f, k, fn * bary[2])
@wp.kernel
def eval_triangles_body_contacts(
num_particles: int, # number of particles (size of contact_point)
x: wp.array(dtype=wp.vec3), # position of particles
v: wp.array(dtype=wp.vec3),
indices: wp.array(dtype=int), # triangle indices
body_x: wp.array(dtype=wp.vec3), # body body positions
body_r: wp.array(dtype=wp.quat),
body_v: wp.array(dtype=wp.vec3),
body_w: wp.array(dtype=wp.vec3),
contact_body: wp.array(dtype=int),
contact_point: wp.array(dtype=wp.vec3), # position of contact points relative to body
contact_dist: wp.array(dtype=float),
contact_mat: wp.array(dtype=int),
materials: wp.array(dtype=float),
# body_f : wp.array(dtype=wp.vec3),
# body_t : wp.array(dtype=wp.vec3),
tri_f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
face_no = tid // num_particles # which face
particle_no = tid % num_particles # which particle
# -----------------------
# load body body point
c_body = contact_body[particle_no]
c_point = contact_point[particle_no]
c_dist = contact_dist[particle_no]
c_mat = contact_mat[particle_no]
# hard coded surface parameter tensor layout (ke, kd, kf, mu)
ke = materials[c_mat * 4 + 0] # restitution coefficient
kd = materials[c_mat * 4 + 1] # damping coefficient
kf = materials[c_mat * 4 + 2] # friction coefficient
mu = materials[c_mat * 4 + 3] # coulomb friction
x0 = body_x[c_body] # position of colliding body
r0 = body_r[c_body] # orientation of colliding body
v0 = body_v[c_body]
w0 = body_w[c_body]
# transform point to world space
pos = x0 + wp.quat_rotate(r0, c_point)
# use x0 as center, everything is offset from center of mass
# moment arm
r = pos - x0 # basically just c_point in the new coordinates
rhat = wp.normalize(r)
pos = pos + rhat * c_dist # add on 'thickness' of shape, e.g.: radius of sphere/capsule
# contact point velocity
dpdt = v0 + wp.cross(w0, r) # this is body velocity cross offset, so it's the velocity of the contact point.
# -----------------------
# load triangle
i = indices[face_no * 3 + 0]
j = indices[face_no * 3 + 1]
k = indices[face_no * 3 + 2]
p = x[i] # point zero
q = x[j] # point one
r = x[k] # point two
vp = v[i] # vel zero
vq = v[j] # vel one
vr = v[k] # vel two
bary = triangle_closest_point_barycentric(p, q, r, pos)
closest = p * bary[0] + q * bary[1] + r * bary[2]
diff = pos - closest # vector from tri to point
dist = wp.dot(diff, diff) # squared distance
n = wp.normalize(diff) # points into the object
c = wp.min(dist - 0.05, 0.0) # 0 unless within 0.05 of surface
# c = wp.leaky_min(dot(n, x0)-0.01, 0.0, 0.0)
# fn = n * c * 1e6 # points towards cloth (both n and c are negative)
# wp.atomic_sub(tri_f, particle_no, fn)
fn = c * ke # normal force (restitution coefficient * how far inside for ground) (negative)
vtri = vp * bary[0] + vq * bary[1] + vr * bary[2] # bad approximation for centroid velocity
vrel = vtri - dpdt
vn = dot(n, vrel) # velocity component of body in negative normal direction
vt = vrel - n * vn # velocity component not in normal direction
# contact damping
fd = 0.0 - wp.max(vn, 0.0) * kd * wp.step(c) # again, negative, into the ground
# # viscous friction
# ft = vt*kf
# Coulomb friction (box)
lower = mu * (fn + fd)
upper = 0.0 - lower # workaround because no unary ops yet
nx = cross(n, vec3(0.0, 0.0, 1.0)) # basis vectors for tangent
nz = cross(n, vec3(1.0, 0.0, 0.0))
vx = wp.clamp(dot(nx * kf, vt), lower, upper)
vz = wp.clamp(dot(nz * kf, vt), lower, upper)
ft = (nx * vx + nz * vz) * (0.0 - wp.step(c)) # wp.vec3(vx, 0.0, vz)*wp.step(c)
# # Coulomb friction (smooth, but gradients are numerically unstable around |vt| = 0)
# #ft = wp.normalize(vt)*wp.min(kf*wp.length(vt), 0.0 - mu*c*ke)
f_total = n * (fn + fd) + ft
wp.atomic_add(tri_f, i, f_total * bary[0])
wp.atomic_add(tri_f, j, f_total * bary[1])
wp.atomic_add(tri_f, k, f_total * bary[2])
@wp.kernel
def eval_bending(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
rest: wp.array(dtype=float),
bending_properties: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
ke = bending_properties[tid, 0]
kd = bending_properties[tid, 1]
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
rest_angle = rest[tid]
x1 = x[i]
x2 = x[j]
x3 = x[k]
x4 = x[l]
v1 = v[i]
v2 = v[j]
v3 = v[k]
v4 = v[l]
n1 = wp.cross(x3 - x1, x4 - x1) # normal to face 1
n2 = wp.cross(x4 - x2, x3 - x2) # normal to face 2
n1_length = wp.length(n1)
n2_length = wp.length(n2)
if n1_length < 1.0e-6 or n2_length < 1.0e-6:
return
rcp_n1 = 1.0 / n1_length
rcp_n2 = 1.0 / n2_length
cos_theta = wp.dot(n1, n2) * rcp_n1 * rcp_n2
n1 = n1 * rcp_n1 * rcp_n1
n2 = n2 * rcp_n2 * rcp_n2
e = x4 - x3
e_hat = wp.normalize(e)
e_length = wp.length(e)
s = wp.sign(wp.dot(wp.cross(n2, n1), e_hat))
angle = wp.acos(cos_theta) * s
d1 = n1 * e_length
d2 = n2 * e_length
d3 = n1 * wp.dot(x1 - x4, e_hat) + n2 * wp.dot(x2 - x4, e_hat)
d4 = n1 * wp.dot(x3 - x1, e_hat) + n2 * wp.dot(x3 - x2, e_hat)
# elastic
f_elastic = ke * (angle - rest_angle)
# damping
f_damp = kd * (wp.dot(d1, v1) + wp.dot(d2, v2) + wp.dot(d3, v3) + wp.dot(d4, v4))
# total force, proportional to edge length
f_total = 0.0 - e_length * (f_elastic + f_damp)
wp.atomic_add(f, i, d1 * f_total)
wp.atomic_add(f, j, d2 * f_total)
wp.atomic_add(f, k, d3 * f_total)
wp.atomic_add(f, l, d4 * f_total)
@wp.kernel
def eval_tetrahedra(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
pose: wp.array(dtype=wp.mat33),
activation: wp.array(dtype=float),
materials: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
act = activation[tid]
k_mu = materials[tid, 0]
k_lambda = materials[tid, 1]
k_damp = materials[tid, 2]
x0 = x[i]
x1 = x[j]
x2 = x[k]
x3 = x[l]
v0 = v[i]
v1 = v[j]
v2 = v[k]
v3 = v[l]
x10 = x1 - x0
x20 = x2 - x0
x30 = x3 - x0
v10 = v1 - v0
v20 = v2 - v0
v30 = v3 - v0
Ds = wp.mat33(x10, x20, x30)
Dm = pose[tid]
inv_rest_volume = wp.determinant(Dm) * 6.0
rest_volume = 1.0 / inv_rest_volume
alpha = 1.0 + k_mu / k_lambda - k_mu / (4.0 * k_lambda)
# scale stiffness coefficients to account for area
k_mu = k_mu * rest_volume
k_lambda = k_lambda * rest_volume
k_damp = k_damp * rest_volume
# F = Xs*Xm^-1
F = Ds * Dm
dFdt = wp.mat33(v10, v20, v30) * Dm
col1 = wp.vec3(F[0, 0], F[1, 0], F[2, 0])
col2 = wp.vec3(F[0, 1], F[1, 1], F[2, 1])
col3 = wp.vec3(F[0, 2], F[1, 2], F[2, 2])
# -----------------------------
# Neo-Hookean (with rest stability [Smith et al 2018])
Ic = dot(col1, col1) + dot(col2, col2) + dot(col3, col3)
# deviatoric part
P = F * k_mu * (1.0 - 1.0 / (Ic + 1.0)) + dFdt * k_damp
H = P * wp.transpose(Dm)
f1 = wp.vec3(H[0, 0], H[1, 0], H[2, 0])
f2 = wp.vec3(H[0, 1], H[1, 1], H[2, 1])
f3 = wp.vec3(H[0, 2], H[1, 2], H[2, 2])
# -----------------------------
# C_sqrt
# alpha = 1.0
# r_s = wp.sqrt(wp.abs(dot(col1, col1) + dot(col2, col2) + dot(col3, col3) - 3.0))
# f1 = wp.vec3()
# f2 = wp.vec3()
# f3 = wp.vec3()
# if (r_s > 0.0):
# r_s_inv = 1.0/r_s
# C = r_s
# dCdx = F*wp.transpose(Dm)*r_s_inv*wp.sign(r_s)
# grad1 = vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# f1 = grad1*C*k_mu
# f2 = grad2*C*k_mu
# f3 = grad3*C*k_mu
# -----------------------------
# C_spherical
# alpha = 1.0
# r_s = wp.sqrt(dot(col1, col1) + dot(col2, col2) + dot(col3, col3))
# r_s_inv = 1.0/r_s
# C = r_s - wp.sqrt(3.0)
# dCdx = F*wp.transpose(Dm)*r_s_inv
# grad1 = vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# f1 = grad1*C*k_mu
# f2 = grad2*C*k_mu
# f3 = grad3*C*k_mu
# ----------------------------
# C_D
# alpha = 1.0
# r_s = wp.sqrt(dot(col1, col1) + dot(col2, col2) + dot(col3, col3))
# C = r_s*r_s - 3.0
# dCdx = F*wp.transpose(Dm)*2.0
# grad1 = vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# f1 = grad1*C*k_mu
# f2 = grad2*C*k_mu
# f3 = grad3*C*k_mu
# ----------------------------
# Hookean
# alpha = 1.0
# I = wp.mat33(wp.vec3(1.0, 0.0, 0.0),
# wp.vec3(0.0, 1.0, 0.0),
# wp.vec3(0.0, 0.0, 1.0))
# P = (F + wp.transpose(F) + I*(0.0-2.0))*k_mu
# H = P * wp.transpose(Dm)
# f1 = wp.vec3(H[0, 0], H[1, 0], H[2, 0])
# f2 = wp.vec3(H[0, 1], H[1, 1], H[2, 1])
# f3 = wp.vec3(H[0, 2], H[1, 2], H[2, 2])
# hydrostatic part
J = wp.determinant(F)
# print(J)
s = inv_rest_volume / 6.0
dJdx1 = wp.cross(x20, x30) * s
dJdx2 = wp.cross(x30, x10) * s
dJdx3 = wp.cross(x10, x20) * s
f_volume = (J - alpha + act) * k_lambda
f_damp = (wp.dot(dJdx1, v1) + wp.dot(dJdx2, v2) + wp.dot(dJdx3, v3)) * k_damp
f_total = f_volume + f_damp
f1 = f1 + dJdx1 * f_total
f2 = f2 + dJdx2 * f_total
f3 = f3 + dJdx3 * f_total
f0 = (f1 + f2 + f3) * (0.0 - 1.0)
# apply forces
wp.atomic_sub(f, i, f0)
wp.atomic_sub(f, j, f1)
wp.atomic_sub(f, k, f2)
wp.atomic_sub(f, l, f3)
@wp.kernel
def eval_particle_ground_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
ke: float,
kd: float,
kf: float,
mu: float,
ground: wp.array(dtype=float),
# outputs
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
x = particle_x[tid]
v = particle_v[tid]
radius = particle_radius[tid]
n = wp.vec3(ground[0], ground[1], ground[2])
c = wp.min(wp.dot(n, x) + ground[3] - radius, 0.0)
vn = wp.dot(n, v)
jn = c * ke
if c >= 0.0:
return
jd = min(vn, 0.0) * kd
# contact force
fn = jn + jd
# friction force
vt = v - n * vn
vs = wp.length(vt)
if vs > 0.0:
vt = vt / vs
# Coulomb condition
ft = wp.min(vs * kf, mu * wp.abs(fn))
# total force
f[tid] = f[tid] - n * fn - vt * ft
@wp.kernel
def eval_particle_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_com: wp.array(dtype=wp.vec3),
shape_body: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
particle_ke: float,
particle_kd: float,
particle_kf: float,
particle_mu: float,
particle_ka: float,
contact_count: wp.array(dtype=int),
contact_particle: wp.array(dtype=int),
contact_shape: wp.array(dtype=int),
contact_body_pos: wp.array(dtype=wp.vec3),
contact_body_vel: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_max: int,
# outputs
particle_f: wp.array(dtype=wp.vec3),
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
count = min(contact_max, contact_count[0])
if tid >= count:
return
shape_index = contact_shape[tid]
body_index = shape_body[shape_index]
particle_index = contact_particle[tid]
if (particle_flags[particle_index] & PARTICLE_FLAG_ACTIVE) == 0:
return
px = particle_x[particle_index]
pv = particle_v[particle_index]
X_wb = wp.transform_identity()
X_com = wp.vec3()
body_v_s = wp.spatial_vector()
if body_index >= 0:
X_wb = body_q[body_index]
X_com = body_com[body_index]
body_v_s = body_qd[body_index]
# body position in world space
bx = wp.transform_point(X_wb, contact_body_pos[tid])
r = bx - wp.transform_point(X_wb, X_com)
n = contact_normal[tid]
c = wp.dot(n, px - bx) - particle_radius[tid]
if c > particle_ka:
return
# take average material properties of shape and particle parameters
ke = 0.5 * (particle_ke + shape_materials.ke[shape_index])
kd = 0.5 * (particle_kd + shape_materials.kd[shape_index])
kf = 0.5 * (particle_kf + shape_materials.kf[shape_index])
mu = 0.5 * (particle_mu + shape_materials.mu[shape_index])
body_w = wp.spatial_top(body_v_s)
body_v = wp.spatial_bottom(body_v_s)
# compute the body velocity at the particle position
bv = body_v + wp.cross(body_w, r) + wp.transform_vector(X_wb, contact_body_vel[tid])
# relative velocity
v = pv - bv
# decompose relative velocity
vn = wp.dot(n, v)
vt = v - n * vn
# contact elastic
fn = n * c * ke
# contact damping
fd = n * wp.min(vn, 0.0) * kd
# viscous friction
# ft = vt*kf
# Coulomb friction (box)
# lower = mu * c * ke
# upper = 0.0 - lower
# vx = wp.clamp(wp.dot(wp.vec3(kf, 0.0, 0.0), vt), lower, upper)
# vz = wp.clamp(wp.dot(wp.vec3(0.0, 0.0, kf), vt), lower, upper)
# ft = wp.vec3(vx, 0.0, vz)
# Coulomb friction (smooth, but gradients are numerically unstable around |vt| = 0)
ft = wp.normalize(vt) * wp.min(kf * wp.length(vt), abs(mu * c * ke))
f_total = fn + (fd + ft)
t_total = wp.cross(r, f_total)
wp.atomic_sub(particle_f, particle_index, f_total)
if body_index >= 0:
wp.atomic_add(body_f, body_index, wp.spatial_vector(t_total, f_total))
@wp.kernel
def eval_rigid_contacts(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
shape_materials: ModelShapeMaterials,
geo: ModelShapeGeometry,
contact_count: wp.array(dtype=int),
contact_body0: wp.array(dtype=int),
contact_body1: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
# outputs
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
if contact_shape0[tid] == contact_shape1[tid]:
return
count = contact_count[0]
if tid >= count:
return
# retrieve contact thickness, compute average contact material properties
ke = 0.0 # restitution coefficient
kd = 0.0 # damping coefficient
kf = 0.0 # friction coefficient
mu = 0.0 # coulomb friction
mat_nonzero = 0
thickness_a = 0.0
thickness_b = 0.0
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a >= 0:
mat_nonzero += 1
ke += shape_materials.ke[shape_a]
kd += shape_materials.kd[shape_a]
kf += shape_materials.kf[shape_a]
mu += shape_materials.mu[shape_a]
thickness_a = geo.thickness[shape_a]
if shape_b >= 0:
mat_nonzero += 1
ke += shape_materials.ke[shape_b]
kd += shape_materials.kd[shape_b]
kf += shape_materials.kf[shape_b]
mu += shape_materials.mu[shape_b]
thickness_b = geo.thickness[shape_b]
if mat_nonzero > 0:
ke = ke / float(mat_nonzero)
kd = kd / float(mat_nonzero)
kf = kf / float(mat_nonzero)
mu = mu / float(mat_nonzero)
body_a = contact_body0[tid]
body_b = contact_body1[tid]
# body position in world space
n = contact_normal[tid]
bx_a = contact_point0[tid]
bx_b = contact_point1[tid]
if body_a >= 0:
X_wb_a = body_q[body_a]
X_com_a = body_com[body_a]
bx_a = wp.transform_point(X_wb_a, bx_a) - thickness_a * n
r_a = bx_a - wp.transform_point(X_wb_a, X_com_a)
if body_b >= 0:
X_wb_b = body_q[body_b]
X_com_b = body_com[body_b]
bx_b = wp.transform_point(X_wb_b, bx_b) + thickness_b * n
r_b = bx_b - wp.transform_point(X_wb_b, X_com_b)
d = wp.dot(n, bx_a - bx_b)
if d >= 0.0:
return
# compute contact point velocity
bv_a = wp.vec3(0.0)
bv_b = wp.vec3(0.0)
if body_a >= 0:
body_v_s_a = body_qd[body_a]
body_w_a = wp.spatial_top(body_v_s_a)
body_v_a = wp.spatial_bottom(body_v_s_a)
bv_a = body_v_a + wp.cross(body_w_a, r_a)
if body_b >= 0:
body_v_s_b = body_qd[body_b]
body_w_b = wp.spatial_top(body_v_s_b)
body_v_b = wp.spatial_bottom(body_v_s_b)
bv_b = body_v_b + wp.cross(body_w_b, r_b)
# relative velocity
v = bv_a - bv_b
# print(v)
# decompose relative velocity
vn = wp.dot(n, v)
vt = v - n * vn
# contact elastic
fn = d * ke
# contact damping
fd = wp.min(vn, 0.0) * kd * wp.step(d)
# viscous friction
# ft = vt*kf
# Coulomb friction (box)
# lower = mu * d * ke
# upper = 0.0 - lower
# vx = wp.clamp(wp.dot(wp.vec3(kf, 0.0, 0.0), vt), lower, upper)
# vz = wp.clamp(wp.dot(wp.vec3(0.0, 0.0, kf), vt), lower, upper)
# ft = wp.vec3(vx, 0.0, vz)
# Coulomb friction (smooth, but gradients are numerically unstable around |vt| = 0)
# ft = wp.normalize(vt)*wp.min(kf*wp.length(vt), abs(mu*d*ke))
ft = wp.normalize(vt) * wp.min(kf * wp.length(vt), 0.0 - mu * (fn + fd))
# f_total = fn + (fd + ft)
f_total = n * (fn + fd) + ft
# t_total = wp.cross(r, f_total)
# print("apply contact force")
# print(f_total)
if body_a >= 0:
wp.atomic_sub(body_f, body_a, wp.spatial_vector(wp.cross(r_a, f_total), f_total))
if body_b >= 0:
wp.atomic_add(body_f, body_b, wp.spatial_vector(wp.cross(r_b, f_total), f_total))
@wp.func
def eval_joint_force(
q: float,
qd: float,
target: float,
target_ke: float,
target_kd: float,
act: float,
limit_lower: float,
limit_upper: float,
limit_ke: float,
limit_kd: float,
axis: wp.vec3,
):
limit_f = 0.0
# compute limit forces, damping only active when limit is violated
if q < limit_lower:
limit_f = limit_ke * (limit_lower - q) - limit_kd * min(qd, 0.0)
if q > limit_upper:
limit_f = limit_ke * (limit_upper - q) - limit_kd * max(qd, 0.0)
# joint dynamics
total_f = (target_ke * (q - target) + target_kd * qd + act - limit_f) * axis
return total_f
@wp.kernel
def eval_body_joints(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_enabled: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_target: wp.array(dtype=float),
joint_act: wp.array(dtype=float),
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
joint_limit_ke: wp.array(dtype=float),
joint_limit_kd: wp.array(dtype=float),
joint_attach_ke: float,
joint_attach_kd: float,
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
# early out for free joints
if joint_enabled[tid] == 0 or type == wp.sim.JOINT_FREE:
return
c_child = joint_child[tid]
c_parent = joint_parent[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
r_p = wp.vec3()
w_p = wp.vec3()
v_p = wp.vec3()
# parent transform and moment arm
if c_parent >= 0:
X_wp = body_q[c_parent] * X_wp
r_p = wp.transform_get_translation(X_wp) - wp.transform_point(body_q[c_parent], body_com[c_parent])
twist_p = body_qd[c_parent]
w_p = wp.spatial_top(twist_p)
v_p = wp.spatial_bottom(twist_p) + wp.cross(w_p, r_p)
# child transform and moment arm
X_wc = body_q[c_child] * X_cj
r_c = wp.transform_get_translation(X_wc) - wp.transform_point(body_q[c_child], body_com[c_child])
twist_c = body_qd[c_child]
w_c = wp.spatial_top(twist_c)
v_c = wp.spatial_bottom(twist_c) + wp.cross(w_c, r_c)
# joint properties (for 1D joints)
q_start = joint_q_start[tid]
qd_start = joint_qd_start[tid]
axis_start = joint_axis_start[tid]
target = joint_target[axis_start]
target_ke = joint_target_ke[axis_start]
target_kd = joint_target_kd[axis_start]
limit_ke = joint_limit_ke[axis_start]
limit_kd = joint_limit_kd[axis_start]
limit_lower = joint_limit_lower[axis_start]
limit_upper = joint_limit_upper[axis_start]
act = joint_act[qd_start]
x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
# translational error
x_err = x_c - x_p
r_err = wp.quat_inverse(q_p) * q_c
v_err = v_c - v_p
w_err = w_c - w_p
# total force/torque on the parent
t_total = wp.vec3()
f_total = wp.vec3()
# reduce angular damping stiffness for stability
angular_damping_scale = 0.01
if type == wp.sim.JOINT_FIXED:
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
t_total += (
wp.transform_vector(X_wp, ang_err) * joint_attach_ke + w_err * joint_attach_kd * angular_damping_scale
)
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
# world space joint axis
axis_p = wp.transform_vector(X_wp, axis)
# evaluate joint coordinates
q = wp.dot(x_err, axis_p)
qd = wp.dot(v_err, axis_p)
f_total = eval_joint_force(
q, qd, target, target_ke, target_kd, act, limit_lower, limit_upper, limit_ke, limit_kd, axis_p
)
# attachment dynamics
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
# project off any displacement along the joint axis
f_total += (x_err - q * axis_p) * joint_attach_ke + (v_err - qd * axis_p) * joint_attach_kd
t_total += (
wp.transform_vector(X_wp, ang_err) * joint_attach_ke + w_err * joint_attach_kd * angular_damping_scale
)
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
axis_p = wp.transform_vector(X_wp, axis)
axis_c = wp.transform_vector(X_wc, axis)
# swing twist decomposition
twist = quat_twist(axis, r_err)
q = wp.acos(twist[3]) * 2.0 * wp.sign(wp.dot(axis, wp.vec3(twist[0], twist[1], twist[2])))
qd = wp.dot(w_err, axis_p)
t_total = eval_joint_force(
q, qd, target, target_ke, target_kd, act, limit_lower, limit_upper, limit_ke, limit_kd, axis_p
)
# attachment dynamics
swing_err = wp.cross(axis_p, axis_c)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
t_total += swing_err * joint_attach_ke + (w_err - qd * axis_p) * joint_attach_kd * angular_damping_scale
if type == wp.sim.JOINT_BALL:
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
# todo: joint limits
t_total += target_kd * w_err + target_ke * wp.transform_vector(X_wp, ang_err)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
if type == wp.sim.JOINT_COMPOUND:
q_pc = wp.quat_inverse(q_p) * q_c
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# reconstruct rotation axes
axis_0 = wp.vec3(1.0, 0.0, 0.0)
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, wp.vec3(0.0, 0.0, 1.0))
q_2 = wp.quat_from_axis_angle(axis_2, angles[2])
q_w = q_p
axis_0 = wp.transform_vector(X_wp, axis_0)
axis_1 = wp.transform_vector(X_wp, axis_1)
axis_2 = wp.transform_vector(X_wp, axis_2)
# joint dynamics
t_total = wp.vec3()
# # TODO remove wp.quat_rotate(q_w, ...)?
# t_total += eval_joint_force(angles[0], wp.dot(wp.quat_rotate(q_w, axis_0), w_err), joint_target[axis_start+0], joint_target_ke[axis_start+0],joint_target_kd[axis_start+0], joint_act[axis_start+0], joint_limit_lower[axis_start+0], joint_limit_upper[axis_start+0], joint_limit_ke[axis_start+0], joint_limit_kd[axis_start+0], wp.quat_rotate(q_w, axis_0))
# t_total += eval_joint_force(angles[1], wp.dot(wp.quat_rotate(q_w, axis_1), w_err), joint_target[axis_start+1], joint_target_ke[axis_start+1],joint_target_kd[axis_start+1], joint_act[axis_start+1], joint_limit_lower[axis_start+1], joint_limit_upper[axis_start+1], joint_limit_ke[axis_start+1], joint_limit_kd[axis_start+1], wp.quat_rotate(q_w, axis_1))
# t_total += eval_joint_force(angles[2], wp.dot(wp.quat_rotate(q_w, axis_2), w_err), joint_target[axis_start+2], joint_target_ke[axis_start+2],joint_target_kd[axis_start+2], joint_act[axis_start+2], joint_limit_lower[axis_start+2], joint_limit_upper[axis_start+2], joint_limit_ke[axis_start+2], joint_limit_kd[axis_start+2], wp.quat_rotate(q_w, axis_2))
t_total += eval_joint_force(
angles[0],
wp.dot(axis_0, w_err),
joint_target[axis_start + 0],
joint_target_ke[axis_start + 0],
joint_target_kd[axis_start + 0],
joint_act[axis_start + 0],
joint_limit_lower[axis_start + 0],
joint_limit_upper[axis_start + 0],
joint_limit_ke[axis_start + 0],
joint_limit_kd[axis_start + 0],
axis_0,
)
t_total += eval_joint_force(
angles[1],
wp.dot(axis_1, w_err),
joint_target[axis_start + 1],
joint_target_ke[axis_start + 1],
joint_target_kd[axis_start + 1],
joint_act[axis_start + 1],
joint_limit_lower[axis_start + 1],
joint_limit_upper[axis_start + 1],
joint_limit_ke[axis_start + 1],
joint_limit_kd[axis_start + 1],
axis_1,
)
t_total += eval_joint_force(
angles[2],
wp.dot(axis_2, w_err),
joint_target[axis_start + 2],
joint_target_ke[axis_start + 2],
joint_target_kd[axis_start + 2],
joint_act[axis_start + 2],
joint_limit_lower[axis_start + 2],
joint_limit_upper[axis_start + 2],
joint_limit_ke[axis_start + 2],
joint_limit_kd[axis_start + 2],
axis_2,
)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
if type == wp.sim.JOINT_UNIVERSAL:
q_pc = wp.quat_inverse(q_p) * q_c
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# reconstruct rotation axes
axis_0 = wp.vec3(1.0, 0.0, 0.0)
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, wp.vec3(0.0, 0.0, 1.0))
q_2 = wp.quat_from_axis_angle(axis_2, angles[2])
q_w = q_p
axis_0 = wp.transform_vector(X_wp, axis_0)
axis_1 = wp.transform_vector(X_wp, axis_1)
axis_2 = wp.transform_vector(X_wp, axis_2)
# joint dynamics
t_total = wp.vec3()
# free axes
# # TODO remove wp.quat_rotate(q_w, ...)?
# t_total += eval_joint_force(angles[0], wp.dot(wp.quat_rotate(q_w, axis_0), w_err), joint_target[axis_start+0], joint_target_ke[axis_start+0],joint_target_kd[axis_start+0], joint_act[axis_start+0], joint_limit_lower[axis_start+0], joint_limit_upper[axis_start+0], joint_limit_ke[axis_start+0], joint_limit_kd[axis_start+0], wp.quat_rotate(q_w, axis_0))
# t_total += eval_joint_force(angles[1], wp.dot(wp.quat_rotate(q_w, axis_1), w_err), joint_target[axis_start+1], joint_target_ke[axis_start+1],joint_target_kd[axis_start+1], joint_act[axis_start+1], joint_limit_lower[axis_start+1], joint_limit_upper[axis_start+1], joint_limit_ke[axis_start+1], joint_limit_kd[axis_start+1], wp.quat_rotate(q_w, axis_1))
# # last axis (fixed)
# t_total += eval_joint_force(angles[2], wp.dot(wp.quat_rotate(q_w, axis_2), w_err), 0.0, joint_attach_ke, joint_attach_kd*angular_damping_scale, 0.0, 0.0, 0.0, 0.0, 0.0, wp.quat_rotate(q_w, axis_2))
# TODO remove wp.quat_rotate(q_w, ...)?
t_total += eval_joint_force(
angles[0],
wp.dot(axis_0, w_err),
joint_target[axis_start + 0],
joint_target_ke[axis_start + 0],
joint_target_kd[axis_start + 0],
joint_act[axis_start + 0],
joint_limit_lower[axis_start + 0],
joint_limit_upper[axis_start + 0],
joint_limit_ke[axis_start + 0],
joint_limit_kd[axis_start + 0],
axis_0,
)
t_total += eval_joint_force(
angles[1],
wp.dot(axis_1, w_err),
joint_target[axis_start + 1],
joint_target_ke[axis_start + 1],
joint_target_kd[axis_start + 1],
joint_act[axis_start + 1],
joint_limit_lower[axis_start + 1],
joint_limit_upper[axis_start + 1],
joint_limit_ke[axis_start + 1],
joint_limit_kd[axis_start + 1],
axis_1,
)
# last axis (fixed)
t_total += eval_joint_force(
angles[2],
wp.dot(axis_2, w_err),
0.0,
joint_attach_ke,
joint_attach_kd * angular_damping_scale,
0.0,
0.0,
0.0,
0.0,
0.0,
axis_2,
)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
# write forces
if c_parent >= 0:
wp.atomic_add(body_f, c_parent, wp.spatial_vector(t_total + wp.cross(r_p, f_total), f_total))
wp.atomic_sub(body_f, c_child, wp.spatial_vector(t_total + wp.cross(r_c, f_total), f_total))
@wp.func
def compute_muscle_force(
i: int,
body_X_s: wp.array(dtype=wp.transform),
body_v_s: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
muscle_links: wp.array(dtype=int),
muscle_points: wp.array(dtype=wp.vec3),
muscle_activation: float,
body_f_s: wp.array(dtype=wp.spatial_vector),
):
link_0 = muscle_links[i]
link_1 = muscle_links[i + 1]
if link_0 == link_1:
return 0
r_0 = muscle_points[i]
r_1 = muscle_points[i + 1]
xform_0 = body_X_s[link_0]
xform_1 = body_X_s[link_1]
pos_0 = wp.transform_point(xform_0, r_0 - body_com[link_0])
pos_1 = wp.transform_point(xform_1, r_1 - body_com[link_1])
n = wp.normalize(pos_1 - pos_0)
# todo: add passive elastic and viscosity terms
f = n * muscle_activation
wp.atomic_sub(body_f_s, link_0, wp.spatial_vector(f, wp.cross(pos_0, f)))
wp.atomic_add(body_f_s, link_1, wp.spatial_vector(f, wp.cross(pos_1, f)))
return 0
@wp.kernel
def eval_muscles(
body_X_s: wp.array(dtype=wp.transform),
body_v_s: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
muscle_start: wp.array(dtype=int),
muscle_params: wp.array(dtype=float),
muscle_links: wp.array(dtype=int),
muscle_points: wp.array(dtype=wp.vec3),
muscle_activation: wp.array(dtype=float),
# output
body_f_s: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
m_start = muscle_start[tid]
m_end = muscle_start[tid + 1] - 1
activation = muscle_activation[tid]
for i in range(m_start, m_end):
compute_muscle_force(i, body_X_s, body_v_s, body_com, muscle_links, muscle_points, activation, body_f_s)
def compute_forces(model, state, particle_f, body_f, requires_grad):
# damped springs
if model.spring_count:
wp.launch(
kernel=eval_springs,
dim=model.spring_count,
inputs=[
state.particle_q,
state.particle_qd,
model.spring_indices,
model.spring_rest_length,
model.spring_stiffness,
model.spring_damping,
],
outputs=[particle_f],
device=model.device,
)
# particle-particle interactions
if model.particle_count:
eval_particle_forces(model, state, particle_f)
# triangle elastic and lift/drag forces
if model.tri_count:
wp.launch(
kernel=eval_triangles,
dim=model.tri_count,
inputs=[
state.particle_q,
state.particle_qd,
model.tri_indices,
model.tri_poses,
model.tri_activations,
model.tri_materials,
],
outputs=[particle_f],
device=model.device,
)
# triangle/triangle contacts
if model.enable_tri_collisions and model.tri_count:
wp.launch(
kernel=eval_triangles_contact,
dim=model.tri_count * model.particle_count,
inputs=[
model.particle_count,
state.particle_q,
state.particle_qd,
model.tri_indices,
model.tri_poses,
model.tri_activations,
model.tri_materials,
],
outputs=[particle_f],
device=model.device,
)
# triangle bending
if model.edge_count:
wp.launch(
kernel=eval_bending,
dim=model.edge_count,
inputs=[
state.particle_q,
state.particle_qd,
model.edge_indices,
model.edge_rest_angle,
model.edge_bending_properties,
],
outputs=[particle_f],
device=model.device,
)
# particle ground contact
if model.ground and model.particle_count:
wp.launch(
kernel=eval_particle_ground_contacts,
dim=model.particle_count,
inputs=[
state.particle_q,
state.particle_qd,
model.particle_radius,
model.particle_flags,
model.soft_contact_ke,
model.soft_contact_kd,
model.soft_contact_kf,
model.soft_contact_mu,
model.ground_plane,
],
outputs=[particle_f],
device=model.device,
)
# tetrahedral FEM
if model.tet_count:
wp.launch(
kernel=eval_tetrahedra,
dim=model.tet_count,
inputs=[
state.particle_q,
state.particle_qd,
model.tet_indices,
model.tet_poses,
model.tet_activations,
model.tet_materials,
],
outputs=[particle_f],
device=model.device,
)
if model.rigid_contact_max and (
model.ground and model.shape_ground_contact_pair_count or model.shape_contact_pair_count
):
wp.launch(
kernel=eval_rigid_contacts,
dim=model.rigid_contact_max,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.shape_materials,
model.shape_geo,
model.rigid_contact_count,
model.rigid_contact_body0,
model.rigid_contact_body1,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_normal,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
],
outputs=[body_f],
device=model.device,
)
if model.joint_count:
wp.launch(
kernel=eval_body_joints,
dim=model.joint_count,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.joint_q_start,
model.joint_qd_start,
model.joint_type,
model.joint_enabled,
model.joint_child,
model.joint_parent,
model.joint_X_p,
model.joint_X_c,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_target,
model.joint_act,
model.joint_target_ke,
model.joint_target_kd,
model.joint_limit_lower,
model.joint_limit_upper,
model.joint_limit_ke,
model.joint_limit_kd,
model.joint_attach_ke,
model.joint_attach_kd,
],
outputs=[body_f],
device=model.device,
)
# particle shape contact
if model.particle_count and model.shape_count > 1:
wp.launch(
kernel=eval_particle_contacts,
dim=model.soft_contact_max,
inputs=[
state.particle_q,
state.particle_qd,
state.body_q,
state.body_qd,
model.particle_radius,
model.particle_flags,
model.body_com,
model.shape_body,
model.shape_materials,
model.soft_contact_ke,
model.soft_contact_kd,
model.soft_contact_kf,
model.soft_contact_mu,
model.particle_adhesion,
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
model.soft_contact_max,
],
# outputs
outputs=[particle_f, body_f],
device=model.device,
)
# evaluate muscle actuation
if False and model.muscle_count:
wp.launch(
kernel=eval_muscles,
dim=model.muscle_count,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.muscle_start,
model.muscle_params,
model.muscle_bodies,
model.muscle_points,
model.muscle_activation,
],
outputs=[body_f],
device=model.device,
)
# if (model.articulation_count):
# # evaluate joint torques
# wp.launch(
# kernel=eval_body_tau,
# dim=model.articulation_count,
# inputs=[
# model.articulation_joint_start,
# model.joint_type,
# model.joint_parent,
# model.joint_q_start,
# model.joint_qd_start,
# state.joint_q,
# state.joint_qd,
# state.joint_act,
# model.joint_target,
# model.joint_target_ke,
# model.joint_target_kd,
# model.joint_limit_lower,
# model.joint_limit_upper,
# model.joint_limit_ke,
# model.joint_limit_kd,
# model.joint_axis,
# state.joint_S_s,
# state.body_f_s
# ],
# outputs=[
# state.body_ft_s,
# state.joint_tau
# ],
# device=model.device,
# preserve_output=True)
state.particle_f = particle_f
state.body_f = body_f
class SemiImplicitIntegrator:
"""A semi-implicit integrator using symplectic Euler
After constructing `Model` and `State` objects this time-integrator
may be used to advance the simulation state forward in time.
Semi-implicit time integration is a variational integrator that
preserves energy, however it not unconditionally stable, and requires a time-step
small enough to support the required stiffness and damping forces.
See: https://en.wikipedia.org/wiki/Semi-implicit_Euler_method
Example
-------
.. code-block:: python
integrator = wp.SemiImplicitIntegrator()
# simulation loop
for i in range(100):
state = integrator.simulate(model, state_in, state_out, dt)
"""
def __init__(self, angular_damping=0.05):
self.angular_damping = angular_damping
def simulate(self, model, state_in, state_out, dt, requires_grad=False):
with wp.ScopedTimer("simulate", False):
particle_f = None
body_f = None
if state_in.particle_count:
particle_f = state_in.particle_f
if state_in.body_count:
body_f = state_in.body_f
compute_forces(model, state_in, particle_f, body_f, requires_grad=requires_grad)
# -------------------------------------
# integrate bodies
if model.body_count:
wp.launch(
kernel=integrate_bodies,
dim=model.body_count,
inputs=[
state_in.body_q,
state_in.body_qd,
state_in.body_f,
model.body_com,
model.body_mass,
model.body_inertia,
model.body_inv_mass,
model.body_inv_inertia,
model.gravity,
self.angular_damping,
dt,
],
outputs=[state_out.body_q, state_out.body_qd],
device=model.device,
)
# ----------------------------
# integrate particles
if model.particle_count:
wp.launch(
kernel=integrate_particles,
dim=model.particle_count,
inputs=[
state_in.particle_q,
state_in.particle_qd,
state_in.particle_f,
model.particle_inv_mass,
model.particle_flags,
model.gravity,
dt,
model.particle_max_velocity,
],
outputs=[state_out.particle_q, state_out.particle_qd],
device=model.device,
)
return state_out
@wp.kernel
def compute_particle_residual(
particle_qd_0: wp.array(dtype=wp.vec3),
particle_qd_1: wp.array(dtype=wp.vec3),
particle_f: wp.array(dtype=wp.vec3),
particle_m: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
gravity: wp.vec3,
dt: float,
residual: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
m = particle_m[tid]
v1 = particle_qd_1[tid]
v0 = particle_qd_0[tid]
f = particle_f[tid]
err = wp.vec3()
if m > 0.0:
err = (v1 - v0) * m - f * dt - gravity * dt * m
residual[tid] = err
@wp.kernel
def update_particle_position(
particle_q_0: wp.array(dtype=wp.vec3),
particle_q_1: wp.array(dtype=wp.vec3),
particle_qd_1: wp.array(dtype=wp.vec3),
x: wp.array(dtype=wp.vec3),
particle_flags: wp.array(dtype=wp.uint32),
dt: float,
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
qd_1 = x[tid]
q_0 = particle_q_0[tid]
q_1 = q_0 + qd_1 * dt
particle_q_1[tid] = q_1
particle_qd_1[tid] = qd_1
def compute_residual(model, state_in, state_out, particle_f, residual, dt):
wp.launch(
kernel=compute_particle_residual,
dim=model.particle_count,
inputs=[
state_in.particle_qd,
state_out.particle_qd,
particle_f,
model.particle_mass,
model.particle_flags,
model.gravity,
dt,
residual.astype(dtype=wp.vec3),
],
device=model.device,
)
def init_state(model, state_in, state_out, dt):
wp.launch(
kernel=integrate_particles,
dim=model.particle_count,
inputs=[
state_in.particle_q,
state_in.particle_qd,
state_in.particle_f,
model.particle_inv_mass,
model.particle_flags,
model.gravity,
dt,
model.particle_max_velocity,
],
outputs=[state_out.particle_q, state_out.particle_qd],
device=model.device,
)
# compute the final positions given output velocity (x)
def update_state(model, state_in, state_out, x, dt):
wp.launch(
kernel=update_particle_position,
dim=model.particle_count,
inputs=[state_in.particle_q, state_out.particle_q, state_out.particle_qd, x, model.particle_flags, dt],
device=model.device,
)
class VariationalImplicitIntegrator:
def __init__(self, model, solver="gd", alpha=0.1, max_iters=32, report=False):
self.solver = solver
self.alpha = alpha
self.max_iters = max_iters
self.report = report
self.opt = Optimizer(model.particle_count * 3, mode=self.solver, device=model.device)
# allocate temporary space for evaluating particle forces
self.particle_f = wp.zeros(model.particle_count, dtype=wp.vec3, device=model.device)
def simulate(self, model, state_in, state_out, dt, requires_grad=False):
if state_in is state_out:
raise RuntimeError("Implicit integrators require state objects to not alias each other")
with wp.ScopedTimer("simulate", False):
# alloc particle force buffer
if model.particle_count:
def residual_func(x, dfdx):
self.particle_f.zero_()
update_state(model, state_in, state_out, x.astype(wp.vec3), dt)
compute_forces(model, state_out, self.particle_f, None)
compute_residual(model, state_in, state_out, self.particle_f, dfdx, dt)
# initialize output state using the input velocity to create 'predicted state'
init_state(model, state_in, state_out, dt)
# our optimization variable
x = state_out.particle_qd.astype(dtype=float)
self.opt.solve(
x=x, grad_func=residual_func, max_iters=self.max_iters, alpha=self.alpha, report=self.report
)
# final update to output state with solved velocity
update_state(model, state_in, state_out, x.astype(wp.vec3), dt)
return state_out
| warp-main | warp/sim/integrator_euler.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 os
import re
import xml.etree.ElementTree as ET
import numpy as np
import warp as wp
def parse_mjcf(
mjcf_filename,
builder,
xform=wp.transform(),
density=1000.0,
stiffness=0.0,
damping=0.0,
contact_ke=1000.0,
contact_kd=100.0,
contact_kf=100.0,
contact_mu=0.5,
contact_restitution=0.5,
limit_ke=100.0,
limit_kd=10.0,
scale=1.0,
armature=0.0,
armature_scale=1.0,
parse_meshes=True,
enable_self_collisions=False,
up_axis="Z",
ignore_classes=[],
collapse_fixed_joints=False,
):
"""
Parses MuJoCo XML (MJCF) file and adds the bodies and joints to the given ModelBuilder.
Args:
mjcf_filename (str): The filename of the MuJoCo file to parse.
builder (ModelBuilder): The :class:`ModelBuilder` to add the bodies and joints to.
xform (wp.transform): The transform to apply to the imported mechanism.
density (float): The density of the shapes in kg/m^3 which will be used to calculate the body mass and inertia.
stiffness (float): The stiffness of the joints.
damping (float): The damping of the joints.
contact_ke (float): The stiffness of the shape contacts (used by SemiImplicitIntegrator).
contact_kd (float): The damping of the shape contacts (used by SemiImplicitIntegrator).
contact_kf (float): The friction stiffness of the shape contacts (used by SemiImplicitIntegrator).
contact_mu (float): The friction coefficient of the shape contacts.
contact_restitution (float): The restitution coefficient of the shape contacts.
limit_ke (float): The stiffness of the joint limits (used by SemiImplicitIntegrator).
limit_kd (float): The damping of the joint limits (used by SemiImplicitIntegrator).
scale (float): The scaling factor to apply to the imported mechanism.
armature (float): Default joint armature to use if `armature` has not been defined for a joint in the MJCF.
armature_scale (float): Scaling factor to apply to the MJCF-defined joint armature values.
parse_meshes (bool): Whether geometries of type `"mesh"` should be parsed. If False, geometries of type `"mesh"` are ignored.
enable_self_collisions (bool): If True, self-collisions are enabled.
up_axis (str): The up axis of the mechanism. Can be either `"X"`, `"Y"` or `"Z"`. The default is `"Z"`.
ignore_classes (List[str]): A list of regular expressions. Bodies and joints with a class matching one of the regular expressions will be ignored.
collapse_fixed_joints (bool): If True, fixed joints are removed and the respective bodies are merged.
Note:
The inertia and masses of the bodies are calculated from the shape geometry and the given density. The values defined in the MJCF are not respected at the moment.
The handling of advanced features, such as MJCF classes, is still experimental.
"""
mjcf_dirname = os.path.dirname(mjcf_filename)
file = ET.parse(mjcf_filename)
root = file.getroot()
use_degrees = True # angles are in degrees by default
euler_seq = [1, 2, 3] # XYZ by default
compiler = root.find("compiler")
if compiler is not None:
use_degrees = compiler.attrib.get("angle", "degree").lower() == "degree"
euler_seq = ["xyz".index(c) + 1 for c in compiler.attrib.get("eulerseq", "xyz").lower()]
mesh_dir = compiler.attrib.get("meshdir", ".")
mesh_assets = {}
for asset in root.findall("asset"):
for mesh in asset.findall("mesh"):
if "file" in mesh.attrib:
fname = os.path.join(mesh_dir, mesh.attrib["file"])
# handle stl relative paths
if not os.path.isabs(fname):
fname = os.path.abspath(os.path.join(mjcf_dirname, fname))
if "name" in mesh.attrib:
mesh_assets[mesh.attrib["name"]] = fname
else:
name = ".".join(os.path.basename(fname).split(".")[:-1])
mesh_assets[name] = fname
class_parent = {}
class_children = {}
class_defaults = {"__all__": {}}
def get_class(element):
return element.get("class", "__all__")
def parse_default(node, parent):
nonlocal class_parent
nonlocal class_children
nonlocal class_defaults
class_name = "__all__"
if "class" in node.attrib:
class_name = node.attrib["class"]
class_parent[class_name] = parent
parent = parent or "__all__"
if parent not in class_children:
class_children[parent] = []
class_children[parent].append(class_name)
if class_name not in class_defaults:
class_defaults[class_name] = {}
for child in node:
if child.tag == "default":
parse_default(child, node.get("class"))
else:
class_defaults[class_name][child.tag] = child.attrib
for default in root.findall("default"):
parse_default(default, None)
def merge_attrib(default_attrib: dict, incoming_attrib: dict):
attrib = default_attrib.copy()
attrib.update(incoming_attrib)
return attrib
if isinstance(up_axis, str):
up_axis = "XYZ".index(up_axis.upper())
sqh = np.sqrt(0.5)
if up_axis == 0:
xform = wp.transform(xform.p, wp.quat(0.0, 0.0, -sqh, sqh) * xform.q)
elif up_axis == 2:
xform = wp.transform(xform.p, wp.quat(sqh, 0.0, 0.0, -sqh) * xform.q)
# do not apply scaling to the root transform
xform = wp.transform(np.array(xform.p) / scale, xform.q)
def parse_float(attrib, key, default):
if key in attrib:
return float(attrib[key])
else:
return default
def parse_vec(attrib, key, default):
if key in attrib:
return np.fromstring(attrib[key], sep=" ")
else:
return np.array(default)
def parse_orientation(attrib):
if "quat" in attrib:
wxyz = np.fromstring(attrib["quat"], sep=" ")
return wp.normalize(wp.quat(*wxyz[1:], wxyz[0]))
if "euler" in attrib:
euler = np.fromstring(attrib["euler"], sep=" ")
if use_degrees:
euler *= np.pi / 180
return wp.quat_from_euler(euler, *euler_seq)
if "axisangle" in attrib:
axisangle = np.fromstring(attrib["axisangle"], sep=" ")
angle = axisangle[3]
if use_degrees:
angle *= np.pi / 180
axis = wp.normalize(wp.vec3(*axisangle[:3]))
return wp.quat_from_axis_angle(axis, angle)
if "xyaxes" in attrib:
xyaxes = np.fromstring(attrib["xyaxes"], sep=" ")
xaxis = wp.normalize(wp.vec3(*xyaxes[:3]))
zaxis = wp.normalize(wp.vec3(*xyaxes[3:]))
yaxis = wp.normalize(wp.cross(zaxis, xaxis))
rot_matrix = np.array([xaxis, yaxis, zaxis]).T
return wp.quat_from_matrix(rot_matrix)
if "zaxis" in attrib:
zaxis = np.fromstring(attrib["zaxis"], sep=" ")
zaxis = wp.normalize(wp.vec3(*zaxis))
xaxis = wp.normalize(wp.cross(wp.vec3(0, 0, 1), zaxis))
yaxis = wp.normalize(wp.cross(zaxis, xaxis))
rot_matrix = np.array([xaxis, yaxis, zaxis]).T
return wp.quat_from_matrix(rot_matrix)
return wp.quat_identity()
def parse_mesh(geom):
import trimesh
faces = []
vertices = []
stl_file = mesh_assets[geom["mesh"]]
m = trimesh.load(stl_file)
for v in m.vertices:
vertices.append(np.array(v) * scale)
for f in m.faces:
faces.append(int(f[0]))
faces.append(int(f[1]))
faces.append(int(f[2]))
return wp.sim.Mesh(vertices, faces), m.scale
def parse_body(body, parent, incoming_defaults: dict):
body_class = body.get("childclass")
if body_class is None:
defaults = incoming_defaults
else:
for pattern in ignore_classes:
if re.match(pattern, body_class):
return
defaults = merge_attrib(incoming_defaults, class_defaults[body_class])
if "body" in defaults:
body_attrib = merge_attrib(defaults["body"], body.attrib)
else:
body_attrib = body.attrib
body_name = body_attrib["name"]
body_pos = parse_vec(body_attrib, "pos", (0.0, 0.0, 0.0))
body_ori = parse_orientation(body_attrib)
if parent == -1:
body_pos = wp.transform_point(xform, body_pos)
body_ori = xform.q * body_ori
body_pos *= scale
joint_armature = []
joint_name = []
joint_pos = []
linear_axes = []
angular_axes = []
joint_type = None
joints = body.findall("joint")
for i, joint in enumerate(joints):
if "joint" in defaults:
joint_attrib = merge_attrib(defaults["joint"], joint.attrib)
else:
joint_attrib = joint.attrib
# default to hinge if not specified
joint_type_str = joint_attrib.get("type", "hinge")
joint_name.append(joint_attrib["name"])
joint_pos.append(parse_vec(joint_attrib, "pos", (0.0, 0.0, 0.0)) * scale)
joint_range = parse_vec(joint_attrib, "range", (-3.0, 3.0))
joint_armature.append(parse_float(joint_attrib, "armature", armature) * armature_scale)
if joint_type_str == "free":
joint_type = wp.sim.JOINT_FREE
break
if joint_type_str == "fixed":
joint_type = wp.sim.JOINT_FIXED
break
is_angular = joint_type_str == "hinge"
mode = wp.sim.JOINT_MODE_LIMIT
if stiffness > 0.0 or "stiffness" in joint_attrib:
mode = wp.sim.JOINT_MODE_TARGET_POSITION
axis_vec = parse_vec(joint_attrib, "axis", (0.0, 0.0, 0.0))
ax = wp.sim.model.JointAxis(
axis=axis_vec,
limit_lower=(np.deg2rad(joint_range[0]) if is_angular and use_degrees else joint_range[0]),
limit_upper=(np.deg2rad(joint_range[1]) if is_angular and use_degrees else joint_range[1]),
target_ke=parse_float(joint_attrib, "stiffness", stiffness),
target_kd=parse_float(joint_attrib, "damping", damping),
limit_ke=limit_ke,
limit_kd=limit_kd,
mode=mode,
)
if is_angular:
angular_axes.append(ax)
else:
linear_axes.append(ax)
link = builder.add_body(
origin=wp.transform(body_pos, body_ori), # will be evaluated in fk()
armature=joint_armature[0] if len(joint_armature) > 0 else armature,
name=body_name,
)
if joint_type is None:
if len(linear_axes) == 0:
if len(angular_axes) == 0:
joint_type = wp.sim.JOINT_FIXED
elif len(angular_axes) == 1:
joint_type = wp.sim.JOINT_REVOLUTE
elif len(angular_axes) == 2:
joint_type = wp.sim.JOINT_UNIVERSAL
elif len(angular_axes) == 3:
joint_type = wp.sim.JOINT_COMPOUND
elif len(linear_axes) == 1 and len(angular_axes) == 0:
joint_type = wp.sim.JOINT_PRISMATIC
else:
joint_type = wp.sim.JOINT_D6
joint_pos = joint_pos[0] if len(joint_pos) > 0 else (0.0, 0.0, 0.0)
builder.add_joint(
joint_type,
parent,
link,
linear_axes,
angular_axes,
name="_".join(joint_name),
parent_xform=wp.transform(body_pos + joint_pos, body_ori),
child_xform=wp.transform(joint_pos, wp.quat_identity()),
)
# -----------------
# add shapes
for geo_count, geom in enumerate(body.findall("geom")):
geom_defaults = defaults
if "class" in geom.attrib:
geom_class = geom.attrib["class"]
ignore_geom = False
for pattern in ignore_classes:
if re.match(pattern, geom_class):
ignore_geom = True
break
if ignore_geom:
continue
if geom_class in class_defaults:
geom_defaults = merge_attrib(defaults, class_defaults[geom_class])
if "geom" in geom_defaults:
geom_attrib = merge_attrib(geom_defaults["geom"], geom.attrib)
else:
geom_attrib = geom.attrib
geom_name = geom_attrib.get("name", f"{body_name}_geom_{geo_count}")
geom_type = geom_attrib.get("type", "sphere")
if "mesh" in geom_attrib:
geom_type = "mesh"
geom_size = parse_vec(geom_attrib, "size", [1.0, 1.0, 1.0]) * scale
geom_pos = parse_vec(geom_attrib, "pos", (0.0, 0.0, 0.0)) * scale
geom_rot = parse_orientation(geom_attrib)
geom_density = parse_float(geom_attrib, "density", density)
if geom_type == "sphere":
builder.add_shape_sphere(
link,
pos=geom_pos,
rot=geom_rot,
radius=geom_size[0],
density=geom_density,
ke=contact_ke,
kd=contact_kd,
kf=contact_kf,
mu=contact_mu,
restitution=contact_restitution,
)
elif geom_type == "box":
builder.add_shape_box(
link,
pos=geom_pos,
rot=geom_rot,
hx=geom_size[0],
hy=geom_size[1],
hz=geom_size[2],
density=geom_density,
ke=contact_ke,
kd=contact_kd,
kf=contact_kf,
mu=contact_mu,
restitution=contact_restitution,
)
elif geom_type == "mesh" and parse_meshes:
mesh, _ = parse_mesh(geom_attrib)
if "mesh" in defaults:
mesh_scale = parse_vec(defaults["mesh"], "scale", [1.0, 1.0, 1.0])
else:
mesh_scale = [1.0, 1.0, 1.0]
# as per the Mujoco XML reference, ignore geom size attribute
assert len(geom_size) == 3, "need to specify size for mesh geom"
builder.add_shape_mesh(
body=link,
pos=geom_pos,
rot=geom_rot,
mesh=mesh,
scale=mesh_scale,
density=density,
ke=contact_ke,
kd=contact_kd,
kf=contact_kf,
mu=contact_mu,
)
elif geom_type in {"capsule", "cylinder"}:
if "fromto" in geom_attrib:
geom_fromto = parse_vec(geom_attrib, "fromto", (0.0, 0.0, 0.0, 1.0, 0.0, 0.0))
start = geom_fromto[0:3] * scale
end = geom_fromto[3:6] * scale
# compute rotation to align the Warp capsule (along x-axis), with mjcf fromto direction
axis = wp.normalize(end - start)
angle = math.acos(np.dot(axis, (0.0, 1.0, 0.0)))
axis = wp.normalize(np.cross(axis, (0.0, 1.0, 0.0)))
geom_pos = (start + end) * 0.5
geom_rot = wp.quat_from_axis_angle(axis, -angle)
geom_radius = geom_size[0]
geom_height = np.linalg.norm(end - start) * 0.5
geom_up_axis = 1
else:
geom_radius = geom_size[0]
geom_height = geom_size[1]
geom_up_axis = up_axis
if geom_type == "cylinder":
builder.add_shape_cylinder(
link,
pos=geom_pos,
rot=geom_rot,
radius=geom_radius,
half_height=geom_height,
density=density,
ke=contact_ke,
kd=contact_kd,
kf=contact_kf,
mu=contact_mu,
restitution=contact_restitution,
up_axis=geom_up_axis,
)
else:
builder.add_shape_capsule(
link,
pos=geom_pos,
rot=geom_rot,
radius=geom_radius,
half_height=geom_height,
density=density,
ke=contact_ke,
kd=contact_kd,
kf=contact_kf,
mu=contact_mu,
restitution=contact_restitution,
up_axis=geom_up_axis,
)
else:
print(f"MJCF parsing shape {geom_name} issue: geom type {geom_type} is unsupported")
# -----------------
# recurse
for child in body.findall("body"):
parse_body(child, link, defaults)
# -----------------
# start articulation
start_shape_count = len(builder.shape_geo_type)
builder.add_articulation()
world = root.find("worldbody")
world_class = get_class(world)
world_defaults = merge_attrib(class_defaults["__all__"], class_defaults.get(world_class, {}))
for body in world.findall("body"):
parse_body(body, -1, world_defaults)
end_shape_count = len(builder.shape_geo_type)
if not enable_self_collisions:
for i in range(start_shape_count, end_shape_count):
for j in range(i + 1, end_shape_count):
builder.shape_collision_filter_pairs.add((i, j))
if collapse_fixed_joints:
builder.collapse_fixed_joints()
| warp-main | warp/sim/import_mjcf.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
import warp.sim
import warp.render
from collections import defaultdict
import numpy as np
from warp.render.utils import solidify_mesh, tab10_color_map
# TODO allow NaNs in Warp kernels
NAN = wp.constant(-1.0e8)
@wp.kernel
def compute_contact_points(
body_q: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
# outputs
contact_pos0: wp.array(dtype=wp.vec3),
contact_pos1: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a == shape_b:
contact_pos0[tid] = wp.vec3(NAN, NAN, NAN)
contact_pos1[tid] = wp.vec3(NAN, NAN, NAN)
return
body_a = shape_body[shape_a]
body_b = shape_body[shape_b]
X_wb_a = wp.transform_identity()
X_wb_b = wp.transform_identity()
if body_a >= 0:
X_wb_a = body_q[body_a]
if body_b >= 0:
X_wb_b = body_q[body_b]
contact_pos0[tid] = wp.transform_point(X_wb_a, contact_point0[tid])
contact_pos1[tid] = wp.transform_point(X_wb_b, contact_point1[tid])
def CreateSimRenderer(renderer):
class SimRenderer(renderer):
use_unique_colors = True
def __init__(
self,
model: warp.sim.Model,
path,
scaling=1.0,
fps=60,
up_axis="Y",
show_rigid_contact_points=False,
contact_points_radius=1e-3,
show_joints=False,
**render_kwargs,
):
# create USD stage
super().__init__(path, scaling=scaling, fps=fps, up_axis=up_axis, **render_kwargs)
self.scaling = scaling
self.cam_axis = "XYZ".index(up_axis.upper())
self.show_rigid_contact_points = show_rigid_contact_points
self.show_joints = show_joints
self.contact_points_radius = contact_points_radius
self.populate(model)
def populate(self, model: warp.sim.Model):
self.skip_rendering = False
self.model = model
self.num_envs = model.num_envs
self.body_names = []
if self.show_rigid_contact_points and model.rigid_contact_max:
self.contact_points0 = wp.array(
np.zeros((model.rigid_contact_max, 3)), dtype=wp.vec3, device=model.device
)
self.contact_points1 = wp.array(
np.zeros((model.rigid_contact_max, 3)), dtype=wp.vec3, device=model.device
)
self.contact_points0_colors = [(1.0, 0.5, 0.0)] * model.rigid_contact_max
self.contact_points1_colors = [(0.0, 0.5, 1.0)] * model.rigid_contact_max
self.body_env = [] # mapping from body index to its environment index
env_id = 0
self.bodies_per_env = model.body_count // self.num_envs
# create rigid body nodes
for b in range(model.body_count):
body_name = f"body_{b}_{self.model.body_name[b].replace(' ', '_')}"
self.body_names.append(body_name)
self.register_body(body_name)
if b > 0 and b % self.bodies_per_env == 0:
env_id += 1
self.body_env.append(env_id)
# create rigid shape children
if self.model.shape_count:
# mapping from hash of geometry to shape ID
self.geo_shape = {}
self.instance_count = 0
self.body_name = {} # mapping from body name to its body ID
self.body_shapes = defaultdict(list) # mapping from body index to its shape IDs
shape_body = model.shape_body.numpy()
shape_geo_src = model.shape_geo_src
shape_geo_type = model.shape_geo.type.numpy()
shape_geo_scale = model.shape_geo.scale.numpy()
shape_geo_thickness = model.shape_geo.thickness.numpy()
shape_geo_is_solid = model.shape_geo.is_solid.numpy()
shape_transform = model.shape_transform.numpy()
p = np.zeros(3, dtype=np.float32)
q = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32)
scale = np.ones(3)
color = np.ones(3)
# loop over shapes excluding the ground plane
for s in range(model.shape_count - 1):
geo_type = shape_geo_type[s]
geo_scale = [float(v) for v in shape_geo_scale[s]]
geo_thickness = float(shape_geo_thickness[s])
geo_is_solid = bool(shape_geo_is_solid[s])
geo_src = shape_geo_src[s]
if self.use_unique_colors:
color = self._get_new_color()
name = f"shape_{s}"
# shape transform in body frame
body = int(shape_body[s])
if body >= 0 and body < len(self.body_names):
body = self.body_names[body]
else:
body = None
# shape transform in body frame
X_bs = wp.transform_expand(shape_transform[s])
# check whether we can instance an already created shape with the same geometry
geo_hash = hash((int(geo_type), geo_src, *geo_scale, geo_thickness, geo_is_solid))
if geo_hash in self.geo_shape:
shape = self.geo_shape[geo_hash]
else:
if geo_type == warp.sim.GEO_PLANE:
if s == model.shape_count - 1 and not model.ground:
continue # hide ground plane
# plane mesh
width = geo_scale[0] if geo_scale[0] > 0.0 else 100.0
length = geo_scale[1] if geo_scale[1] > 0.0 else 100.0
shape = self.render_plane(
name, p, q, width, length, color, parent_body=body, is_template=True
)
elif geo_type == warp.sim.GEO_SPHERE:
shape = self.render_sphere(name, p, q, geo_scale[0], parent_body=body, is_template=True)
elif geo_type == warp.sim.GEO_CAPSULE:
shape = self.render_capsule(
name, p, q, geo_scale[0], geo_scale[1], parent_body=body, is_template=True
)
elif geo_type == warp.sim.GEO_CYLINDER:
shape = self.render_cylinder(
name, p, q, geo_scale[0], geo_scale[1], parent_body=body, is_template=True
)
elif geo_type == warp.sim.GEO_CONE:
shape = self.render_cone(
name, p, q, geo_scale[0], geo_scale[1], parent_body=body, is_template=True
)
elif geo_type == warp.sim.GEO_BOX:
shape = self.render_box(name, p, q, geo_scale, parent_body=body, is_template=True)
elif geo_type == warp.sim.GEO_MESH:
if not geo_is_solid:
faces, vertices = solidify_mesh(geo_src.indices, geo_src.vertices, geo_thickness)
else:
faces, vertices = geo_src.indices, geo_src.vertices
shape = self.render_mesh(
name,
vertices,
faces,
pos=p,
rot=q,
scale=geo_scale,
colors=[color],
parent_body=body,
is_template=True,
)
elif geo_type == warp.sim.GEO_SDF:
continue
self.geo_shape[geo_hash] = shape
self.add_shape_instance(name, shape, body, X_bs.p, X_bs.q, scale)
self.instance_count += 1
if self.show_joints and model.joint_count:
joint_type = model.joint_type.numpy()
joint_axis = model.joint_axis.numpy()
joint_axis_start = model.joint_axis_start.numpy()
joint_axis_dim = model.joint_axis_dim.numpy()
joint_parent = model.joint_parent.numpy()
joint_child = model.joint_child.numpy()
joint_tf = model.joint_X_p.numpy()
shape_collision_radius = model.shape_collision_radius.numpy()
y_axis = wp.vec3(0., 1., 0.)
color = (1., 0., 1.)
shape = self.render_arrow(
"joint_arrow", None, None,
base_radius=0.01, base_height=0.4,
cap_radius=0.02, cap_height=0.1,
parent_body=None, is_template=True,
color=color
)
for i, t in enumerate(joint_type):
if t not in {
warp.sim.JOINT_REVOLUTE,
# warp.sim.JOINT_PRISMATIC,
warp.sim.JOINT_UNIVERSAL,
warp.sim.JOINT_COMPOUND,
warp.sim.JOINT_D6,
}:
continue
tf = joint_tf[i]
body = int(joint_parent[i])
# if body == -1:
# continue
num_linear_axes = int(joint_axis_dim[i][0])
num_angular_axes = int(joint_axis_dim[i][1])
# find a good scale for the arrow based on the average radius
# of the shapes attached to the joint child body
scale = np.ones(3)
child = int(joint_child[i])
if child >= 0:
radii = []
for s in model.body_shapes[child]:
radii.append(shape_collision_radius[s])
if len(radii) > 0:
scale *= np.mean(radii) * 2.0
for a in range(num_linear_axes, num_linear_axes + num_angular_axes):
index = joint_axis_start[i] + a
axis = joint_axis[index]
if np.linalg.norm(axis) < 1e-6:
continue
p = wp.vec3(tf[:3])
q = wp.quat(tf[3:])
# compute rotation between axis and y
axis = axis / np.linalg.norm(axis)
q = q * wp.quat_between_vectors(wp.vec3(*axis), y_axis)
name = f"joint_{i}_{a}"
self.add_shape_instance(name, shape, body, p, q, scale, color1=color, color2=color)
self.instance_count += 1
if model.ground:
self.render_ground()
if hasattr(self, "complete_setup"):
self.complete_setup()
def _get_new_color(self):
return tab10_color_map(self.instance_count)
def render(self, state: warp.sim.State):
if self.skip_rendering:
return
if self.model.particle_count:
particle_q = state.particle_q.numpy()
# render particles
self.render_points("particles", particle_q, radius=self.model.particle_radius.numpy())
# render tris
if self.model.tri_count:
self.render_mesh("surface", particle_q, self.model.tri_indices.numpy().flatten())
# render springs
if self.model.spring_count:
self.render_line_list("springs", particle_q, self.model.spring_indices.numpy().flatten(), [], 0.05)
# render muscles
if self.model.muscle_count:
body_q = state.body_q.numpy()
muscle_start = self.model.muscle_start.numpy()
muscle_links = self.model.muscle_bodies.numpy()
muscle_points = self.model.muscle_points.numpy()
muscle_activation = self.model.muscle_activation.numpy()
# for s in self.skeletons:
# # for mesh, link in s.mesh_map.items():
# # if link != -1:
# # X_sc = wp.transform_expand(self.state.body_X_sc[link].tolist())
# # #self.renderer.add_mesh(mesh, "../assets/snu/OBJ/" + mesh + ".usd", X_sc, 1.0, self.render_time)
# # self.renderer.add_mesh(mesh, "../assets/snu/OBJ/" + mesh + ".usd", X_sc, 1.0, self.render_time)
for m in range(self.model.muscle_count):
start = int(muscle_start[m])
end = int(muscle_start[m + 1])
points = []
for w in range(start, end):
link = muscle_links[w]
point = muscle_points[w]
X_sc = wp.transform_expand(body_q[link][0])
points.append(wp.transform_point(X_sc, point).tolist())
self.render_line_strip(
name=f"muscle_{m}", vertices=points, radius=0.0075, color=(muscle_activation[m], 0.2, 0.5)
)
# update bodies
if self.model.body_count:
self.update_body_transforms(state.body_q)
if self.show_rigid_contact_points and self.model.rigid_contact_max:
wp.launch(
kernel=compute_contact_points,
dim=self.model.rigid_contact_max,
inputs=[
state.body_q,
self.model.shape_body,
self.model.rigid_contact_shape0,
self.model.rigid_contact_shape1,
self.model.rigid_contact_point0,
self.model.rigid_contact_point1,
],
outputs=[
self.contact_points0,
self.contact_points1,
],
device=self.model.device,
)
self.render_points(
"contact_points0",
self.contact_points0.numpy(),
radius=self.contact_points_radius * self.scaling,
colors=self.contact_points0_colors,
)
self.render_points(
"contact_points1",
self.contact_points1.numpy(),
radius=self.contact_points_radius * self.scaling,
colors=self.contact_points1_colors,
)
return SimRenderer
SimRendererUsd = CreateSimRenderer(wp.render.UsdRenderer)
SimRendererOpenGL = CreateSimRenderer(wp.render.OpenGLRenderer)
SimRenderer = SimRendererUsd
| warp-main | warp/sim/render.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 .model import (
PARTICLE_FLAG_ACTIVE,
ModelShapeMaterials,
JOINT_MODE_TARGET_POSITION,
JOINT_MODE_TARGET_VELOCITY,
JOINT_MODE_LIMIT,
)
from .utils import velocity_at_point, vec_min, vec_max, vec_abs
from .integrator_euler import integrate_bodies, integrate_particles
@wp.kernel
def solve_particle_ground_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
ke: float,
kd: float,
kf: float,
mu: float,
ground: wp.array(dtype=float),
dt: float,
relaxation: float,
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
wi = invmass[tid]
if wi == 0.0:
return
x = particle_x[tid]
v = particle_v[tid]
n = wp.vec3(ground[0], ground[1], ground[2])
c = wp.min(wp.dot(n, x) + ground[3] - particle_radius[tid], 0.0)
if c > 0.0:
return
# normal
lambda_n = c
delta_n = n * lambda_n
# friction
vn = wp.dot(n, v)
vt = v - n * vn
lambda_f = wp.max(mu * lambda_n, 0.0 - wp.length(vt) * dt)
delta_f = wp.normalize(vt) * lambda_f
wp.atomic_add(delta, tid, (delta_f - delta_n) / wi * relaxation)
@wp.kernel
def apply_soft_restitution_ground(
particle_x_new: wp.array(dtype=wp.vec3),
particle_v_new: wp.array(dtype=wp.vec3),
particle_x_old: wp.array(dtype=wp.vec3),
particle_v_old: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
restitution: float,
ground: wp.array(dtype=float),
dt: float,
relaxation: float,
particle_v_out: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
wi = invmass[tid]
if wi == 0.0:
return
# x_new = particle_x_new[tid]
v_new = particle_v_new[tid]
x_old = particle_x_old[tid]
v_old = particle_v_old[tid]
n = wp.vec3(ground[0], ground[1], ground[2])
c = wp.dot(n, x_old) + ground[3] - particle_radius[tid]
if c > 0.0:
return
rel_vel_old = wp.dot(n, v_old)
rel_vel_new = wp.dot(n, v_new)
dv = n * wp.max(-rel_vel_new + wp.max(-restitution * rel_vel_old, 0.0), 0.0)
wp.atomic_add(particle_v_out, tid, dv / wi * relaxation)
@wp.kernel
def solve_particle_shape_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
shape_body: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
particle_mu: float,
particle_ka: float,
contact_count: wp.array(dtype=int),
contact_particle: wp.array(dtype=int),
contact_shape: wp.array(dtype=int),
contact_body_pos: wp.array(dtype=wp.vec3),
contact_body_vel: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_max: int,
dt: float,
relaxation: float,
# outputs
delta: wp.array(dtype=wp.vec3),
body_delta: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
count = min(contact_max, contact_count[0])
if tid >= count:
return
shape_index = contact_shape[tid]
body_index = shape_body[shape_index]
particle_index = contact_particle[tid]
px = particle_x[particle_index]
pv = particle_v[particle_index]
X_wb = wp.transform_identity()
X_com = wp.vec3()
if body_index >= 0:
X_wb = body_q[body_index]
X_com = body_com[body_index]
# body position in world space
bx = wp.transform_point(X_wb, contact_body_pos[tid])
r = bx - wp.transform_point(X_wb, X_com)
n = contact_normal[tid]
c = wp.dot(n, px - bx) - particle_radius[tid]
if c > particle_ka:
return
# take average material properties of shape and particle parameters
mu = 0.5 * (particle_mu + shape_materials.mu[shape_index])
# body velocity
body_v_s = wp.spatial_vector()
if body_index >= 0:
body_v_s = body_qd[body_index]
body_w = wp.spatial_top(body_v_s)
body_v = wp.spatial_bottom(body_v_s)
# compute the body velocity at the particle position
bv = body_v + wp.cross(body_w, r) + wp.transform_vector(X_wb, contact_body_vel[tid])
# relative velocity
v = pv - bv
# normal
lambda_n = c
delta_n = n * lambda_n
# friction
vn = wp.dot(n, v)
vt = v - n * vn
# compute inverse masses
w1 = particle_invmass[particle_index]
w2 = 0.0
if body_index >= 0:
angular = wp.cross(r, n)
q = wp.transform_get_rotation(X_wb)
rot_angular = wp.quat_rotate_inv(q, angular)
I_inv = body_I_inv[body_index]
w2 = body_m_inv[body_index] + wp.dot(rot_angular, I_inv * rot_angular)
denom = w1 + w2
if denom == 0.0:
return
lambda_f = wp.max(mu * lambda_n, -wp.length(vt) * dt)
delta_f = wp.normalize(vt) * lambda_f
delta_total = (delta_f - delta_n) / denom * relaxation
wp.atomic_add(delta, particle_index, delta_total)
if body_index >= 0:
delta_t = wp.cross(r, delta_total)
wp.atomic_sub(body_delta, body_index, wp.spatial_vector(delta_t, delta_total))
@wp.kernel
def solve_particle_particle_contacts(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
k_mu: float,
k_cohesion: float,
max_radius: float,
dt: float,
relaxation: float,
# outputs
deltas: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
if i == -1:
# hash grid has not been built yet
return
if (particle_flags[i] & PARTICLE_FLAG_ACTIVE) == 0:
return
x = particle_x[i]
v = particle_v[i]
radius = particle_radius[i]
w1 = particle_invmass[i]
# particle contact
query = wp.hash_grid_query(grid, x, radius + max_radius + k_cohesion)
index = int(0)
delta = wp.vec3(0.0)
while wp.hash_grid_query_next(query, index):
if (particle_flags[index] & PARTICLE_FLAG_ACTIVE) != 0 and index != i:
# compute distance to point
n = x - particle_x[index]
d = wp.length(n)
err = d - radius - particle_radius[index]
# compute inverse masses
w2 = particle_invmass[index]
denom = w1 + w2
if err <= k_cohesion and denom > 0.0:
n = n / d
vrel = v - particle_v[index]
# normal
lambda_n = err
delta_n = n * lambda_n
# friction
vn = wp.dot(n, vrel)
vt = v - n * vn
lambda_f = wp.max(k_mu * lambda_n, -wp.length(vt) * dt)
delta_f = wp.normalize(vt) * lambda_f
delta += (delta_f - delta_n) / denom
wp.atomic_add(deltas, i, delta * relaxation)
@wp.kernel
def solve_springs(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
spring_indices: wp.array(dtype=int),
spring_rest_lengths: wp.array(dtype=float),
spring_stiffness: wp.array(dtype=float),
spring_damping: wp.array(dtype=float),
dt: float,
lambdas: wp.array(dtype=float),
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = spring_indices[tid * 2 + 0]
j = spring_indices[tid * 2 + 1]
ke = spring_stiffness[tid]
kd = spring_damping[tid]
rest = spring_rest_lengths[tid]
xi = x[i]
xj = x[j]
vi = v[i]
vj = v[j]
xij = xi - xj
vij = vi - vj
l = wp.length(xij)
if l == 0.0:
return
n = xij / l
c = l - rest
grad_c_xi = n
grad_c_xj = -1.0 * n
wi = invmass[i]
wj = invmass[j]
denom = wi + wj
# Note strict inequality for damping -- 0 damping is ok
if denom <= 0.0 or ke <= 0.0 or kd < 0.0:
return
alpha= 1.0 / (ke * dt * dt)
gamma = kd / (ke * dt)
grad_c_dot_v = dt * wp.dot(grad_c_xi, vij) # Note: dt because from the paper we want x_i - x^n, not v...
dlambda = -1.0 * (c + alpha* lambdas[tid] + gamma * grad_c_dot_v) / ((1.0 + gamma) * denom + alpha)
dxi = wi * dlambda * grad_c_xi
dxj = wj * dlambda * grad_c_xj
lambdas[tid] = lambdas[tid] + dlambda
wp.atomic_add(delta, i, dxi)
wp.atomic_add(delta, j, dxj)
@wp.kernel
def bending_constraint(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
indices: wp.array2d(dtype=int),
rest: wp.array(dtype=float),
bending_properties: wp.array2d(dtype=float),
dt: float,
lambdas: wp.array(dtype=float),
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
eps = 1.0e-6
ke = bending_properties[tid, 0]
kd = bending_properties[tid, 1]
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
if i == -1 or j == -1 or k == -1 or l == -1:
return
rest_angle = rest[tid]
x1 = x[i]
x2 = x[j]
x3 = x[k]
x4 = x[l]
v1 = v[i]
v2 = v[j]
v3 = v[k]
v4 = v[l]
w1 = invmass[i]
w2 = invmass[j]
w3 = invmass[k]
w4 = invmass[l]
n1 = wp.cross(x3 - x1, x4 - x1) # normal to face 1
n2 = wp.cross(x4 - x2, x3 - x2) # normal to face 2
n1_length = wp.length(n1)
n2_length = wp.length(n2)
if n1_length < eps or n2_length < eps:
return
n1 /= n1_length
n2 /= n2_length
cos_theta = wp.dot(n1, n2)
e = x4 - x3
e_hat = wp.normalize(e)
e_length = wp.length(e)
derivative_flip = wp.sign(wp.dot(wp.cross(n1, n2), e))
derivative_flip *= -1.0
angle = wp.acos(cos_theta)
grad_x1 = n1 * e_length * derivative_flip
grad_x2 = n2 * e_length * derivative_flip
grad_x3 = (n1 * wp.dot(x1 - x4, e_hat) + n2 * wp.dot(x2 - x4, e_hat)) * derivative_flip
grad_x4 = (n1 * wp.dot(x3 - x1, e_hat) + n2 * wp.dot(x3 - x2, e_hat)) * derivative_flip
c = angle - rest_angle
denominator = (w1 * wp.length_sq(grad_x1) + w2 * wp.length_sq(grad_x2) + w3 * wp.length_sq(grad_x3) + w4 * wp.length_sq(grad_x4))
# Note strict inequality for damping -- 0 damping is ok
if denominator <= 0.0 or ke <= 0.0 or kd < 0.0:
return
alpha = 1.0 / (ke * dt * dt)
gamma = kd / (ke * dt)
grad_dot_v = dt * (wp.dot(grad_x1, v1) + wp.dot(grad_x2, v2) + wp.dot(grad_x3, v3) + wp.dot(grad_x4, v4))
dlambda = -1.0 * (c + alpha * lambdas[tid] + gamma * grad_dot_v) / ((1.0 + gamma) * denominator + alpha)
delta0 = w1 * dlambda * grad_x1
delta1 = w2 * dlambda * grad_x2
delta2 = w3 * dlambda * grad_x3
delta3 = w4 * dlambda * grad_x4
lambdas[tid] = lambdas[tid] + dlambda
wp.atomic_add(delta, i, delta0)
wp.atomic_add(delta, j, delta1)
wp.atomic_add(delta, k, delta2)
wp.atomic_add(delta, l, delta3)
@wp.kernel
def solve_tetrahedra(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
inv_mass: wp.array(dtype=float),
indices: wp.array(dtype=int, ndim=2),
pose: wp.array(dtype=wp.mat33),
activation: wp.array(dtype=float),
materials: wp.array(dtype=float, ndim=2),
dt: float,
relaxation: float,
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
act = activation[tid]
k_mu = materials[tid, 0]
k_lambda = materials[tid, 1]
k_damp = materials[tid, 2]
x0 = x[i]
x1 = x[j]
x2 = x[k]
x3 = x[l]
v0 = v[i]
v1 = v[j]
v2 = v[k]
v3 = v[l]
w0 = inv_mass[i]
w1 = inv_mass[j]
w2 = inv_mass[k]
w3 = inv_mass[l]
x10 = x1 - x0
x20 = x2 - x0
x30 = x3 - x0
v10 = v1 - v0
v20 = v2 - v0
v30 = v3 - v0
Ds = wp.mat33(x10, x20, x30)
Dm = pose[tid]
inv_rest_volume = wp.determinant(Dm) * 6.0
rest_volume = 1.0 / inv_rest_volume
# F = Xs*Xm^-1
F = Ds * Dm
f1 = wp.vec3(F[0, 0], F[1, 0], F[2, 0])
f2 = wp.vec3(F[0, 1], F[1, 1], F[2, 1])
f3 = wp.vec3(F[0, 2], F[1, 2], F[2, 2])
# C_sqrt
# tr = wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3)
# r_s = wp.sqrt(abs(tr - 3.0))
# C = r_s
# if (r_s == 0.0):
# return
# if (tr < 3.0):
# r_s = 0.0 - r_s
# dCdx = F*wp.transpose(Dm)*(1.0/r_s)
# alpha = 1.0 + k_mu / k_lambda
# C_Neo
r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
if r_s == 0.0:
return
# tr = wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3)
# if (tr < 3.0):
# r_s = -r_s
r_s_inv = 1.0 / r_s
C = r_s
dCdx = F * wp.transpose(Dm) * r_s_inv
alpha = 1.0 + k_mu / k_lambda
# C_Spherical
# r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
# r_s_inv = 1.0/r_s
# C = r_s - wp.sqrt(3.0)
# dCdx = F*wp.transpose(Dm)*r_s_inv
# alpha = 1.0
# C_D
# r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
# C = r_s*r_s - 3.0
# dCdx = F*wp.transpose(Dm)*2.0
# alpha = 1.0
grad1 = wp.vec3(dCdx[0, 0], dCdx[1, 0], dCdx[2, 0])
grad2 = wp.vec3(dCdx[0, 1], dCdx[1, 1], dCdx[2, 1])
grad3 = wp.vec3(dCdx[0, 2], dCdx[1, 2], dCdx[2, 2])
grad0 = (grad1 + grad2 + grad3) * (0.0 - 1.0)
denom = (
wp.dot(grad0, grad0) * w0 + wp.dot(grad1, grad1) * w1 + wp.dot(grad2, grad2) * w2 + wp.dot(grad3, grad3) * w3
)
multiplier = C / (denom + 1.0 / (k_mu * dt * dt * rest_volume))
delta0 = grad0 * multiplier
delta1 = grad1 * multiplier
delta2 = grad2 * multiplier
delta3 = grad3 * multiplier
# hydrostatic part
J = wp.determinant(F)
C_vol = J - alpha
# dCdx = wp.mat33(wp.cross(f2, f3), wp.cross(f3, f1), wp.cross(f1, f2))*wp.transpose(Dm)
# grad1 = wp.vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = wp.vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = wp.vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# grad0 = (grad1 + grad2 + grad3)*(0.0 - 1.0)
s = inv_rest_volume / 6.0
grad1 = wp.cross(x20, x30) * s
grad2 = wp.cross(x30, x10) * s
grad3 = wp.cross(x10, x20) * s
grad0 = -(grad1 + grad2 + grad3)
denom = (
wp.dot(grad0, grad0) * w0 + wp.dot(grad1, grad1) * w1 + wp.dot(grad2, grad2) * w2 + wp.dot(grad3, grad3) * w3
)
multiplier = C_vol / (denom + 1.0 / (k_lambda * dt * dt * rest_volume))
delta0 += grad0 * multiplier
delta1 += grad1 * multiplier
delta2 += grad2 * multiplier
delta3 += grad3 * multiplier
# apply forces
wp.atomic_sub(delta, i, delta0 * w0 * relaxation)
wp.atomic_sub(delta, j, delta1 * w1 * relaxation)
wp.atomic_sub(delta, k, delta2 * w2 * relaxation)
wp.atomic_sub(delta, l, delta3 * w3 * relaxation)
@wp.kernel
def apply_particle_deltas(
x_orig: wp.array(dtype=wp.vec3),
x_pred: wp.array(dtype=wp.vec3),
particle_flags: wp.array(dtype=wp.uint32),
delta: wp.array(dtype=wp.vec3),
dt: float,
v_max: float,
x_out: wp.array(dtype=wp.vec3),
v_out: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
x0 = x_orig[tid]
xp = x_pred[tid]
# constraint deltas
d = delta[tid]
x_new = xp + d
v_new = (x_new - x0) / dt
# enforce velocity limit to prevent instability
v_new_mag = wp.length(v_new)
if v_new_mag > v_max:
v_new *= v_max / v_new_mag
x_out[tid] = x_new
v_out[tid] = v_new
@wp.kernel
def apply_body_deltas(
q_in: wp.array(dtype=wp.transform),
qd_in: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_I: wp.array(dtype=wp.mat33),
body_inv_m: wp.array(dtype=float),
body_inv_I: wp.array(dtype=wp.mat33),
deltas: wp.array(dtype=wp.spatial_vector),
constraint_inv_weights: wp.array(dtype=float),
dt: float,
# outputs
q_out: wp.array(dtype=wp.transform),
qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
inv_m = body_inv_m[tid]
if inv_m == 0.0:
q_out[tid] = q_in[tid]
qd_out[tid] = qd_in[tid]
return
inv_I = body_inv_I[tid]
tf = q_in[tid]
delta = deltas[tid]
p0 = wp.transform_get_translation(tf)
q0 = wp.transform_get_rotation(tf)
weight = 1.0
if constraint_inv_weights:
if constraint_inv_weights[tid] > 0.0:
weight = 1.0 / constraint_inv_weights[tid]
dp = wp.spatial_bottom(delta) * (inv_m * weight)
dq = wp.spatial_top(delta) * weight
dq = wp.quat_rotate(q0, inv_I * wp.quat_rotate_inv(q0, dq))
# update orientation
q1 = q0 + 0.5 * wp.quat(dq * dt * dt, 0.0) * q0
q1 = wp.normalize(q1)
# update position
com = body_com[tid]
x_com = p0 + wp.quat_rotate(q0, com)
p1 = x_com + dp * dt * dt
p1 -= wp.quat_rotate(q1, com)
q_out[tid] = wp.transform(p1, q1)
v0 = wp.spatial_bottom(qd_in[tid])
w0 = wp.spatial_top(qd_in[tid])
# update linear and angular velocity
v1 = v0 + dp * dt
# angular part (compute in body frame)
wb = wp.quat_rotate_inv(q0, w0 + dq * dt)
tb = -wp.cross(wb, body_I[tid] * wb) # coriolis forces
w1 = wp.quat_rotate(q0, wb + inv_I * tb * dt)
qd_out[tid] = wp.spatial_vector(w1, v1)
@wp.kernel
def apply_body_delta_velocities(
qd_in: wp.array(dtype=wp.spatial_vector),
deltas: wp.array(dtype=wp.spatial_vector),
qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
qd_out[tid] = qd_in[tid] + deltas[tid]
@wp.kernel
def apply_joint_torques(
body_q: wp.array(dtype=wp.transform),
body_com: wp.array(dtype=wp.vec3),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis: wp.array(dtype=wp.vec3),
joint_act: wp.array(dtype=float),
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
if type == wp.sim.JOINT_FIXED:
return
if type == wp.sim.JOINT_FREE:
return
if type == wp.sim.JOINT_DISTANCE:
return
if type == wp.sim.JOINT_BALL:
return
# rigid body indices of the child and parent
id_c = joint_child[tid]
id_p = joint_parent[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
pose_p = X_pj
com_p = wp.vec3(0.0)
# parent transform and moment arm
if id_p >= 0:
pose_p = body_q[id_p]
X_wp = pose_p * X_wp
com_p = body_com[id_p]
r_p = wp.transform_get_translation(X_wp) - wp.transform_point(pose_p, com_p)
# child transform and moment arm
pose_c = body_q[id_c]
X_wc = pose_c
com_c = body_com[id_c]
r_c = wp.transform_get_translation(X_wc) - wp.transform_point(pose_c, com_c)
# local joint rotations
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
# joint properties (for 1D joints)
q_start = joint_q_start[tid]
qd_start = joint_qd_start[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
# total force/torque on the parent
t_total = wp.vec3()
f_total = wp.vec3()
# handle angular constraints
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
act = joint_act[qd_start]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
elif type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
act = joint_act[qd_start]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
elif type == wp.sim.JOINT_COMPOUND:
# q_off = wp.transform_get_rotation(X_cj)
# q_pc = wp.quat_inverse(q_off)*wp.quat_inverse(q_p)*q_c*q_off
# # decompose to a compound rotation each axis
# angles = quat_decompose(q_pc)
# # reconstruct rotation axes
# axis_0 = wp.vec3(1.0, 0.0, 0.0)
# q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
# axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
# q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
# axis_2 = wp.quat_rotate(q_1*q_0, wp.vec3(0.0, 0.0, 1.0))
# q_w = q_p*q_off
# t_total += joint_act[qd_start+0] * wp.quat_rotate(q_w, axis_0)
# t_total += joint_act[qd_start+1] * wp.quat_rotate(q_w, axis_1)
# t_total += joint_act[qd_start+2] * wp.quat_rotate(q_w, axis_2)
axis_0 = joint_axis[axis_start + 0]
axis_1 = joint_axis[axis_start + 1]
axis_2 = joint_axis[axis_start + 2]
t_total += joint_act[qd_start + 0] * wp.transform_vector(X_wp, axis_0)
t_total += joint_act[qd_start + 1] * wp.transform_vector(X_wp, axis_1)
t_total += joint_act[qd_start + 2] * wp.transform_vector(X_wp, axis_2)
elif type == wp.sim.JOINT_UNIVERSAL:
# q_off = wp.transform_get_rotation(X_cj)
# q_pc = wp.quat_inverse(q_off)*wp.quat_inverse(q_p)*q_c*q_off
# # decompose to a compound rotation each axis
# angles = quat_decompose(q_pc)
# # reconstruct rotation axes
# axis_0 = wp.vec3(1.0, 0.0, 0.0)
# q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
# axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
# q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
# axis_2 = wp.quat_rotate(q_1*q_0, wp.vec3(0.0, 0.0, 1.0))
# q_w = q_p*q_off
# free axes
# t_total += joint_act[qd_start+0] * wp.quat_rotate(q_w, axis_0)
# t_total += joint_act[qd_start+1] * wp.quat_rotate(q_w, axis_1)
axis_0 = joint_axis[axis_start + 0]
axis_1 = joint_axis[axis_start + 1]
t_total += joint_act[qd_start + 0] * wp.transform_vector(X_wp, axis_0)
t_total += joint_act[qd_start + 1] * wp.transform_vector(X_wp, axis_1)
elif type == wp.sim.JOINT_D6:
# unroll for loop to ensure joint actions remain differentiable
# (since differentiating through a dynamic for loop that updates a local variable is not supported)
if lin_axis_count > 0:
axis = joint_axis[axis_start + 0]
act = joint_act[qd_start + 0]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
if lin_axis_count > 1:
axis = joint_axis[axis_start + 1]
act = joint_act[qd_start + 1]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
if lin_axis_count > 2:
axis = joint_axis[axis_start + 2]
act = joint_act[qd_start + 2]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
if ang_axis_count > 0:
axis = joint_axis[axis_start + lin_axis_count + 0]
act = joint_act[qd_start + lin_axis_count + 0]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
if ang_axis_count > 1:
axis = joint_axis[axis_start + lin_axis_count + 1]
act = joint_act[qd_start + lin_axis_count + 1]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
if ang_axis_count > 2:
axis = joint_axis[axis_start + lin_axis_count + 2]
act = joint_act[qd_start + lin_axis_count + 2]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
else:
print("joint type not handled in apply_joint_torques")
# write forces
if id_p >= 0:
wp.atomic_add(body_f, id_p, wp.spatial_vector(t_total + wp.cross(r_p, f_total), f_total))
wp.atomic_sub(body_f, id_c, wp.spatial_vector(t_total + wp.cross(r_c, f_total), f_total))
@wp.func
def update_joint_axis_mode(mode: wp.uint8, axis: wp.vec3, input_axis_mode: wp.vec3ub):
# update the 3D axis mode flags given the axis vector and mode of this axis
mode_x = wp.max(wp.uint8(wp.nonzero(axis[0])) * mode, input_axis_mode[0])
mode_y = wp.max(wp.uint8(wp.nonzero(axis[1])) * mode, input_axis_mode[1])
mode_z = wp.max(wp.uint8(wp.nonzero(axis[2])) * mode, input_axis_mode[2])
return wp.vec3ub(mode_x, mode_y, mode_z)
@wp.func
def update_joint_axis_limits(axis: wp.vec3, limit_lower: float, limit_upper: float, input_limits: wp.spatial_vector):
# update the 3D linear/angular limits (spatial_vector [lower, upper]) given the axis vector and limits
lo_temp = axis * limit_lower
up_temp = axis * limit_upper
lo = vec_min(lo_temp, up_temp)
up = vec_max(lo_temp, up_temp)
input_lower = wp.spatial_top(input_limits)
input_upper = wp.spatial_bottom(input_limits)
lower = vec_min(input_lower, lo)
upper = vec_max(input_upper, up)
return wp.spatial_vector(lower, upper)
@wp.func
def update_joint_axis_target_ke_kd(
axis: wp.vec3, target: float, target_ke: float, target_kd: float, input_target_ke_kd: wp.mat33
):
# update the 3D linear/angular target, target_ke, and target_kd (mat33 [target, ke, kd]) given the axis vector and target, target_ke, target_kd
axis_target = input_target_ke_kd[0]
axis_ke = input_target_ke_kd[1]
axis_kd = input_target_ke_kd[2]
stiffness = axis * target_ke
axis_target += stiffness * target # weighted target (to be normalized later by sum of target_ke)
axis_ke += vec_abs(stiffness)
axis_kd += vec_abs(axis * target_kd)
return wp.mat33(
axis_target[0],
axis_target[1],
axis_target[2],
axis_ke[0],
axis_ke[1],
axis_ke[2],
axis_kd[0],
axis_kd[1],
axis_kd[2],
)
@wp.kernel
def solve_body_joints(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_inv_m: wp.array(dtype=float),
body_inv_I: wp.array(dtype=wp.mat33),
joint_type: wp.array(dtype=int),
joint_enabled: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis_mode: wp.array(dtype=wp.uint8),
joint_axis: wp.array(dtype=wp.vec3),
joint_target: wp.array(dtype=float),
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_linear_compliance: wp.array(dtype=float),
joint_angular_compliance: wp.array(dtype=float),
angular_relaxation: float,
linear_relaxation: float,
dt: float,
deltas: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
if joint_enabled[tid] == 0 or type == wp.sim.JOINT_FREE:
return
# rigid body indices of the child and parent
id_c = joint_child[tid]
id_p = joint_parent[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
m_inv_p = 0.0
I_inv_p = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
pose_p = X_pj
com_p = wp.vec3(0.0)
vel_p = wp.vec3(0.0)
omega_p = wp.vec3(0.0)
# parent transform and moment arm
if id_p >= 0:
pose_p = body_q[id_p]
X_wp = pose_p * X_wp
com_p = body_com[id_p]
m_inv_p = body_inv_m[id_p]
I_inv_p = body_inv_I[id_p]
vel_p = wp.spatial_bottom(body_qd[id_p])
omega_p = wp.spatial_top(body_qd[id_p])
# child transform and moment arm
pose_c = body_q[id_c]
X_wc = pose_c * X_cj
com_c = body_com[id_c]
m_inv_c = body_inv_m[id_c]
I_inv_c = body_inv_I[id_c]
vel_c = wp.spatial_bottom(body_qd[id_c])
omega_c = wp.spatial_top(body_qd[id_c])
if m_inv_p == 0.0 and m_inv_c == 0.0:
# connection between two immovable bodies
return
# accumulate constraint deltas
lin_delta_p = wp.vec3(0.0)
ang_delta_p = wp.vec3(0.0)
lin_delta_c = wp.vec3(0.0)
ang_delta_c = wp.vec3(0.0)
rel_pose = wp.transform_inverse(X_wp) * X_wc
rel_p = wp.transform_get_translation(rel_pose)
# joint connection points
# x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
linear_compliance = joint_linear_compliance[tid]
angular_compliance = joint_angular_compliance[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
world_com_p = wp.transform_point(pose_p, com_p)
world_com_c = wp.transform_point(pose_c, com_c)
# handle positional constraints
if type == wp.sim.JOINT_DISTANCE:
r_p = wp.transform_get_translation(X_wp) - world_com_p
r_c = wp.transform_get_translation(X_wc) - world_com_c
lower = joint_limit_lower[axis_start]
upper = joint_limit_upper[axis_start]
if lower < 0.0 and upper < 0.0:
# no limits
return
d = wp.length(rel_p)
err = 0.0
if lower >= 0.0 and d < lower:
err = d - lower
# use a more descriptive direction vector for the constraint
# in case the joint parent and child anchors are very close
rel_p = err * wp.normalize(world_com_c - world_com_p)
elif upper >= 0.0 and d > upper:
err = d - upper
if wp.abs(err) > 1e-9:
# compute gradients
linear_c = rel_p
linear_p = -linear_c
r_c = x_c - world_com_c
angular_p = -wp.cross(r_p, linear_c)
angular_c = wp.cross(r_c, linear_c)
# constraint time derivative
derr = (
wp.dot(linear_p, vel_p)
+ wp.dot(linear_c, vel_c)
+ wp.dot(angular_p, omega_p)
+ wp.dot(angular_c, omega_c)
)
lambda_in = 0.0
compliance = linear_compliance
ke = joint_target_ke[axis_start]
if ke > 0.0:
compliance = 1.0 / ke
damping = joint_target_kd[axis_start]
d_lambda = compute_positional_correction(
err,
derr,
pose_p,
pose_c,
m_inv_p,
m_inv_c,
I_inv_p,
I_inv_c,
linear_p,
linear_c,
angular_p,
angular_c,
lambda_in,
compliance,
damping,
dt,
)
lin_delta_p += linear_p * (d_lambda * linear_relaxation)
ang_delta_p += angular_p * (d_lambda * angular_relaxation)
lin_delta_c += linear_c * (d_lambda * linear_relaxation)
ang_delta_c += angular_c * (d_lambda * angular_relaxation)
else:
# compute joint target, stiffness, damping
ke_sum = float(0.0)
axis_limits = wp.spatial_vector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
axis_mode = wp.vec3ub(wp.uint8(0), wp.uint8(0), wp.uint8(0))
axis_target_ke_kd = wp.mat33(0.0)
# avoid a for loop here since local variables would need to be modified which is not yet differentiable
if lin_axis_count > 0:
axis = joint_axis[axis_start]
lo_temp = axis * joint_limit_lower[axis_start]
up_temp = axis * joint_limit_upper[axis_start]
axis_limits = wp.spatial_vector(vec_min(lo_temp, up_temp), vec_max(lo_temp, up_temp))
mode = joint_axis_mode[axis_start]
if mode != JOINT_MODE_LIMIT: # position or velocity target
ke = joint_target_ke[axis_start]
kd = joint_target_kd[axis_start]
target = joint_target[axis_start]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if lin_axis_count > 1:
axis_idx = axis_start + 1
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_LIMIT: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_target[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if lin_axis_count > 2:
axis_idx = axis_start + 2
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_LIMIT: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_target[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
axis_target = axis_target_ke_kd[0]
axis_stiffness = axis_target_ke_kd[1]
axis_damping = axis_target_ke_kd[2]
if ke_sum > 0.0:
axis_target /= ke_sum
axis_limits_lower = wp.spatial_top(axis_limits)
axis_limits_upper = wp.spatial_bottom(axis_limits)
frame_p = wp.quat_to_matrix(wp.transform_get_rotation(X_wp))
# note that x_c appearing in both is correct
r_p = x_c - world_com_p
r_c = x_c - wp.transform_point(pose_c, com_c)
# for loop will be unrolled, so we can modify local variables
for dim in range(3):
e = rel_p[dim]
mode = axis_mode[dim]
# compute gradients
linear_c = wp.vec3(frame_p[0, dim], frame_p[1, dim], frame_p[2, dim])
linear_p = -linear_c
angular_p = -wp.cross(r_p, linear_c)
angular_c = wp.cross(r_c, linear_c)
# constraint time derivative
derr = (
wp.dot(linear_p, vel_p)
+ wp.dot(linear_c, vel_c)
+ wp.dot(angular_p, omega_p)
+ wp.dot(angular_c, omega_c)
)
err = 0.0
compliance = linear_compliance
damping = 0.0
# consider joint limits irrespective of axis mode
lower = axis_limits_lower[dim]
upper = axis_limits_upper[dim]
if e < lower:
err = e - lower
compliance = linear_compliance
damping = 0.0
elif e > upper:
err = e - upper
compliance = linear_compliance
damping = 0.0
else:
target = axis_target[dim]
if mode == JOINT_MODE_TARGET_POSITION:
target = wp.clamp(target, lower, upper)
if axis_stiffness[dim] > 0.0:
err = e - target
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
elif mode == JOINT_MODE_TARGET_VELOCITY:
if axis_stiffness[dim] > 0.0:
err = (derr - target) * dt
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
if wp.abs(err) > 1e-9:
lambda_in = 0.0
d_lambda = compute_positional_correction(
err,
derr,
pose_p,
pose_c,
m_inv_p,
m_inv_c,
I_inv_p,
I_inv_c,
linear_p,
linear_c,
angular_p,
angular_c,
lambda_in,
compliance,
damping,
dt,
)
lin_delta_p += linear_p * (d_lambda * linear_relaxation)
ang_delta_p += angular_p * (d_lambda * angular_relaxation)
lin_delta_c += linear_c * (d_lambda * linear_relaxation)
ang_delta_c += angular_c * (d_lambda * angular_relaxation)
if (
type == wp.sim.JOINT_FIXED
or type == wp.sim.JOINT_PRISMATIC
or type == wp.sim.JOINT_REVOLUTE
or type == wp.sim.JOINT_UNIVERSAL
or type == wp.sim.JOINT_COMPOUND
or type == wp.sim.JOINT_D6
):
# handle angular constraints
# local joint rotations
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
# make quats lie in same hemisphere
if wp.dot(q_p, q_c) < 0.0:
q_c *= -1.0
rel_q = wp.quat_inverse(q_p) * q_c
qtwist = wp.normalize(wp.quat(rel_q[0], 0.0, 0.0, rel_q[3]))
qswing = rel_q * wp.quat_inverse(qtwist)
# decompose to a compound rotation each axis
s = wp.sqrt(rel_q[0] * rel_q[0] + rel_q[3] * rel_q[3])
invs = 1.0 / s
invscube = invs * invs * invs
# handle axis-angle joints
# rescale twist from quaternion space to angular
err_0 = 2.0 * wp.asin(wp.clamp(qtwist[0], -1.0, 1.0))
err_1 = qswing[1]
err_2 = qswing[2]
# analytic gradients of swing-twist decomposition
grad_0 = wp.quat(invs - rel_q[0] * rel_q[0] * invscube, 0.0, 0.0, -(rel_q[3] * rel_q[0]) * invscube)
grad_1 = wp.quat(
-rel_q[3] * (rel_q[3] * rel_q[2] + rel_q[0] * rel_q[1]) * invscube,
rel_q[3] * invs,
-rel_q[0] * invs,
rel_q[0] * (rel_q[3] * rel_q[2] + rel_q[0] * rel_q[1]) * invscube,
)
grad_2 = wp.quat(
rel_q[3] * (rel_q[3] * rel_q[1] - rel_q[0] * rel_q[2]) * invscube,
rel_q[0] * invs,
rel_q[3] * invs,
rel_q[0] * (rel_q[2] * rel_q[0] - rel_q[3] * rel_q[1]) * invscube,
)
grad_0 *= 2.0 / wp.abs(qtwist[3])
# grad_0 *= 2.0 / wp.sqrt(1.0-qtwist[0]*qtwist[0]) # derivative of asin(x) = 1/sqrt(1-x^2)
# rescale swing
swing_sq = qswing[3] * qswing[3]
# if swing axis magnitude close to zero vector, just treat in quaternion space
angularEps = 1.0e-4
if swing_sq + angularEps < 1.0:
d = wp.sqrt(1.0 - qswing[3] * qswing[3])
theta = 2.0 * wp.acos(wp.clamp(qswing[3], -1.0, 1.0))
scale = theta / d
err_1 *= scale
err_2 *= scale
grad_1 *= scale
grad_2 *= scale
errs = wp.vec3(err_0, err_1, err_2)
grad_x = wp.vec3(grad_0[0], grad_1[0], grad_2[0])
grad_y = wp.vec3(grad_0[1], grad_1[1], grad_2[1])
grad_z = wp.vec3(grad_0[2], grad_1[2], grad_2[2])
grad_w = wp.vec3(grad_0[3], grad_1[3], grad_2[3])
# compute joint target, stiffness, damping
ke_sum = float(0.0)
axis_limits = wp.spatial_vector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
axis_mode = wp.vec3ub(wp.uint8(0), wp.uint8(0), wp.uint8(0))
axis_target_ke_kd = wp.mat33(0.0)
# avoid a for loop here since local variables would need to be modified which is not yet differentiable
if ang_axis_count > 0:
axis_idx = axis_start + lin_axis_count
axis = joint_axis[axis_idx]
lo_temp = axis * joint_limit_lower[axis_idx]
up_temp = axis * joint_limit_upper[axis_idx]
axis_limits = wp.spatial_vector(vec_min(lo_temp, up_temp), vec_max(lo_temp, up_temp))
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_LIMIT: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_target[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if ang_axis_count > 1:
axis_idx = axis_start + lin_axis_count + 1
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_LIMIT: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_target[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if ang_axis_count > 2:
axis_idx = axis_start + lin_axis_count + 2
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_LIMIT: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_target[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
axis_target = axis_target_ke_kd[0]
axis_stiffness = axis_target_ke_kd[1]
axis_damping = axis_target_ke_kd[2]
if ke_sum > 0.0:
axis_target /= ke_sum
axis_limits_lower = wp.spatial_top(axis_limits)
axis_limits_upper = wp.spatial_bottom(axis_limits)
# if type == wp.sim.JOINT_D6:
# wp.printf("axis_target: %f %f %f\t axis_stiffness: %f %f %f\t axis_damping: %f %f %f\t axis_limits_lower: %f %f %f \t axis_limits_upper: %f %f %f\n",
# axis_target[0], axis_target[1], axis_target[2],
# axis_stiffness[0], axis_stiffness[1], axis_stiffness[2],
# axis_damping[0], axis_damping[1], axis_damping[2],
# axis_limits_lower[0], axis_limits_lower[1], axis_limits_lower[2],
# axis_limits_upper[0], axis_limits_upper[1], axis_limits_upper[2])
# # wp.printf("wp.sqrt(1.0-qtwist[0]*qtwist[0]) = %f\n", wp.sqrt(1.0-qtwist[0]*qtwist[0]))
for dim in range(3):
e = errs[dim]
mode = axis_mode[dim]
# analytic gradients of swing-twist decomposition
grad = wp.quat(grad_x[dim], grad_y[dim], grad_z[dim], grad_w[dim])
quat_c = 0.5 * q_p * grad * wp.quat_inverse(q_c)
angular_c = wp.vec3(quat_c[0], quat_c[1], quat_c[2])
angular_p = -angular_c
# time derivative of the constraint
derr = wp.dot(angular_p, omega_p) + wp.dot(angular_c, omega_c)
err = 0.0
compliance = angular_compliance
damping = 0.0
# consider joint limits irrespective of mode
lower = axis_limits_lower[dim]
upper = axis_limits_upper[dim]
if e < lower:
err = e - lower
compliance = angular_compliance
damping = 0.0
elif e > upper:
err = e - upper
compliance = angular_compliance
damping = 0.0
else:
target = axis_target[dim]
if mode == JOINT_MODE_TARGET_POSITION:
target = wp.clamp(target, lower, upper)
if axis_stiffness[dim] > 0.0:
err = e - target
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
elif mode == JOINT_MODE_TARGET_VELOCITY:
if axis_stiffness[dim] > 0.0:
err = (derr - target) * dt
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
d_lambda = (
compute_angular_correction(
err, derr, pose_p, pose_c, I_inv_p, I_inv_c, angular_p, angular_c, 0.0, compliance, damping, dt
)
* angular_relaxation
)
# update deltas
ang_delta_p += angular_p * d_lambda
ang_delta_c += angular_c * d_lambda
if id_p >= 0:
wp.atomic_add(deltas, id_p, wp.spatial_vector(ang_delta_p, lin_delta_p))
if id_c >= 0:
wp.atomic_add(deltas, id_c, wp.spatial_vector(ang_delta_c, lin_delta_c))
@wp.func
def compute_contact_constraint_delta(
err: float,
tf_a: wp.transform,
tf_b: wp.transform,
m_inv_a: float,
m_inv_b: float,
I_inv_a: wp.mat33,
I_inv_b: wp.mat33,
linear_a: wp.vec3,
linear_b: wp.vec3,
angular_a: wp.vec3,
angular_b: wp.vec3,
relaxation: float,
dt: float,
) -> float:
denom = 0.0
denom += wp.length_sq(linear_a) * m_inv_a
denom += wp.length_sq(linear_b) * m_inv_b
q1 = wp.transform_get_rotation(tf_a)
q2 = wp.transform_get_rotation(tf_b)
# Eq. 2-3 (make sure to project into the frame of the body)
rot_angular_a = wp.quat_rotate_inv(q1, angular_a)
rot_angular_b = wp.quat_rotate_inv(q2, angular_b)
denom += wp.dot(rot_angular_a, I_inv_a * rot_angular_a)
denom += wp.dot(rot_angular_b, I_inv_b * rot_angular_b)
deltaLambda = -err
if denom > 0.0:
deltaLambda /= dt * dt * denom
return deltaLambda * relaxation
@wp.func
def compute_positional_correction(
err: float,
derr: float,
tf_a: wp.transform,
tf_b: wp.transform,
m_inv_a: float,
m_inv_b: float,
I_inv_a: wp.mat33,
I_inv_b: wp.mat33,
linear_a: wp.vec3,
linear_b: wp.vec3,
angular_a: wp.vec3,
angular_b: wp.vec3,
lambda_in: float,
compliance: float,
damping: float,
dt: float,
) -> float:
denom = 0.0
denom += wp.length_sq(linear_a) * m_inv_a
denom += wp.length_sq(linear_b) * m_inv_b
q1 = wp.transform_get_rotation(tf_a)
q2 = wp.transform_get_rotation(tf_b)
# Eq. 2-3 (make sure to project into the frame of the body)
rot_angular_a = wp.quat_rotate_inv(q1, angular_a)
rot_angular_b = wp.quat_rotate_inv(q2, angular_b)
denom += wp.dot(rot_angular_a, I_inv_a * rot_angular_a)
denom += wp.dot(rot_angular_b, I_inv_b * rot_angular_b)
alpha = compliance
gamma = compliance * damping
deltaLambda = -(err + alpha * lambda_in + gamma * derr)
if denom + alpha > 0.0:
deltaLambda /= dt * (dt + gamma) * denom + alpha
return deltaLambda
@wp.func
def compute_angular_correction(
err: float,
derr: float,
tf_a: wp.transform,
tf_b: wp.transform,
I_inv_a: wp.mat33,
I_inv_b: wp.mat33,
angular_a: wp.vec3,
angular_b: wp.vec3,
lambda_in: float,
compliance: float,
damping: float,
dt: float,
) -> float:
denom = 0.0
q1 = wp.transform_get_rotation(tf_a)
q2 = wp.transform_get_rotation(tf_b)
# Eq. 2-3 (make sure to project into the frame of the body)
rot_angular_a = wp.quat_rotate_inv(q1, angular_a)
rot_angular_b = wp.quat_rotate_inv(q2, angular_b)
denom += wp.dot(rot_angular_a, I_inv_a * rot_angular_a)
denom += wp.dot(rot_angular_b, I_inv_b * rot_angular_b)
alpha = compliance
gamma = compliance * damping
deltaLambda = -(err + alpha * lambda_in + gamma * derr)
if denom + alpha > 0.0:
deltaLambda /= dt * (dt + gamma) * denom + alpha
return deltaLambda
@wp.kernel
def solve_body_contact_positions(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
contact_count: wp.array(dtype=int),
contact_body0: wp.array(dtype=int),
contact_body1: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_offset0: wp.array(dtype=wp.vec3),
contact_offset1: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_thickness: wp.array(dtype=float),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
relaxation: float,
dt: float,
contact_torsional_friction: float,
contact_rolling_friction: float,
# outputs
deltas: wp.array(dtype=wp.spatial_vector),
active_contact_point0: wp.array(dtype=wp.vec3),
active_contact_point1: wp.array(dtype=wp.vec3),
active_contact_distance: wp.array(dtype=float),
contact_inv_weight: wp.array(dtype=float),
):
tid = wp.tid()
count = contact_count[0]
if tid >= count:
return
body_a = contact_body0[tid]
body_b = contact_body1[tid]
if body_a == body_b:
return
if contact_shape0[tid] == contact_shape1[tid]:
return
# find body to world transform
X_wb_a = wp.transform_identity()
X_wb_b = wp.transform_identity()
if body_a >= 0:
X_wb_a = body_q[body_a]
if body_b >= 0:
X_wb_b = body_q[body_b]
# compute body position in world space
bx_a = wp.transform_point(X_wb_a, contact_point0[tid])
bx_b = wp.transform_point(X_wb_b, contact_point1[tid])
active_contact_point0[tid] = bx_a
active_contact_point1[tid] = bx_b
thickness = contact_thickness[tid]
n = -contact_normal[tid]
d = wp.dot(n, bx_b - bx_a) - thickness
active_contact_distance[tid] = d
if d >= 0.0:
return
m_inv_a = 0.0
m_inv_b = 0.0
I_inv_a = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
I_inv_b = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
# center of mass in body frame
com_a = wp.vec3(0.0)
com_b = wp.vec3(0.0)
# body to world transform
X_wb_a = wp.transform_identity()
X_wb_b = wp.transform_identity()
# angular velocities
omega_a = wp.vec3(0.0)
omega_b = wp.vec3(0.0)
# contact offset in body frame
offset_a = contact_offset0[tid]
offset_b = contact_offset1[tid]
if body_a >= 0:
X_wb_a = body_q[body_a]
com_a = body_com[body_a]
m_inv_a = body_m_inv[body_a]
I_inv_a = body_I_inv[body_a]
omega_a = wp.spatial_top(body_qd[body_a])
if body_b >= 0:
X_wb_b = body_q[body_b]
com_b = body_com[body_b]
m_inv_b = body_m_inv[body_b]
I_inv_b = body_I_inv[body_b]
omega_b = wp.spatial_top(body_qd[body_b])
# use average contact material properties
mat_nonzero = 0
mu = 0.0
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a >= 0:
mat_nonzero += 1
mu += shape_materials.mu[shape_a]
if shape_b >= 0:
mat_nonzero += 1
mu += shape_materials.mu[shape_b]
if mat_nonzero > 0:
mu /= float(mat_nonzero)
r_a = bx_a - wp.transform_point(X_wb_a, com_a)
r_b = bx_b - wp.transform_point(X_wb_b, com_b)
angular_a = -wp.cross(r_a, n)
angular_b = wp.cross(r_b, n)
if contact_inv_weight:
if body_a >= 0:
wp.atomic_add(contact_inv_weight, body_a, 1.0)
if body_b >= 0:
wp.atomic_add(contact_inv_weight, body_b, 1.0)
lambda_n = compute_contact_constraint_delta(
d, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, -n, n, angular_a, angular_b, relaxation, dt
)
lin_delta_a = -n * lambda_n
lin_delta_b = n * lambda_n
ang_delta_a = angular_a * lambda_n
ang_delta_b = angular_b * lambda_n
# linear friction
if mu > 0.0:
# add on displacement from surface offsets, this ensures we include any rotational effects due to thickness from feature
# need to use the current rotation to account for friction due to angular effects (e.g.: slipping contact)
bx_a += wp.transform_vector(X_wb_a, offset_a)
bx_b += wp.transform_vector(X_wb_b, offset_b)
# update delta
delta = bx_b - bx_a
friction_delta = delta - wp.dot(n, delta) * n
perp = wp.normalize(friction_delta)
r_a = bx_a - wp.transform_point(X_wb_a, com_a)
r_b = bx_b - wp.transform_point(X_wb_b, com_b)
angular_a = -wp.cross(r_a, perp)
angular_b = wp.cross(r_b, perp)
err = wp.length(friction_delta)
if err > 0.0:
lambda_fr = compute_contact_constraint_delta(
err, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, -perp, perp, angular_a, angular_b, 1.0, dt
)
# limit friction based on incremental normal force, good approximation to limiting on total force
lambda_fr = wp.max(lambda_fr, -lambda_n * mu)
lin_delta_a -= perp * lambda_fr
lin_delta_b += perp * lambda_fr
ang_delta_a += angular_a * lambda_fr
ang_delta_b += angular_b * lambda_fr
torsional_friction = mu * contact_torsional_friction
delta_omega = omega_b - omega_a
if torsional_friction > 0.0:
err = wp.dot(delta_omega, n) * dt
if wp.abs(err) > 0.0:
lin = wp.vec3(0.0)
lambda_torsion = compute_contact_constraint_delta(
err, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, lin, lin, -n, n, 1.0, dt
)
lambda_torsion = wp.clamp(lambda_torsion, -lambda_n * torsional_friction, lambda_n * torsional_friction)
ang_delta_a -= n * lambda_torsion
ang_delta_b += n * lambda_torsion
rolling_friction = mu * contact_rolling_friction
if rolling_friction > 0.0:
delta_omega -= wp.dot(n, delta_omega) * n
err = wp.length(delta_omega) * dt
if err > 0.0:
lin = wp.vec3(0.0)
roll_n = wp.normalize(delta_omega)
lambda_roll = compute_contact_constraint_delta(
err, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, lin, lin, -roll_n, roll_n, 1.0, dt
)
lambda_roll = wp.max(lambda_roll, -lambda_n * rolling_friction)
ang_delta_a -= roll_n * lambda_roll
ang_delta_b += roll_n * lambda_roll
if body_a >= 0:
wp.atomic_add(deltas, body_a, wp.spatial_vector(ang_delta_a, lin_delta_a))
if body_b >= 0:
wp.atomic_add(deltas, body_b, wp.spatial_vector(ang_delta_b, lin_delta_b))
@wp.kernel
def update_body_velocities(
poses: wp.array(dtype=wp.transform),
poses_prev: wp.array(dtype=wp.transform),
body_com: wp.array(dtype=wp.vec3),
dt: float,
qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
pose = poses[tid]
pose_prev = poses_prev[tid]
x = wp.transform_get_translation(pose)
x_prev = wp.transform_get_translation(pose_prev)
q = wp.transform_get_rotation(pose)
q_prev = wp.transform_get_rotation(pose_prev)
# Update body velocities according to Alg. 2
# XXX we consider the body COM as the origin of the body frame
x_com = x + wp.quat_rotate(q, body_com[tid])
x_com_prev = x_prev + wp.quat_rotate(q_prev, body_com[tid])
# XXX consider the velocity of the COM
v = (x_com - x_com_prev) / dt
dq = q * wp.quat_inverse(q_prev)
omega = 2.0 / dt * wp.vec3(dq[0], dq[1], dq[2])
if dq[3] < 0.0:
omega = -omega
qd_out[tid] = wp.spatial_vector(omega, v)
@wp.kernel
def apply_rigid_restitution(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_q_prev: wp.array(dtype=wp.transform),
body_qd_prev: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
contact_count: wp.array(dtype=int),
contact_body0: wp.array(dtype=int),
contact_body1: wp.array(dtype=int),
contact_normal: wp.array(dtype=wp.vec3),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
active_contact_distance: wp.array(dtype=float),
active_contact_point0: wp.array(dtype=wp.vec3),
active_contact_point1: wp.array(dtype=wp.vec3),
contact_inv_weight: wp.array(dtype=float),
gravity: wp.vec3,
dt: float,
# outputs
deltas: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
count = contact_count[0]
if tid >= count:
return
d = active_contact_distance[tid]
if d >= 0.0:
return
# use average contact material properties
mat_nonzero = 0
restitution = 0.0
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a >= 0:
mat_nonzero += 1
restitution += shape_materials.restitution[shape_a]
if shape_b >= 0:
mat_nonzero += 1
restitution += shape_materials.restitution[shape_b]
if mat_nonzero > 0:
restitution /= float(mat_nonzero)
body_a = contact_body0[tid]
body_b = contact_body1[tid]
m_inv_a = 0.0
m_inv_b = 0.0
I_inv_a = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
I_inv_b = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
# body to world transform
X_wb_a_prev = wp.transform_identity()
X_wb_b_prev = wp.transform_identity()
# center of mass in body frame
com_a = wp.vec3(0.0)
com_b = wp.vec3(0.0)
# previous velocity at contact points
v_a = wp.vec3(0.0)
v_b = wp.vec3(0.0)
# new velocity at contact points
v_a_new = wp.vec3(0.0)
v_b_new = wp.vec3(0.0)
# inverse mass used to compute the impulse
inv_mass = 0.0
if body_a >= 0:
X_wb_a_prev = body_q_prev[body_a]
X_wb_a = body_q[body_a]
m_inv_a = body_m_inv[body_a]
I_inv_a = body_I_inv[body_a]
com_a = body_com[body_a]
if body_b >= 0:
X_wb_b_prev = body_q_prev[body_b]
X_wb_b = body_q[body_b]
m_inv_b = body_m_inv[body_b]
I_inv_b = body_I_inv[body_b]
com_b = body_com[body_b]
bx_a = active_contact_point0[tid]
bx_b = active_contact_point1[tid]
r_a = bx_a - wp.transform_point(X_wb_a, com_a)
r_b = bx_b - wp.transform_point(X_wb_b, com_b)
n = contact_normal[tid]
if body_a >= 0:
v_a = velocity_at_point(body_qd_prev[body_a], r_a) + gravity * dt
v_a_new = velocity_at_point(body_qd[body_a], r_a)
q_a = wp.transform_get_rotation(X_wb_a_prev)
rxn = wp.quat_rotate_inv(q_a, wp.cross(r_a, n))
# Eq. 2
inv_mass_a = m_inv_a + wp.dot(rxn, I_inv_a * rxn)
# if (contact_inv_weight):
# if (contact_inv_weight[body_a] > 0.0):
# inv_mass_a *= contact_inv_weight[body_a]
inv_mass += inv_mass_a
# inv_mass += m_inv_a + wp.dot(rxn, I_inv_a * rxn)
if body_b >= 0:
v_b = velocity_at_point(body_qd_prev[body_b], r_b) + gravity * dt
v_b_new = velocity_at_point(body_qd[body_b], r_b)
q_b = wp.transform_get_rotation(X_wb_b_prev)
rxn = wp.quat_rotate_inv(q_b, wp.cross(r_b, n))
# Eq. 3
inv_mass_b = m_inv_b + wp.dot(rxn, I_inv_b * rxn)
# if (contact_inv_weight):
# if (contact_inv_weight[body_b] > 0.0):
# inv_mass_b *= contact_inv_weight[body_b]
inv_mass += inv_mass_b
# inv_mass += m_inv_b + wp.dot(rxn, I_inv_b * rxn)
if inv_mass == 0.0:
return
# Eq. 29
rel_vel_old = wp.dot(n, v_a - v_b)
rel_vel_new = wp.dot(n, v_a_new - v_b_new)
# Eq. 34 (Eq. 33 from the ACM paper, note the max operation)
dv = n * (-rel_vel_new + wp.max(-restitution * rel_vel_old, 0.0))
# Eq. 33
p = dv / inv_mass
if body_a >= 0:
p_a = p
if contact_inv_weight:
if contact_inv_weight[body_a] > 0.0:
p_a /= contact_inv_weight[body_a]
q_a = wp.transform_get_rotation(X_wb_a)
rxp = wp.quat_rotate_inv(q_a, wp.cross(r_a, p_a))
dq = wp.quat_rotate(q_a, I_inv_a * rxp)
wp.atomic_add(deltas, body_a, wp.spatial_vector(dq, p_a * m_inv_a))
if body_b >= 0:
p_b = p
if contact_inv_weight:
if contact_inv_weight[body_b] > 0.0:
p_b /= contact_inv_weight[body_b]
q_b = wp.transform_get_rotation(X_wb_b)
rxp = wp.quat_rotate_inv(q_b, wp.cross(r_b, p_b))
dq = wp.quat_rotate(q_b, I_inv_b * rxp)
wp.atomic_sub(deltas, body_b, wp.spatial_vector(dq, p_b * m_inv_b))
class XPBDIntegrator:
"""A implicit integrator using XPBD
After constructing `Model` and `State` objects this time-integrator
may be used to advance the simulation state forward in time.
Example
-------
.. code-block:: python
integrator = wp.SemiImplicitIntegrator()
# simulation loop
for i in range(100):
state = integrator.simulate(model, state_in, state_out, dt)
"""
def __init__(
self,
iterations=2,
soft_body_relaxation=0.9,
soft_contact_relaxation=0.9,
joint_linear_relaxation=0.7,
joint_angular_relaxation=0.4,
rigid_contact_relaxation=0.8,
rigid_contact_con_weighting=True,
angular_damping=0.0,
enable_restitution=False,
):
self.iterations = iterations
self.soft_body_relaxation = soft_body_relaxation
self.soft_contact_relaxation = soft_contact_relaxation
self.joint_linear_relaxation = joint_linear_relaxation
self.joint_angular_relaxation = joint_angular_relaxation
self.rigid_contact_relaxation = rigid_contact_relaxation
self.rigid_contact_con_weighting = rigid_contact_con_weighting
self.angular_damping = angular_damping
self.enable_restitution = enable_restitution
def simulate(self, model, state_in, state_out, dt, requires_grad=False):
with wp.ScopedTimer("simulate", False):
particle_q = None
particle_qd = None
if model.particle_count:
if requires_grad:
particle_q = wp.zeros_like(state_in.particle_q)
particle_qd = wp.zeros_like(state_in.particle_qd)
else:
particle_q = state_out.particle_q
particle_qd = state_out.particle_qd
wp.launch(
kernel=integrate_particles,
dim=model.particle_count,
inputs=[
state_in.particle_q,
state_in.particle_qd,
state_in.particle_f,
model.particle_inv_mass,
model.particle_flags,
model.gravity,
dt,
model.particle_max_velocity,
],
outputs=[particle_q, particle_qd],
device=model.device,
)
if model.body_count:
if model.joint_count:
wp.launch(
kernel=apply_joint_torques,
dim=model.joint_count,
inputs=[
state_in.body_q,
model.body_com,
model.joint_q_start,
model.joint_qd_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_axis,
model.joint_act,
],
outputs=[state_in.body_f],
device=model.device,
)
wp.launch(
kernel=integrate_bodies,
dim=model.body_count,
inputs=[
state_in.body_q,
state_in.body_qd,
state_in.body_f,
model.body_com,
model.body_mass,
model.body_inertia,
model.body_inv_mass,
model.body_inv_inertia,
model.gravity,
self.angular_damping,
dt,
],
outputs=[state_out.body_q, state_out.body_qd],
device=model.device,
)
if model.spring_count:
model.spring_constraint_lambdas.zero_()
if model.edge_count:
model.edge_constraint_lambdas.zero_()
for i in range(self.iterations):
# print(f"### iteration {i} / {self.iterations-1}")
if model.body_count:
if requires_grad:
out_body_q = wp.clone(state_out.body_q)
out_body_qd = wp.clone(state_out.body_qd)
state_out.body_deltas = wp.zeros_like(state_out.body_deltas)
else:
out_body_q = state_out.body_q
out_body_qd = state_out.body_qd
state_out.body_deltas.zero_()
else:
out_body_q = None
out_body_qd = None
# ----------------------------
# handle particles
if model.particle_count:
if requires_grad:
deltas = wp.zeros_like(state_out.particle_f)
else:
deltas = state_out.particle_f
deltas.zero_()
# particle ground contact
if model.ground:
wp.launch(
kernel=solve_particle_ground_contacts,
dim=model.particle_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
model.soft_contact_ke,
model.soft_contact_kd,
model.soft_contact_kf,
model.soft_contact_mu,
model.ground_plane,
dt,
self.soft_contact_relaxation,
],
outputs=[deltas],
device=model.device,
)
# particle - rigid body contacts (besides ground plane)
if model.shape_count > 1:
wp.launch(
kernel=solve_particle_shape_contacts,
dim=model.soft_contact_max,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
out_body_q,
out_body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.shape_body,
model.shape_materials,
model.soft_contact_mu,
model.particle_adhesion,
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
model.soft_contact_max,
dt,
self.soft_contact_relaxation,
],
# outputs
outputs=[deltas, state_out.body_deltas],
device=model.device,
)
if model.particle_max_radius > 0.0:
wp.launch(
kernel=solve_particle_particle_contacts,
dim=model.particle_count,
inputs=[
model.particle_grid.id,
particle_q,
particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
model.particle_mu,
model.particle_cohesion,
model.particle_max_radius,
dt,
self.soft_contact_relaxation,
],
outputs=[deltas],
device=model.device,
)
# distance constraints
if model.spring_count:
wp.launch(
kernel=solve_springs,
dim=model.spring_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.spring_indices,
model.spring_rest_length,
model.spring_stiffness,
model.spring_damping,
dt,
model.spring_constraint_lambdas,
],
outputs=[deltas],
device=model.device,
)
# bending constraints
if model.edge_count:
wp.launch(
kernel=bending_constraint,
dim=model.edge_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.edge_indices,
model.edge_rest_angle,
model.edge_bending_properties,
dt,
model.edge_constraint_lambdas,
],
outputs=[deltas],
device=model.device,
)
# tetrahedral FEM
if model.tet_count:
wp.launch(
kernel=solve_tetrahedra,
dim=model.tet_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.tet_indices,
model.tet_poses,
model.tet_activations,
model.tet_materials,
dt,
self.soft_body_relaxation,
],
outputs=[deltas],
device=model.device,
)
# apply particle deltas
if requires_grad:
new_particle_q = wp.clone(particle_q)
new_particle_qd = wp.clone(particle_qd)
else:
new_particle_q = particle_q
new_particle_qd = particle_qd
wp.launch(
kernel=apply_particle_deltas,
dim=model.particle_count,
inputs=[
state_in.particle_q,
particle_q,
model.particle_flags,
deltas,
dt,
model.particle_max_velocity,
],
outputs=[new_particle_q, new_particle_qd],
device=model.device,
)
if requires_grad:
particle_q.assign(new_particle_q)
particle_qd.assign(new_particle_qd)
else:
particle_q = new_particle_q
particle_qd = new_particle_qd
# handle rigid bodies
# ----------------------------
if model.joint_count:
wp.launch(
kernel=solve_body_joints,
dim=model.joint_count,
inputs=[
state_out.body_q,
state_out.body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.joint_type,
model.joint_enabled,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_limit_lower,
model.joint_limit_upper,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_axis_mode,
model.joint_axis,
model.joint_target,
model.joint_target_ke,
model.joint_target_kd,
model.joint_linear_compliance,
model.joint_angular_compliance,
self.joint_angular_relaxation,
self.joint_linear_relaxation,
dt,
],
outputs=[state_out.body_deltas],
device=model.device,
)
# apply updates
wp.launch(
kernel=apply_body_deltas,
dim=model.body_count,
inputs=[
state_out.body_q,
state_out.body_qd,
model.body_com,
model.body_inertia,
model.body_inv_mass,
model.body_inv_inertia,
state_out.body_deltas,
None,
dt,
],
outputs=[
out_body_q,
out_body_qd,
],
device=model.device,
)
if model.body_count and requires_grad:
# update state
state_out.body_q.assign(out_body_q)
state_out.body_qd.assign(out_body_qd)
# Solve rigid contact constraints
if model.rigid_contact_max and (
model.ground and model.shape_ground_contact_pair_count or model.shape_contact_pair_count
):
rigid_contact_inv_weight = None
if requires_grad:
body_deltas = wp.zeros_like(state_out.body_deltas)
rigid_active_contact_distance = wp.zeros_like(model.rigid_active_contact_distance)
rigid_active_contact_point0 = wp.empty_like(
model.rigid_active_contact_point0, requires_grad=True
)
rigid_active_contact_point1 = wp.empty_like(
model.rigid_active_contact_point1, requires_grad=True
)
if self.rigid_contact_con_weighting:
rigid_contact_inv_weight = wp.zeros_like(model.rigid_contact_inv_weight)
else:
body_deltas = state_out.body_deltas
body_deltas.zero_()
rigid_active_contact_distance = model.rigid_active_contact_distance
rigid_active_contact_point0 = model.rigid_active_contact_point0
rigid_active_contact_point1 = model.rigid_active_contact_point1
rigid_active_contact_distance.zero_()
if self.rigid_contact_con_weighting:
rigid_contact_inv_weight = model.rigid_contact_inv_weight
rigid_contact_inv_weight.zero_()
wp.launch(
kernel=solve_body_contact_positions,
dim=model.rigid_contact_max,
inputs=[
state_out.body_q,
state_out.body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.rigid_contact_count,
model.rigid_contact_body0,
model.rigid_contact_body1,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_offset0,
model.rigid_contact_offset1,
model.rigid_contact_normal,
model.rigid_contact_thickness,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.shape_materials,
self.rigid_contact_relaxation,
dt,
model.rigid_contact_torsional_friction,
model.rigid_contact_rolling_friction,
],
outputs=[
body_deltas,
rigid_active_contact_point0,
rigid_active_contact_point1,
rigid_active_contact_distance,
rigid_contact_inv_weight,
],
device=model.device,
)
if self.enable_restitution and i == 0:
# remember the contacts from the first iteration
if requires_grad:
model.rigid_active_contact_distance_prev = wp.clone(rigid_active_contact_distance)
model.rigid_active_contact_point0_prev = wp.clone(rigid_active_contact_point0)
model.rigid_active_contact_point1_prev = wp.clone(rigid_active_contact_point1)
if self.rigid_contact_con_weighting:
model.rigid_contact_inv_weight_prev = wp.clone(rigid_contact_inv_weight)
else:
model.rigid_contact_inv_weight_prev = None
else:
model.rigid_active_contact_distance_prev.assign(rigid_active_contact_distance)
model.rigid_active_contact_point0_prev.assign(rigid_active_contact_point0)
model.rigid_active_contact_point1_prev.assign(rigid_active_contact_point1)
if self.rigid_contact_con_weighting:
model.rigid_contact_inv_weight_prev.assign(rigid_contact_inv_weight)
else:
model.rigid_contact_inv_weight_prev = None
if requires_grad:
model.rigid_active_contact_distance = rigid_active_contact_distance
model.rigid_active_contact_point0 = rigid_active_contact_point0
model.rigid_active_contact_point1 = rigid_active_contact_point1
body_q = wp.clone(state_out.body_q)
body_qd = wp.clone(state_out.body_qd)
else:
body_q = state_out.body_q
body_qd = state_out.body_qd
# apply updates
wp.launch(
kernel=apply_body_deltas,
dim=model.body_count,
inputs=[
state_out.body_q,
state_out.body_qd,
model.body_com,
model.body_inertia,
model.body_inv_mass,
model.body_inv_inertia,
body_deltas,
rigid_contact_inv_weight,
dt,
],
outputs=[
body_q,
body_qd,
],
device=model.device,
)
if requires_grad:
state_out.body_q = body_q
state_out.body_qd = body_qd
# update body velocities from position changes
if model.body_count and not requires_grad:
# causes gradient issues (probably due to numerical problems
# when computing velocities from position changes)
if requires_grad:
out_body_qd = wp.clone(state_out.body_qd)
else:
out_body_qd = state_out.body_qd
# update body velocities
wp.launch(
kernel=update_body_velocities,
dim=model.body_count,
inputs=[state_out.body_q, state_in.body_q, model.body_com, dt],
outputs=[out_body_qd],
device=model.device,
)
if requires_grad:
state_out.body_qd.assign(out_body_qd)
if self.enable_restitution:
if model.particle_count:
if requires_grad:
new_particle_qd = wp.clone(particle_qd)
else:
new_particle_qd = particle_qd
wp.launch(
kernel=apply_soft_restitution_ground,
dim=model.particle_count,
inputs=[
particle_q,
particle_qd,
state_in.particle_q,
state_in.particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
model.soft_contact_restitution,
model.ground_plane,
dt,
self.soft_contact_relaxation,
],
outputs=[new_particle_qd],
device=model.device,
)
if requires_grad:
particle_qd.assign(new_particle_qd)
else:
particle_qd = new_particle_qd
if model.body_count:
if requires_grad:
state_out.body_deltas = wp.zeros_like(state_out.body_deltas)
else:
state_out.body_deltas.zero_()
wp.launch(
kernel=apply_rigid_restitution,
dim=model.rigid_contact_max,
inputs=[
state_out.body_q,
state_out.body_qd,
state_in.body_q,
state_in.body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.rigid_contact_count,
model.rigid_contact_body0,
model.rigid_contact_body1,
model.rigid_contact_normal,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.shape_materials,
model.rigid_active_contact_distance_prev,
model.rigid_active_contact_point0_prev,
model.rigid_active_contact_point1_prev,
model.rigid_contact_inv_weight_prev,
model.gravity,
dt,
],
outputs=[
state_out.body_deltas,
],
device=model.device,
)
wp.launch(
kernel=apply_body_delta_velocities,
dim=model.body_count,
inputs=[
state_out.body_qd,
state_out.body_deltas,
],
outputs=[state_out.body_qd],
device=model.device,
)
if model.particle_count:
# update particle state
state_out.particle_q.assign(particle_q)
state_out.particle_qd.assign(particle_qd)
return state_out
| warp-main | warp/sim/integrator_xpbd.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.
"""Helper functions for computing rigid body inertia properties.
"""
import warp as wp
import numpy as np
import math
from typing import List, Union
@wp.func
def triangle_inertia(
p: wp.vec3,
q: wp.vec3,
r: wp.vec3,
density: float,
com: wp.vec3,
# outputs
mass: wp.array(dtype=float, ndim=1),
inertia: wp.array(dtype=wp.mat33, ndim=1),
):
pcom = p - com
qcom = q - com
rcom = r - com
Dm = wp.mat33(pcom[0], qcom[0], rcom[0], pcom[1], qcom[1], rcom[1], pcom[2], qcom[2], rcom[2])
volume = wp.determinant(Dm) / 6.0
# accumulate mass
wp.atomic_add(mass, 0, 4.0 * density * volume)
alpha = wp.sqrt(5.0) / 5.0
mid = (com + p + q + r) / 4.0
off_mid = mid - com
# displacement of quadrature point from COM
d0 = alpha * (p - mid) + off_mid
d1 = alpha * (q - mid) + off_mid
d2 = alpha * (r - mid) + off_mid
d3 = alpha * (com - mid) + off_mid
# accumulate inertia
identity = wp.mat33(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
I = wp.dot(d0, d0) * identity - wp.outer(d0, d0)
I += wp.dot(d1, d1) * identity - wp.outer(d1, d1)
I += wp.dot(d2, d2) * identity - wp.outer(d2, d2)
I += wp.dot(d3, d3) * identity - wp.outer(d3, d3)
wp.atomic_add(inertia, 0, (density * volume) * I)
return volume
@wp.kernel
def compute_solid_mesh_inertia(
# inputs
com: wp.vec3,
weight: float,
indices: wp.array(dtype=int, ndim=1),
vertices: wp.array(dtype=wp.vec3, ndim=1),
# outputs
mass: wp.array(dtype=float, ndim=1),
inertia: wp.array(dtype=wp.mat33, ndim=1),
volume: wp.array(dtype=float, ndim=1),
):
i = wp.tid()
p = vertices[indices[i * 3 + 0]]
q = vertices[indices[i * 3 + 1]]
r = vertices[indices[i * 3 + 2]]
vol = triangle_inertia(p, q, r, weight, com, mass, inertia)
wp.atomic_add(volume, 0, vol)
@wp.kernel
def compute_hollow_mesh_inertia(
# inputs
com: wp.vec3,
density: float,
indices: wp.array(dtype=int, ndim=1),
vertices: wp.array(dtype=wp.vec3, ndim=1),
thickness: wp.array(dtype=float, ndim=1),
# outputs
mass: wp.array(dtype=float, ndim=1),
inertia: wp.array(dtype=wp.mat33, ndim=1),
volume: wp.array(dtype=float, ndim=1),
):
tid = wp.tid()
i = indices[tid * 3 + 0]
j = indices[tid * 3 + 1]
k = indices[tid * 3 + 2]
vi = vertices[i]
vj = vertices[j]
vk = vertices[k]
normal = -wp.normalize(wp.cross(vj - vi, vk - vi))
ti = normal * thickness[i]
tj = normal * thickness[j]
tk = normal * thickness[k]
# wedge vertices
vi0 = vi - ti
vi1 = vi + ti
vj0 = vj - tj
vj1 = vj + tj
vk0 = vk - tk
vk1 = vk + tk
triangle_inertia(vi0, vj0, vk0, density, com, mass, inertia)
triangle_inertia(vj0, vk1, vk0, density, com, mass, inertia)
triangle_inertia(vj0, vj1, vk1, density, com, mass, inertia)
triangle_inertia(vj0, vi1, vj1, density, com, mass, inertia)
triangle_inertia(vj0, vi0, vi1, density, com, mass, inertia)
triangle_inertia(vj1, vi1, vk1, density, com, mass, inertia)
triangle_inertia(vi1, vi0, vk0, density, com, mass, inertia)
triangle_inertia(vi1, vk0, vk1, density, com, mass, inertia)
# compute volume
a = wp.length(wp.cross(vj - vi, vk - vi)) * 0.5
vol = a * (thickness[i] + thickness[j] + thickness[k]) / 3.0
wp.atomic_add(volume, 0, vol)
def compute_sphere_inertia(density: float, r: float) -> tuple:
"""Helper to compute mass and inertia of a solid sphere
Args:
density: The sphere density
r: The sphere radius
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
v = 4.0 / 3.0 * math.pi * r * r * r
m = density * v
Ia = 2.0 / 5.0 * m * r * r
I = np.array([[Ia, 0.0, 0.0], [0.0, Ia, 0.0], [0.0, 0.0, Ia]])
return (m, np.zeros(3), I)
def compute_capsule_inertia(density: float, r: float, h: float) -> tuple:
"""Helper to compute mass and inertia of a solid capsule extending along the y-axis
Args:
density: The capsule density
r: The capsule radius
h: The capsule height (full height of the interior cylinder)
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
ms = density * (4.0 / 3.0) * math.pi * r * r * r
mc = density * math.pi * r * r * h
# total mass
m = ms + mc
# adapted from ODE
Ia = mc * (0.25 * r * r + (1.0 / 12.0) * h * h) + ms * (0.4 * r * r + 0.375 * r * h + 0.25 * h * h)
Ib = (mc * 0.5 + ms * 0.4) * r * r
I = np.array([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ia]])
return (m, np.zeros(3), I)
def compute_cylinder_inertia(density: float, r: float, h: float) -> tuple:
"""Helper to compute mass and inertia of a solid cylinder extending along the y-axis
Args:
density: The cylinder density
r: The cylinder radius
h: The cylinder height (extent along the y-axis)
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
m = density * math.pi * r * r * h
Ia = 1 / 12 * m * (3 * r * r + h * h)
Ib = 1 / 2 * m * r * r
I = np.array([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ia]])
return (m, np.zeros(3), I)
def compute_cone_inertia(density: float, r: float, h: float) -> tuple:
"""Helper to compute mass and inertia of a solid cone extending along the y-axis
Args:
density: The cone density
r: The cone radius
h: The cone height (extent along the y-axis)
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
m = density * math.pi * r * r * h / 3.0
Ia = 1 / 20 * m * (3 * r * r + 2 * h * h)
Ib = 3 / 10 * m * r * r
I = np.array([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ia]])
return (m, np.zeros(3), I)
def compute_box_inertia(density: float, w: float, h: float, d: float) -> tuple:
"""Helper to compute mass and inertia of a solid box
Args:
density: The box density
w: The box width along the x-axis
h: The box height along the y-axis
d: The box depth along the z-axis
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
v = w * h * d
m = density * v
Ia = 1.0 / 12.0 * m * (h * h + d * d)
Ib = 1.0 / 12.0 * m * (w * w + d * d)
Ic = 1.0 / 12.0 * m * (w * w + h * h)
I = np.array([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ic]])
return (m, np.zeros(3), I)
def compute_mesh_inertia(
density: float, vertices: list, indices: list, is_solid: bool = True, thickness: Union[List[float], float] = 0.001
) -> tuple:
"""Computes mass, center of mass, 3x3 inertia matrix, and volume for a mesh."""
com = np.mean(vertices, 0)
com_warp = wp.vec3(com[0], com[1], com[2])
num_tris = len(indices) // 3
# compute signed inertia for each tetrahedron
# formed with the interior point, using an order-2
# quadrature: https://www.sciencedirect.com/science/article/pii/S0377042712001604#br000040
# Allocating for mass and inertia
I_warp = wp.zeros(1, dtype=wp.mat33)
mass_warp = wp.zeros(1, dtype=float)
vol_warp = wp.zeros(1, dtype=float)
if is_solid:
weight = 0.25
alpha = math.sqrt(5.0) / 5.0
wp.launch(
kernel=compute_solid_mesh_inertia,
dim=num_tris,
inputs=[
com_warp,
weight,
wp.array(indices, dtype=int),
wp.array(vertices, dtype=wp.vec3),
],
outputs=[mass_warp, I_warp, vol_warp],
)
else:
weight = 0.25 * density
if isinstance(thickness, float):
thickness = [thickness] * len(vertices)
wp.launch(
kernel=compute_hollow_mesh_inertia,
dim=num_tris,
inputs=[
com_warp,
weight,
wp.array(indices, dtype=int),
wp.array(vertices, dtype=wp.vec3),
wp.array(thickness, dtype=float),
],
outputs=[mass_warp, I_warp, vol_warp],
)
# Extract mass and inertia and save to class attributes.
mass = mass_warp.numpy()[0] * density
I = I_warp.numpy()[0] * density
volume = vol_warp.numpy()[0]
return mass, com, I, volume
def transform_inertia(m, I, p, q):
R = np.array(wp.quat_to_matrix(q)).reshape(3, 3)
# Steiner's theorem
return R @ I @ R.T + m * (np.dot(p, p) * np.eye(3) - np.outer(p, p))
| warp-main | warp/sim/inertia.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 .model import State, Model, ModelBuilder, Mesh, SDF
from .model import GEO_SPHERE
from .model import GEO_BOX
from .model import GEO_CAPSULE
from .model import GEO_CYLINDER
from .model import GEO_CONE
from .model import GEO_MESH
from .model import GEO_SDF
from .model import GEO_PLANE
from .model import GEO_NONE
from .model import ModelShapeGeometry
from .model import JOINT_MODE_LIMIT
from .model import JOINT_MODE_TARGET_POSITION
from .model import JOINT_MODE_TARGET_VELOCITY
from .model import JointAxis
from .model import ModelShapeMaterials
from .model import JOINT_PRISMATIC
from .model import JOINT_REVOLUTE
from .model import JOINT_BALL
from .model import JOINT_FIXED
from .model import JOINT_FREE
from .model import JOINT_COMPOUND
from .model import JOINT_UNIVERSAL
from .model import JOINT_DISTANCE
from .model import JOINT_D6
from .integrator_euler import SemiImplicitIntegrator
from .integrator_euler import VariationalImplicitIntegrator
from .integrator_xpbd import XPBDIntegrator
from .collide import collide
from .articulation import eval_fk, eval_ik
from .import_mjcf import parse_mjcf
from .import_urdf import parse_urdf
from .import_snu import parse_snu
from .import_usd import parse_usd
| warp-main | warp/sim/__init__.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 os
import xml.etree.ElementTree as ET
from typing import Union
import numpy as np
import warp as wp
from warp.sim.model import Mesh
def parse_urdf(
urdf_filename,
builder,
xform=wp.transform(),
floating=False,
base_joint: Union[dict, str] = None,
density=1000.0,
stiffness=100.0,
damping=10.0,
armature=0.0,
shape_ke=1.0e4,
shape_kd=1.0e3,
shape_kf=1.0e2,
shape_mu=0.25,
shape_restitution=0.5,
shape_thickness=0.0,
limit_ke=100.0,
limit_kd=10.0,
scale=1.0,
parse_visuals_as_colliders=False,
enable_self_collisions=True,
ignore_inertial_definitions=True,
ensure_nonstatic_links=True,
static_link_mass=1e-2,
collapse_fixed_joints=False,
):
"""
Parses a URDF file and adds the bodies and joints to the given ModelBuilder.
Args:
urdf_filename (str): The filename of the URDF file to parse.
builder (ModelBuilder): The :class:`ModelBuilder` to add the bodies and joints to.
xform (wp.transform): The transform to apply to the root body.
floating (bool): If True, the root body is a free joint. If False, the root body is connected via a fixed joint to the world, unless a `base_joint` is defined.
base_joint (Union[str, dict]): The joint by which the root body is connected to the world. This can be either a string defining the joint axes of a D6 joint with comma-separated positional and angular axis names (e.g. "px,py,rz" for a D6 joint with linear axes in x, y and an angular axis in z) or a dict with joint parameters (see :meth:`ModelBuilder.add_joint`).
density (float): The density of the shapes in kg/m^3 which will be used to calculate the body mass and inertia.
stiffness (float): The stiffness of the joints.
damping (float): The damping of the joints.
armature (float): The armature of the joints (bias to add to the inertia diagonals that may stabilize the simulation).
shape_ke (float): The stiffness of the shape contacts (used by SemiImplicitIntegrator).
shape_kd (float): The damping of the shape contacts (used by SemiImplicitIntegrator).
shape_kf (float): The friction stiffness of the shape contacts (used by SemiImplicitIntegrator).
shape_mu (float): The friction coefficient of the shape contacts.
shape_restitution (float): The restitution coefficient of the shape contacts.
shape_thickness (float): The thickness to add to the shape geometry.
limit_ke (float): The stiffness of the joint limits (used by SemiImplicitIntegrator).
limit_kd (float): The damping of the joint limits (used by SemiImplicitIntegrator).
scale (float): The scaling factor to apply to the imported mechanism.
parse_visuals_as_colliders (bool): If True, the geometry defined under the `<visual>` tags is used for collision handling instead of the `<collision>` geoemtries.
enable_self_collisions (bool): If True, self-collisions are enabled.
ignore_inertial_definitions (bool): If True, the inertial parameters defined in the URDF are ignored and the inertia is calculated from the shape geometry.
ensure_nonstatic_links (bool): If True, links with zero mass are given a small mass (see `static_link_mass`) to ensure they are dynamic.
static_link_mass (float): The mass to assign to links with zero mass (if `ensure_nonstatic_links` is set to True).
collapse_fixed_joints (bool): If True, fixed joints are removed and the respective bodies are merged.
"""
file = ET.parse(urdf_filename)
root = file.getroot()
def parse_transform(element):
if element is None or element.find("origin") is None:
return wp.transform()
origin = element.find("origin")
xyz = origin.get("xyz") or "0 0 0"
rpy = origin.get("rpy") or "0 0 0"
xyz = [float(x) * scale for x in xyz.split()]
rpy = [float(x) for x in rpy.split()]
return wp.transform(xyz, wp.quat_rpy(*rpy))
def parse_shapes(link, collisions, density, incoming_xform=None):
# add geometry
for collision in collisions:
geo = collision.find("geometry")
if geo is None:
continue
tf = parse_transform(collision)
if incoming_xform is not None:
tf = incoming_xform * tf
for box in geo.findall("box"):
size = box.get("size") or "1 1 1"
size = [float(x) for x in size.split()]
builder.add_shape_box(
body=link,
pos=tf.p,
rot=tf.q,
hx=size[0] * 0.5 * scale,
hy=size[1] * 0.5 * scale,
hz=size[2] * 0.5 * scale,
density=density,
ke=shape_ke,
kd=shape_kd,
kf=shape_kf,
mu=shape_mu,
restitution=shape_restitution,
thickness=shape_thickness,
)
for sphere in geo.findall("sphere"):
builder.add_shape_sphere(
body=link,
pos=tf.p,
rot=tf.q,
radius=float(sphere.get("radius") or "1") * scale,
density=density,
ke=shape_ke,
kd=shape_kd,
kf=shape_kf,
mu=shape_mu,
restitution=shape_restitution,
thickness=shape_thickness,
)
for cylinder in geo.findall("cylinder"):
builder.add_shape_capsule(
body=link,
pos=tf.p,
rot=tf.q,
radius=float(cylinder.get("radius") or "1") * scale,
half_height=float(cylinder.get("length") or "1") * 0.5 * scale,
density=density,
ke=shape_ke,
kd=shape_kd,
kf=shape_kf,
mu=shape_mu,
up_axis=2, # cylinders in URDF are aligned with z-axis
restitution=shape_restitution,
thickness=shape_thickness,
)
for mesh in geo.findall("mesh"):
filename = mesh.get("filename")
if filename is None:
continue
if filename.startswith("http://") or filename.startswith("https://"):
# download mesh
import shutil
import tempfile
import requests
with tempfile.TemporaryDirectory() as tmpdir:
# get filename extension
extension = os.path.splitext(filename)[1]
tmpfile = os.path.join(tmpdir, "mesh" + extension)
with requests.get(filename, stream=True) as r:
with open(tmpfile, "wb") as f:
shutil.copyfileobj(r.raw, f)
filename = tmpfile
else:
filename = os.path.join(os.path.dirname(urdf_filename), filename)
if not os.path.exists(filename):
wp.utils.warn(f"Warning: mesh file {filename} does not exist")
continue
import trimesh
m = trimesh.load_mesh(filename)
scaling = mesh.get("scale") or "1 1 1"
scaling = np.array([float(x) * scale for x in scaling.split()])
if hasattr(m, "geometry"):
# multiple meshes are contained in a scene
for geom in m.geometry.values():
vertices = np.array(geom.vertices, dtype=np.float32) * scaling
faces = np.array(geom.faces, dtype=np.int32)
mesh = Mesh(vertices, faces)
builder.add_shape_mesh(
body=link,
pos=tf.p,
rot=tf.q,
mesh=mesh,
density=density,
ke=shape_ke,
kd=shape_kd,
kf=shape_kf,
mu=shape_mu,
restitution=shape_restitution,
thickness=shape_thickness,
)
else:
# a single mesh
vertices = np.array(m.vertices, dtype=np.float32) * scaling
faces = np.array(m.faces, dtype=np.int32)
mesh = Mesh(vertices, faces)
builder.add_shape_mesh(
body=link,
pos=tf.p,
rot=tf.q,
mesh=mesh,
density=density,
ke=shape_ke,
kd=shape_kd,
kf=shape_kf,
mu=shape_mu,
restitution=shape_restitution,
thickness=shape_thickness,
)
# maps from link name -> link index
link_index = {}
builder.add_articulation()
start_shape_count = len(builder.shape_geo_type)
# add links
for i, urdf_link in enumerate(root.findall("link")):
if parse_visuals_as_colliders:
colliders = urdf_link.findall("visual")
else:
colliders = urdf_link.findall("collision")
name = urdf_link.get("name")
link = builder.add_body(origin=wp.transform_identity(), armature=armature, name=name)
# add ourselves to the index
link_index[name] = link
parse_shapes(link, colliders, density=density)
m = builder.body_mass[link]
if not ignore_inertial_definitions and urdf_link.find("inertial") is not None:
# overwrite inertial parameters if defined
inertial = urdf_link.find("inertial")
inertial_frame = parse_transform(inertial)
com = inertial_frame.p
I_m = np.zeros((3, 3))
I_m[0, 0] = float(inertial.find("inertia").get("ixx") or "0") * scale**2
I_m[1, 1] = float(inertial.find("inertia").get("iyy") or "0") * scale**2
I_m[2, 2] = float(inertial.find("inertia").get("izz") or "0") * scale**2
I_m[0, 1] = float(inertial.find("inertia").get("ixy") or "0") * scale**2
I_m[0, 2] = float(inertial.find("inertia").get("ixz") or "0") * scale**2
I_m[1, 2] = float(inertial.find("inertia").get("iyz") or "0") * scale**2
I_m[1, 0] = I_m[0, 1]
I_m[2, 0] = I_m[0, 2]
I_m[2, 1] = I_m[1, 2]
rot = wp.quat_to_matrix(inertial_frame.q)
I_m = rot @ I_m
m = float(inertial.find("mass").get("value") or "0")
builder.body_mass[link] = m
builder.body_inv_mass[link] = 1.0 / m
builder.body_com[link] = com
builder.body_inertia[link] = I_m
builder.body_inv_inertia[link] = np.linalg.inv(I_m)
if m == 0.0 and ensure_nonstatic_links:
# set the mass to something nonzero to ensure the body is dynamic
m = static_link_mass
# cube with side length 0.5
I_m = np.eye(3) * m / 12.0 * (0.5 * scale) ** 2 * 2.0
builder.body_mass[link] = m
builder.body_inv_mass[link] = 1.0 / m
builder.body_inertia[link] = I_m
builder.body_inv_inertia[link] = np.linalg.inv(I_m)
end_shape_count = len(builder.shape_geo_type)
# find joints per body
body_children = {name: [] for name in link_index.keys()}
# mapping from parent, child link names to joint
parent_child_joint = {}
joints = []
for joint in root.findall("joint"):
parent = joint.find("parent").get("link")
child = joint.find("child").get("link")
body_children[parent].append(child)
joint_data = {
"name": joint.get("name"),
"parent": parent,
"child": child,
"type": joint.get("type"),
"origin": parse_transform(joint),
"damping": damping,
"friction": 0.0,
"limit_lower": -1.0e6,
"limit_upper": 1.0e6,
}
if joint.find("axis") is not None:
joint_data["axis"] = joint.find("axis").get("xyz")
joint_data["axis"] = np.array([float(x) for x in joint_data["axis"].split()])
if joint.find("dynamics") is not None:
dynamics = joint.find("dynamics")
joint_data["damping"] = float(dynamics.get("damping") or str(damping))
joint_data["friction"] = float(dynamics.get("friction") or "0")
if joint.find("limit") is not None:
limit = joint.find("limit")
joint_data["limit_lower"] = float(limit.get("lower") or "-1e6")
joint_data["limit_upper"] = float(limit.get("upper") or "1e6")
if joint.find("mimic") is not None:
mimic = joint.find("mimic")
joint_data["mimic_joint"] = mimic.get("joint")
joint_data["mimic_multiplier"] = float(mimic.get("multiplier") or "1")
joint_data["mimic_offset"] = float(mimic.get("offset") or "0")
parent_child_joint[(parent, child)] = joint_data
joints.append(joint_data)
# topological sorting of joints because the FK solver will resolve body transforms
# in joint order and needs the parent link transform to be resolved before the child
visited = {name: False for name in link_index.keys()}
sorted_joints = []
# depth-first search
def dfs(joint):
link = joint["child"]
if visited[link]:
return
visited[link] = True
for child in body_children[link]:
if not visited[child]:
dfs(parent_child_joint[(link, child)])
sorted_joints.insert(0, joint)
# start DFS from each unvisited joint
for joint in joints:
if not visited[joint["parent"]]:
dfs(joint)
# add base joint
if len(sorted_joints) > 0:
base_link_name = sorted_joints[0]["parent"]
else:
base_link_name = next(iter(link_index.keys()))
root = link_index[base_link_name]
if base_joint is not None:
# in case of a given base joint, the position is applied first, the rotation only
# after the base joint itself to not rotate its axis
base_parent_xform = wp.transform(xform.p, wp.quat_identity())
base_child_xform = wp.transform((0.0, 0.0, 0.0), wp.quat_inverse(xform.q))
if isinstance(base_joint, str):
axes = base_joint.lower().split(",")
axes = [ax.strip() for ax in axes]
linear_axes = [ax[-1] for ax in axes if ax[0] in {"l", "p"}]
angular_axes = [ax[-1] for ax in axes if ax[0] in {"a", "r"}]
axes = {
"x": [1.0, 0.0, 0.0],
"y": [0.0, 1.0, 0.0],
"z": [0.0, 0.0, 1.0],
}
builder.add_joint_d6(
linear_axes=[wp.sim.JointAxis(axes[a]) for a in linear_axes],
angular_axes=[wp.sim.JointAxis(axes[a]) for a in angular_axes],
parent_xform=base_parent_xform,
child_xform=base_child_xform,
parent=-1,
child=root,
name="base_joint",
)
elif isinstance(base_joint, dict):
base_joint["parent"] = -1
base_joint["child"] = root
base_joint["parent_xform"] = base_parent_xform
base_joint["child_xform"] = base_child_xform
base_joint["name"] = "base_joint"
builder.add_joint(**base_joint)
else:
raise ValueError(
"base_joint must be a comma-separated string of joint axes or a dict with joint parameters"
)
elif floating:
builder.add_joint_free(root, name="floating_base")
# set dofs to transform
start = builder.joint_q_start[root]
builder.joint_q[start + 0] = xform.p[0]
builder.joint_q[start + 1] = xform.p[1]
builder.joint_q[start + 2] = xform.p[2]
builder.joint_q[start + 3] = xform.q[0]
builder.joint_q[start + 4] = xform.q[1]
builder.joint_q[start + 5] = xform.q[2]
builder.joint_q[start + 6] = xform.q[3]
else:
builder.add_joint_fixed(-1, root, parent_xform=xform, name="fixed_base")
# add joints, in topological order starting from root body
for joint in sorted_joints:
parent = link_index[joint["parent"]]
child = link_index[joint["child"]]
if child == -1:
# we skipped the insertion of the child body
continue
lower = joint["limit_lower"]
upper = joint["limit_upper"]
joint_damping = joint["damping"]
parent_xform = joint["origin"]
child_xform = wp.transform_identity()
joint_mode = wp.sim.JOINT_MODE_LIMIT
if stiffness > 0.0:
joint_mode = wp.sim.JOINT_MODE_TARGET_POSITION
joint_params = dict(
parent=parent,
child=child,
parent_xform=parent_xform,
child_xform=child_xform,
name=joint["name"],
)
if joint["type"] == "revolute" or joint["type"] == "continuous":
builder.add_joint_revolute(
axis=joint["axis"],
target_ke=stiffness,
target_kd=joint_damping,
limit_lower=lower,
limit_upper=upper,
limit_ke=limit_ke,
limit_kd=limit_kd,
mode=joint_mode,
**joint_params,
)
elif joint["type"] == "prismatic":
builder.add_joint_prismatic(
axis=joint["axis"],
target_ke=stiffness,
target_kd=joint_damping,
limit_lower=lower * scale,
limit_upper=upper * scale,
limit_ke=limit_ke,
limit_kd=limit_kd,
mode=joint_mode,
**joint_params,
)
elif joint["type"] == "fixed":
builder.add_joint_fixed(**joint_params)
elif joint["type"] == "floating":
builder.add_joint_free(**joint_params)
elif joint["type"] == "planar":
# find plane vectors perpendicular to axis
axis = np.array(joint["axis"])
axis /= np.linalg.norm(axis)
# create helper vector that is not parallel to the axis
helper = np.array([1, 0, 0]) if np.allclose(axis, [0, 1, 0]) else np.array([0, 1, 0])
u = np.cross(helper, axis)
u /= np.linalg.norm(u)
v = np.cross(axis, u)
v /= np.linalg.norm(v)
builder.add_joint_d6(
linear_axes=[
wp.sim.JointAxis(
u, limit_lower=lower * scale, limit_upper=upper * scale, limit_ke=limit_ke, limit_kd=limit_kd
),
wp.sim.JointAxis(
v, limit_lower=lower * scale, limit_upper=upper * scale, limit_ke=limit_ke, limit_kd=limit_kd
),
],
**joint_params,
)
else:
raise Exception("Unsupported joint type: " + joint["type"])
if not enable_self_collisions:
for i in range(start_shape_count, end_shape_count):
for j in range(i + 1, end_shape_count):
builder.shape_collision_filter_pairs.add((i, j))
if collapse_fixed_joints:
builder.collapse_fixed_joints()
| warp-main | warp/sim/import_urdf.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.
"""
Collision handling functions and kernels.
"""
import warp as wp
from .model import PARTICLE_FLAG_ACTIVE, ModelShapeGeometry
@wp.func
def triangle_closest_point_barycentric(a: wp.vec3, b: wp.vec3, c: wp.vec3, p: wp.vec3):
ab = b - a
ac = c - a
ap = p - a
d1 = wp.dot(ab, ap)
d2 = wp.dot(ac, ap)
if d1 <= 0.0 and d2 <= 0.0:
return wp.vec3(1.0, 0.0, 0.0)
bp = p - b
d3 = wp.dot(ab, bp)
d4 = wp.dot(ac, bp)
if d3 >= 0.0 and d4 <= d3:
return wp.vec3(0.0, 1.0, 0.0)
vc = d1 * d4 - d3 * d2
v = d1 / (d1 - d3)
if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0:
return wp.vec3(1.0 - v, v, 0.0)
cp = p - c
d5 = wp.dot(ab, cp)
d6 = wp.dot(ac, cp)
if d6 >= 0.0 and d5 <= d6:
return wp.vec3(0.0, 0.0, 1.0)
vb = d5 * d2 - d1 * d6
w = d2 / (d2 - d6)
if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0:
return wp.vec3(1.0 - w, 0.0, w)
va = d3 * d6 - d5 * d4
w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0:
return wp.vec3(0.0, w, 1.0 - w)
denom = 1.0 / (va + vb + vc)
v = vb * denom
w = vc * denom
return wp.vec3(1.0 - v - w, v, w)
@wp.func
def sphere_sdf(center: wp.vec3, radius: float, p: wp.vec3):
return wp.length(p - center) - radius
@wp.func
def sphere_sdf_grad(center: wp.vec3, radius: float, p: wp.vec3):
return wp.normalize(p - center)
@wp.func
def box_sdf(upper: wp.vec3, p: wp.vec3):
# adapted from https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
qx = abs(p[0]) - upper[0]
qy = abs(p[1]) - upper[1]
qz = abs(p[2]) - upper[2]
e = wp.vec3(wp.max(qx, 0.0), wp.max(qy, 0.0), wp.max(qz, 0.0))
return wp.length(e) + wp.min(wp.max(qx, wp.max(qy, qz)), 0.0)
@wp.func
def box_sdf_grad(upper: wp.vec3, p: wp.vec3):
qx = abs(p[0]) - upper[0]
qy = abs(p[1]) - upper[1]
qz = abs(p[2]) - upper[2]
# exterior case
if qx > 0.0 or qy > 0.0 or qz > 0.0:
x = wp.clamp(p[0], -upper[0], upper[0])
y = wp.clamp(p[1], -upper[1], upper[1])
z = wp.clamp(p[2], -upper[2], upper[2])
return wp.normalize(p - wp.vec3(x, y, z))
sx = wp.sign(p[0])
sy = wp.sign(p[1])
sz = wp.sign(p[2])
# x projection
if qx > qy and qx > qz or qy == 0.0 and qz == 0.0:
return wp.vec3(sx, 0.0, 0.0)
# y projection
if qy > qx and qy > qz or qx == 0.0 and qz == 0.0:
return wp.vec3(0.0, sy, 0.0)
# z projection
return wp.vec3(0.0, 0.0, sz)
@wp.func
def capsule_sdf(radius: float, half_height: float, p: wp.vec3):
if p[1] > half_height:
return wp.length(wp.vec3(p[0], p[1] - half_height, p[2])) - radius
if p[1] < -half_height:
return wp.length(wp.vec3(p[0], p[1] + half_height, p[2])) - radius
return wp.length(wp.vec3(p[0], 0.0, p[2])) - radius
@wp.func
def capsule_sdf_grad(radius: float, half_height: float, p: wp.vec3):
if p[1] > half_height:
return wp.normalize(wp.vec3(p[0], p[1] - half_height, p[2]))
if p[1] < -half_height:
return wp.normalize(wp.vec3(p[0], p[1] + half_height, p[2]))
return wp.normalize(wp.vec3(p[0], 0.0, p[2]))
@wp.func
def cylinder_sdf(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius
dy = wp.abs(p[1]) - half_height
return wp.min(wp.max(dx, dy), 0.0) + wp.length(wp.vec2(wp.max(dx, 0.0), wp.max(dy, 0.0)))
@wp.func
def cylinder_sdf_grad(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius
dy = wp.abs(p[1]) - half_height
if dx > dy:
return wp.normalize(wp.vec3(p[0], 0.0, p[2]))
return wp.vec3(0.0, wp.sign(p[1]), 0.0)
@wp.func
def cone_sdf(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius * (p[1] + half_height) / (2.0 * half_height)
dy = wp.abs(p[1]) - half_height
return wp.min(wp.max(dx, dy), 0.0) + wp.length(wp.vec2(wp.max(dx, 0.0), wp.max(dy, 0.0)))
@wp.func
def cone_sdf_grad(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius * (p[1] + half_height) / (2.0 * half_height)
dy = wp.abs(p[1]) - half_height
if dy < 0.0 or dx == 0.0:
return wp.vec3(0.0, wp.sign(p[1]), 0.0)
return wp.normalize(wp.vec3(p[0], 0.0, p[2])) + wp.vec3(0.0, radius / (2.0 * half_height), 0.0)
@wp.func
def plane_sdf(width: float, length: float, p: wp.vec3):
# SDF for a quad in the xz plane
if width > 0.0 and length > 0.0:
d = wp.max(wp.abs(p[0]) - width, wp.abs(p[2]) - length)
return wp.max(d, wp.abs(p[1]))
return p[1]
@wp.func
def closest_point_plane(width: float, length: float, point: wp.vec3):
# projects the point onto the quad in the xz plane (if width and length > 0.0, otherwise the plane is infinite)
if width > 0.0:
x = wp.clamp(point[0], -width, width)
else:
x = point[0]
if length > 0.0:
z = wp.clamp(point[2], -length, length)
else:
z = point[2]
return wp.vec3(x, 0.0, z)
@wp.func
def closest_point_line_segment(a: wp.vec3, b: wp.vec3, point: wp.vec3):
ab = b - a
ap = point - a
t = wp.dot(ap, ab) / wp.dot(ab, ab)
t = wp.clamp(t, 0.0, 1.0)
return a + t * ab
@wp.func
def closest_point_box(upper: wp.vec3, point: wp.vec3):
# closest point to box surface
x = wp.clamp(point[0], -upper[0], upper[0])
y = wp.clamp(point[1], -upper[1], upper[1])
z = wp.clamp(point[2], -upper[2], upper[2])
if wp.abs(point[0]) <= upper[0] and wp.abs(point[1]) <= upper[1] and wp.abs(point[2]) <= upper[2]:
# the point is inside, find closest face
sx = wp.abs(wp.abs(point[0]) - upper[0])
sy = wp.abs(wp.abs(point[1]) - upper[1])
sz = wp.abs(wp.abs(point[2]) - upper[2])
# return closest point on closest side, handle corner cases
if sx < sy and sx < sz or sy == 0.0 and sz == 0.0:
x = wp.sign(point[0]) * upper[0]
elif sy < sx and sy < sz or sx == 0.0 and sz == 0.0:
y = wp.sign(point[1]) * upper[1]
else:
z = wp.sign(point[2]) * upper[2]
return wp.vec3(x, y, z)
@wp.func
def get_box_vertex(point_id: int, upper: wp.vec3):
# get the vertex of the box given its ID (0-7)
sign_x = float(point_id % 2) * 2.0 - 1.0
sign_y = float((point_id // 2) % 2) * 2.0 - 1.0
sign_z = float((point_id // 4) % 2) * 2.0 - 1.0
return wp.vec3(sign_x * upper[0], sign_y * upper[1], sign_z * upper[2])
@wp.func
def get_box_edge(edge_id: int, upper: wp.vec3):
# get the edge of the box given its ID (0-11)
if edge_id < 4:
# edges along x: 0-1, 2-3, 4-5, 6-7
i = edge_id * 2
j = i + 1
return wp.spatial_vector(get_box_vertex(i, upper), get_box_vertex(j, upper))
elif edge_id < 8:
# edges along y: 0-2, 1-3, 4-6, 5-7
edge_id -= 4
i = edge_id % 2 + edge_id // 2 * 4
j = i + 2
return wp.spatial_vector(get_box_vertex(i, upper), get_box_vertex(j, upper))
# edges along z: 0-4, 1-5, 2-6, 3-7
edge_id -= 8
i = edge_id
j = i + 4
return wp.spatial_vector(get_box_vertex(i, upper), get_box_vertex(j, upper))
@wp.func
def get_plane_edge(edge_id: int, plane_width: float, plane_length: float):
# get the edge of the plane given its ID (0-3)
p0x = (2.0 * float(edge_id % 2) - 1.0) * plane_width
p0z = (2.0 * float(edge_id // 2) - 1.0) * plane_length
if edge_id == 0 or edge_id == 3:
p1x = p0x
p1z = -p0z
else:
p1x = -p0x
p1z = p0z
return wp.spatial_vector(wp.vec3(p0x, 0.0, p0z), wp.vec3(p1x, 0.0, p1z))
@wp.func
def closest_edge_coordinate_box(upper: wp.vec3, edge_a: wp.vec3, edge_b: wp.vec3, max_iter: int):
# find point on edge closest to box, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = box_sdf(upper, query)
query = (1.0 - d) * edge_a + d * edge_b
yd = box_sdf(upper, query)
for k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = box_sdf(upper, query)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = box_sdf(upper, query)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def closest_edge_coordinate_plane(
plane_width: float,
plane_length: float,
edge_a: wp.vec3,
edge_b: wp.vec3,
max_iter: int,
):
# find point on edge closest to plane, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = plane_sdf(plane_width, plane_length, query)
query = (1.0 - d) * edge_a + d * edge_b
yd = plane_sdf(plane_width, plane_length, query)
for k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = plane_sdf(plane_width, plane_length, query)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = plane_sdf(plane_width, plane_length, query)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def closest_edge_coordinate_capsule(radius: float, half_height: float, edge_a: wp.vec3, edge_b: wp.vec3, max_iter: int):
# find point on edge closest to capsule, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = capsule_sdf(radius, half_height, query)
query = (1.0 - d) * edge_a + d * edge_b
yd = capsule_sdf(radius, half_height, query)
for k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = capsule_sdf(radius, half_height, query)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = capsule_sdf(radius, half_height, query)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def mesh_sdf(mesh: wp.uint64, point: wp.vec3, max_dist: float):
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(mesh, point, max_dist, sign, face_index, face_u, face_v)
if res:
closest = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
return wp.length(point - closest) * sign
return max_dist
@wp.func
def closest_point_mesh(mesh: wp.uint64, point: wp.vec3, max_dist: float):
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(mesh, point, max_dist, sign, face_index, face_u, face_v)
if res:
return wp.mesh_eval_position(mesh, face_index, face_u, face_v)
# return arbitrary point from mesh
return wp.mesh_eval_position(mesh, 0, 0.0, 0.0)
@wp.func
def closest_edge_coordinate_mesh(mesh: wp.uint64, edge_a: wp.vec3, edge_b: wp.vec3, max_iter: int, max_dist: float):
# find point on edge closest to mesh, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = mesh_sdf(mesh, query, max_dist)
query = (1.0 - d) * edge_a + d * edge_b
yd = mesh_sdf(mesh, query, max_dist)
for k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = mesh_sdf(mesh, query, max_dist)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = mesh_sdf(mesh, query, max_dist)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def volume_grad(volume: wp.uint64, p: wp.vec3):
eps = 0.05 # TODO make this a parameter
q = wp.volume_world_to_index(volume, p)
# compute gradient of the SDF using finite differences
dx = wp.volume_sample_f(volume, q + wp.vec3(eps, 0.0, 0.0), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(eps, 0.0, 0.0), wp.Volume.LINEAR
)
dy = wp.volume_sample_f(volume, q + wp.vec3(0.0, eps, 0.0), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(0.0, eps, 0.0), wp.Volume.LINEAR
)
dz = wp.volume_sample_f(volume, q + wp.vec3(0.0, 0.0, eps), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(0.0, 0.0, eps), wp.Volume.LINEAR
)
return wp.normalize(wp.vec3(dx, dy, dz))
@wp.kernel
def create_soft_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_X_wb: wp.array(dtype=wp.transform),
shape_X_bs: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
geo: ModelShapeGeometry,
margin: float,
soft_contact_max: int,
# outputs
soft_contact_count: wp.array(dtype=int),
soft_contact_particle: wp.array(dtype=int),
soft_contact_shape: wp.array(dtype=int),
soft_contact_body_pos: wp.array(dtype=wp.vec3),
soft_contact_body_vel: wp.array(dtype=wp.vec3),
soft_contact_normal: wp.array(dtype=wp.vec3),
):
particle_index, shape_index = wp.tid()
if (particle_flags[particle_index] & PARTICLE_FLAG_ACTIVE) == 0:
return
rigid_index = shape_body[shape_index]
px = particle_x[particle_index]
radius = particle_radius[particle_index]
X_wb = wp.transform_identity()
if rigid_index >= 0:
X_wb = body_X_wb[rigid_index]
X_bs = shape_X_bs[shape_index]
X_ws = wp.transform_multiply(X_wb, X_bs)
X_sw = wp.transform_inverse(X_ws)
# transform particle position to shape local space
x_local = wp.transform_point(X_sw, px)
# geo description
geo_type = geo.type[shape_index]
geo_scale = geo.scale[shape_index]
# evaluate shape sdf
d = 1.0e6
n = wp.vec3()
v = wp.vec3()
if geo_type == wp.sim.GEO_SPHERE:
d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
n = sphere_sdf_grad(wp.vec3(), geo_scale[0], x_local)
if geo_type == wp.sim.GEO_BOX:
d = box_sdf(geo_scale, x_local)
n = box_sdf_grad(geo_scale, x_local)
if geo_type == wp.sim.GEO_CAPSULE:
d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
n = capsule_sdf_grad(geo_scale[0], geo_scale[1], x_local)
if geo_type == wp.sim.GEO_CYLINDER:
d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
n = cylinder_sdf_grad(geo_scale[0], geo_scale[1], x_local)
if geo_type == wp.sim.GEO_CONE:
d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
n = cone_sdf_grad(geo_scale[0], geo_scale[1], x_local)
if geo_type == wp.sim.GEO_MESH:
mesh = geo.source[shape_index]
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
if wp.mesh_query_point_sign_normal(
mesh, wp.cw_div(x_local, geo_scale), margin + radius, sign, face_index, face_u, face_v
):
shape_p = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
shape_v = wp.mesh_eval_velocity(mesh, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale)
shape_v = wp.cw_mul(shape_v, geo_scale)
delta = x_local - shape_p
d = wp.length(delta) * sign
n = wp.normalize(delta) * sign
v = shape_v
if geo_type == wp.sim.GEO_SDF:
volume = geo.source[shape_index]
xpred_local = wp.volume_world_to_index(volume, wp.cw_div(x_local, geo_scale))
nn = wp.vec3(0.0, 0.0, 0.0)
d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, nn)
n = wp.normalize(nn)
if geo_type == wp.sim.GEO_PLANE:
d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
n = wp.vec3(0.0, 1.0, 0.0)
if d < margin + radius:
index = wp.atomic_add(soft_contact_count, 0, 1)
if index < soft_contact_max:
# compute contact point in body local space
body_pos = wp.transform_point(X_bs, x_local - n * d)
body_vel = wp.transform_vector(X_bs, v)
world_normal = wp.transform_vector(X_ws, n)
soft_contact_shape[index] = shape_index
soft_contact_body_pos[index] = body_pos
soft_contact_body_vel[index] = body_vel
soft_contact_particle[index] = particle_index
soft_contact_normal[index] = world_normal
@wp.kernel
def count_contact_points(
contact_pairs: wp.array(dtype=int, ndim=2),
geo: ModelShapeGeometry,
# outputs
contact_count: wp.array(dtype=int),
):
tid = wp.tid()
shape_a = contact_pairs[tid, 0]
shape_b = contact_pairs[tid, 1]
if shape_b == -1:
actual_type_a = geo.type[shape_a]
# ground plane
actual_type_b = wp.sim.GEO_PLANE
else:
type_a = geo.type[shape_a]
type_b = geo.type[shape_b]
# unique ordering of shape pairs
if type_a < type_b:
actual_shape_a = shape_a
actual_shape_b = shape_b
actual_type_a = type_a
actual_type_b = type_b
else:
actual_shape_a = shape_b
actual_shape_b = shape_a
actual_type_a = type_b
actual_type_b = type_a
# determine how many contact points need to be evaluated
num_contacts = 0
if actual_type_a == wp.sim.GEO_SPHERE:
num_contacts = 1
elif actual_type_a == wp.sim.GEO_CAPSULE:
if actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 2 # vertex-based collision for infinite plane
else:
num_contacts = 2 + 4 # vertex-based collision + plane edges
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 2
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
else:
num_contacts = 2
elif actual_type_a == wp.sim.GEO_BOX:
if actual_type_b == wp.sim.GEO_BOX:
num_contacts = 24
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 8
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
elif actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 8 # vertex-based collision
else:
num_contacts = 8 + 4 # vertex-based collision + plane edges
else:
num_contacts = 8
elif actual_type_a == wp.sim.GEO_MESH:
mesh_a = wp.mesh_get(geo.source[actual_shape_a])
num_contacts_a = mesh_a.points.shape[0]
if actual_type_b == wp.sim.GEO_MESH:
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
else:
num_contacts_b = 0
num_contacts = num_contacts_a + num_contacts_b
elif actual_type_a == wp.sim.GEO_PLANE:
return # no plane-plane contacts
else:
print("count_contact_points: unsupported geometry type")
print(actual_type_a)
print(actual_type_b)
wp.atomic_add(contact_count, 0, num_contacts)
@wp.kernel
def broadphase_collision_pairs(
contact_pairs: wp.array(dtype=int, ndim=2),
body_q: wp.array(dtype=wp.transform),
shape_X_bs: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
geo: ModelShapeGeometry,
collision_radius: wp.array(dtype=float),
rigid_contact_max: int,
rigid_contact_margin: float,
# outputs
contact_count: wp.array(dtype=int),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
contact_point_id: wp.array(dtype=int),
):
tid = wp.tid()
shape_a = contact_pairs[tid, 0]
shape_b = contact_pairs[tid, 1]
rigid_a = shape_body[shape_a]
if rigid_a == -1:
X_ws_a = shape_X_bs[shape_a]
else:
X_ws_a = wp.transform_multiply(body_q[rigid_a], shape_X_bs[shape_a])
rigid_b = shape_body[shape_b]
if rigid_b == -1:
X_ws_b = shape_X_bs[shape_b]
else:
X_ws_b = wp.transform_multiply(body_q[rigid_b], shape_X_bs[shape_b])
type_a = geo.type[shape_a]
type_b = geo.type[shape_b]
# unique ordering of shape pairs
if type_a < type_b:
actual_shape_a = shape_a
actual_shape_b = shape_b
actual_type_a = type_a
actual_type_b = type_b
actual_X_ws_a = X_ws_a
actual_X_ws_b = X_ws_b
else:
actual_shape_a = shape_b
actual_shape_b = shape_a
actual_type_a = type_b
actual_type_b = type_a
actual_X_ws_a = X_ws_b
actual_X_ws_b = X_ws_a
p_a = wp.transform_get_translation(actual_X_ws_a)
if actual_type_b == wp.sim.GEO_PLANE:
if actual_type_a == wp.sim.GEO_PLANE:
return
query_b = wp.transform_point(wp.transform_inverse(actual_X_ws_b), p_a)
scale = geo.scale[actual_shape_b]
closest = closest_point_plane(scale[0], scale[1], query_b)
d = wp.length(query_b - closest)
r_a = collision_radius[actual_shape_a]
if d > r_a + rigid_contact_margin:
return
else:
p_b = wp.transform_get_translation(actual_X_ws_b)
d = wp.length(p_a - p_b) * 0.5 - 0.1
r_a = collision_radius[actual_shape_a]
r_b = collision_radius[actual_shape_b]
if d > r_a + r_b + rigid_contact_margin:
return
# determine how many contact points need to be evaluated
num_contacts = 0
if actual_type_a == wp.sim.GEO_SPHERE:
num_contacts = 1
elif actual_type_a == wp.sim.GEO_CAPSULE:
if actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 2 # vertex-based collision for infinite plane
else:
num_contacts = 2 + 4 # vertex-based collision + plane edges
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 2
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from capsule A against mesh B
for i in range(num_contacts_a):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
# allocate contact points from mesh B against capsule A
for i in range(num_contacts_b):
contact_shape0[index + num_contacts_a + i] = actual_shape_b
contact_shape1[index + num_contacts_a + i] = actual_shape_a
contact_point_id[index + num_contacts_a + i] = i
return
else:
num_contacts = 2
elif actual_type_a == wp.sim.GEO_BOX:
if actual_type_b == wp.sim.GEO_BOX:
index = wp.atomic_add(contact_count, 0, 24)
if index + 23 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from box A against B
for i in range(12): # 12 edges
contact_shape0[index + i] = shape_a
contact_shape1[index + i] = shape_b
contact_point_id[index + i] = i
# allocate contact points from box B against A
for i in range(12):
contact_shape0[index + 12 + i] = shape_b
contact_shape1[index + 12 + i] = shape_a
contact_point_id[index + 12 + i] = i
return
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 8
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from box A against mesh B
for i in range(num_contacts_a):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
# allocate contact points from mesh B against box A
for i in range(num_contacts_b):
contact_shape0[index + num_contacts_a + i] = actual_shape_b
contact_shape1[index + num_contacts_a + i] = actual_shape_a
contact_point_id[index + num_contacts_a + i] = i
return
elif actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 8 # vertex-based collision
else:
num_contacts = 8 + 4 # vertex-based collision + plane edges
else:
num_contacts = 8
elif actual_type_a == wp.sim.GEO_MESH:
mesh_a = wp.mesh_get(geo.source[actual_shape_a])
num_contacts_a = mesh_a.points.shape[0]
num_contacts_b = 0
if actual_type_b == wp.sim.GEO_MESH:
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
elif actual_type_b != wp.sim.GEO_PLANE:
print("broadphase_collision_pairs: unsupported geometry type for mesh collision")
return
num_contacts = num_contacts_a + num_contacts_b
if num_contacts > 0:
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Mesh contact: Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from mesh A against B
for i in range(num_contacts_a):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
# allocate contact points from mesh B against A
for i in range(num_contacts_b):
contact_shape0[index + num_contacts_a + i] = actual_shape_b
contact_shape1[index + num_contacts_a + i] = actual_shape_a
contact_point_id[index + num_contacts_a + i] = i
return
elif actual_type_a == wp.sim.GEO_PLANE:
return # no plane-plane contacts
else:
print("broadphase_collision_pairs: unsupported geometry type")
if num_contacts > 0:
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points
for i in range(num_contacts):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
@wp.kernel
def handle_contact_pairs(
body_q: wp.array(dtype=wp.transform),
shape_X_bs: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
geo: ModelShapeGeometry,
rigid_contact_margin: float,
body_com: wp.array(dtype=wp.vec3),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
contact_point_id: wp.array(dtype=int),
rigid_contact_count: wp.array(dtype=int),
edge_sdf_iter: int,
# outputs
contact_body0: wp.array(dtype=int),
contact_body1: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_offset0: wp.array(dtype=wp.vec3),
contact_offset1: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_thickness: wp.array(dtype=float),
):
tid = wp.tid()
if tid >= rigid_contact_count[0]:
return
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a == shape_b:
return
point_id = contact_point_id[tid]
rigid_a = shape_body[shape_a]
X_wb_a = wp.transform_identity()
if rigid_a >= 0:
X_wb_a = body_q[rigid_a]
X_bs_a = shape_X_bs[shape_a]
X_ws_a = wp.transform_multiply(X_wb_a, X_bs_a)
X_sw_a = wp.transform_inverse(X_ws_a)
X_bw_a = wp.transform_inverse(X_wb_a)
geo_type_a = geo.type[shape_a]
geo_scale_a = geo.scale[shape_a]
min_scale_a = min(geo_scale_a)
thickness_a = geo.thickness[shape_a]
# is_solid_a = geo.is_solid[shape_a]
rigid_b = shape_body[shape_b]
X_wb_b = wp.transform_identity()
if rigid_b >= 0:
X_wb_b = body_q[rigid_b]
X_bs_b = shape_X_bs[shape_b]
X_ws_b = wp.transform_multiply(X_wb_b, X_bs_b)
X_sw_b = wp.transform_inverse(X_ws_b)
X_bw_b = wp.transform_inverse(X_wb_b)
geo_type_b = geo.type[shape_b]
geo_scale_b = geo.scale[shape_b]
min_scale_b = min(geo_scale_b)
thickness_b = geo.thickness[shape_b]
# is_solid_b = geo.is_solid[shape_b]
# fill in contact rigid body ids
contact_body0[tid] = rigid_a
contact_body1[tid] = rigid_b
distance = 1.0e6
u = float(0.0)
if geo_type_a == wp.sim.GEO_SPHERE:
p_a_world = wp.transform_get_translation(X_ws_a)
if geo_type_b == wp.sim.GEO_SPHERE:
p_b_world = wp.transform_get_translation(X_ws_b)
elif geo_type_b == wp.sim.GEO_BOX:
# contact point in frame of body B
p_a_body = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_box(geo_scale_b, p_a_body)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
elif geo_type_b == wp.sim.GEO_CAPSULE:
half_height_b = geo_scale_b[1]
# capsule B
A_b = wp.transform_point(X_ws_b, wp.vec3(0.0, half_height_b, 0.0))
B_b = wp.transform_point(X_ws_b, wp.vec3(0.0, -half_height_b, 0.0))
p_b_world = closest_point_line_segment(A_b, B_b, p_a_world)
elif geo_type_b == wp.sim.GEO_MESH:
mesh_b = geo.source[shape_b]
query_b_local = wp.transform_point(X_sw_b, p_a_world)
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = (thickness_a + thickness_b + rigid_contact_margin) / geo_scale_b[0]
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
else:
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
elif geo_type_b == wp.sim.GEO_PLANE:
p_b_body = closest_point_plane(geo_scale_b[0], geo_scale_b[1], wp.transform_point(X_sw_b, p_a_world))
p_b_world = wp.transform_point(X_ws_b, p_b_body)
else:
print("Unsupported geometry type in sphere collision handling")
print(geo_type_b)
return
diff = p_a_world - p_b_world
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_BOX:
# edge-based box contact
edge = get_box_edge(point_id, geo_scale_a)
edge0_world = wp.transform_point(X_ws_a, wp.spatial_top(edge))
edge1_world = wp.transform_point(X_ws_a, wp.spatial_bottom(edge))
edge0_b = wp.transform_point(X_sw_b, edge0_world)
edge1_b = wp.transform_point(X_sw_b, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_box(geo_scale_b, edge0_b, edge1_b, max_iter)
p_a_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on box B
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_box(geo_scale_b, query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
# use center of box A to query normal to make sure we are not inside B
query_b = wp.transform_point(X_sw_b, wp.transform_get_translation(X_ws_a))
normal = wp.transform_vector(X_ws_b, box_sdf_grad(geo_scale_b, query_b))
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_CAPSULE:
half_height_b = geo_scale_b[1]
# capsule B
# depending on point id, we query an edge from 0 to 0.5 or 0.5 to 1
e0 = wp.vec3(0.0, -half_height_b * float(point_id % 2), 0.0)
e1 = wp.vec3(0.0, half_height_b * float((point_id + 1) % 2), 0.0)
edge0_world = wp.transform_point(X_ws_b, e0)
edge1_world = wp.transform_point(X_ws_b, e1)
edge0_a = wp.transform_point(X_sw_a, edge0_world)
edge1_a = wp.transform_point(X_sw_a, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_box(geo_scale_a, edge0_a, edge1_a, max_iter)
p_b_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on box A
query_a = wp.transform_point(X_sw_a, p_b_world)
p_a_body = closest_point_box(geo_scale_a, query_a)
p_a_world = wp.transform_point(X_ws_a, p_a_body)
diff = p_a_world - p_b_world
# the contact point inside the capsule should already be outside the box
normal = -wp.transform_vector(X_ws_a, box_sdf_grad(geo_scale_a, query_a))
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_PLANE:
plane_width = geo_scale_b[0]
plane_length = geo_scale_b[1]
if point_id < 8:
# vertex-based contact
p_a_body = get_box_vertex(point_id, geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, p_a_body)
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_plane(plane_width, plane_length, query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
if plane_width > 0.0 and plane_length > 0.0:
if wp.abs(query_b[0]) > plane_width or wp.abs(query_b[2]) > plane_length:
# skip, we will evaluate the plane edge contact with the box later
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
# check whether the COM is above the plane
# sign = wp.sign(wp.dot(wp.transform_get_translation(X_ws_a) - p_b_world, normal))
# if sign < 0.0:
# # the entire box is most likely below the plane
# contact_shape0[tid] = -1
# contact_shape1[tid] = -1
# return
# the contact point is within plane boundaries
distance = wp.dot(diff, normal)
else:
# contact between box A and edges of finite plane B
edge = get_plane_edge(point_id - 8, plane_width, plane_length)
edge0_world = wp.transform_point(X_ws_b, wp.spatial_top(edge))
edge1_world = wp.transform_point(X_ws_b, wp.spatial_bottom(edge))
edge0_a = wp.transform_point(X_sw_a, edge0_world)
edge1_a = wp.transform_point(X_sw_a, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_box(geo_scale_a, edge0_a, edge1_a, max_iter)
p_b_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on box A
query_a = wp.transform_point(X_sw_a, p_b_world)
p_a_body = closest_point_box(geo_scale_a, query_a)
p_a_world = wp.transform_point(X_ws_a, p_a_body)
query_b = wp.transform_point(X_sw_b, p_a_world)
if wp.abs(query_b[0]) > plane_width or wp.abs(query_b[2]) > plane_length:
# ensure that the closest point is actually inside the plane
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
diff = p_a_world - p_b_world
com_a = wp.transform_get_translation(X_ws_a)
query_b = wp.transform_point(X_sw_b, com_a)
if wp.abs(query_b[0]) > plane_width or wp.abs(query_b[2]) > plane_length:
# the COM is outside the plane
normal = wp.normalize(com_a - p_b_world)
else:
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_CAPSULE and geo_type_b == wp.sim.GEO_CAPSULE:
# find closest edge coordinate to capsule SDF B
half_height_a = geo_scale_a[1]
half_height_b = geo_scale_b[1]
# edge from capsule A
# depending on point id, we query an edge from 0 to 0.5 or 0.5 to 1
e0 = wp.vec3(0.0, half_height_a * float(point_id % 2), 0.0)
e1 = wp.vec3(0.0, -half_height_a * float((point_id + 1) % 2), 0.0)
edge0_world = wp.transform_point(X_ws_a, e0)
edge1_world = wp.transform_point(X_ws_a, e1)
edge0_b = wp.transform_point(X_sw_b, edge0_world)
edge1_b = wp.transform_point(X_sw_b, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_capsule(geo_scale_b[0], geo_scale_b[1], edge0_b, edge1_b, max_iter)
p_a_world = (1.0 - u) * edge0_world + u * edge1_world
p0_b_world = wp.transform_point(X_ws_b, wp.vec3(0.0, half_height_b, 0.0))
p1_b_world = wp.transform_point(X_ws_b, wp.vec3(0.0, -half_height_b, 0.0))
p_b_world = closest_point_line_segment(p0_b_world, p1_b_world, p_a_world)
diff = p_a_world - p_b_world
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_CAPSULE and geo_type_b == wp.sim.GEO_MESH:
# find closest edge coordinate to mesh SDF B
half_height_a = geo_scale_a[1]
# edge from capsule A
# depending on point id, we query an edge from -h to 0 or 0 to h
e0 = wp.vec3(0.0, -half_height_a * float(point_id % 2), 0.0)
e1 = wp.vec3(0.0, half_height_a * float((point_id + 1) % 2), 0.0)
edge0_world = wp.transform_point(X_ws_a, e0)
edge1_world = wp.transform_point(X_ws_a, e1)
edge0_b = wp.transform_point(X_sw_b, edge0_world)
edge1_b = wp.transform_point(X_sw_b, edge1_world)
max_iter = edge_sdf_iter
max_dist = (rigid_contact_margin + thickness_a + thickness_b) / min_scale_b
mesh_b = geo.source[shape_b]
u = closest_edge_coordinate_mesh(
mesh_b, wp.cw_div(edge0_b, geo_scale_b), wp.cw_div(edge1_b, geo_scale_b), max_iter, max_dist
)
p_a_world = (1.0 - u) * edge0_world + u * edge1_world
query_b_local = wp.transform_point(X_sw_b, p_a_world)
mesh_b = geo.source[shape_b]
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
p_a_world = closest_point_line_segment(edge0_world, edge1_world, p_b_world)
# contact direction vector in world frame
diff = p_a_world - p_b_world
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
else:
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_CAPSULE:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
# find closest point + contact normal on capsule B
half_height_b = geo_scale_b[1]
A_b = wp.transform_point(X_ws_b, wp.vec3(0.0, half_height_b, 0.0))
B_b = wp.transform_point(X_ws_b, wp.vec3(0.0, -half_height_b, 0.0))
p_b_world = closest_point_line_segment(A_b, B_b, p_a_world)
diff = p_a_world - p_b_world
# this is more reliable in practice than using the SDF gradient
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_CAPSULE and geo_type_b == wp.sim.GEO_PLANE:
plane_width = geo_scale_b[0]
plane_length = geo_scale_b[1]
if point_id < 2:
# vertex-based collision
half_height_a = geo_scale_a[1]
side = float(point_id) * 2.0 - 1.0
p_a_world = wp.transform_point(X_ws_a, wp.vec3(0.0, side * half_height_a, 0.0))
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_plane(geo_scale_b[0], geo_scale_b[1], query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
if geo_scale_b[0] > 0.0 and geo_scale_b[1] > 0.0:
normal = wp.normalize(diff)
else:
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
distance = wp.dot(diff, normal)
else:
# contact between capsule A and edges of finite plane B
plane_width = geo_scale_b[0]
plane_length = geo_scale_b[1]
edge = get_plane_edge(point_id - 2, plane_width, plane_length)
edge0_world = wp.transform_point(X_ws_b, wp.spatial_top(edge))
edge1_world = wp.transform_point(X_ws_b, wp.spatial_bottom(edge))
edge0_a = wp.transform_point(X_sw_a, edge0_world)
edge1_a = wp.transform_point(X_sw_a, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_capsule(geo_scale_a[0], geo_scale_a[1], edge0_a, edge1_a, max_iter)
p_b_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on capsule A
half_height_a = geo_scale_a[1]
p0_a_world = wp.transform_point(X_ws_a, wp.vec3(0.0, half_height_a, 0.0))
p1_a_world = wp.transform_point(X_ws_a, wp.vec3(0.0, -half_height_a, 0.0))
p_a_world = closest_point_line_segment(p0_a_world, p1_a_world, p_b_world)
diff = p_a_world - p_b_world
# normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_BOX:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
# find closest point + contact normal on box B
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_box(geo_scale_b, query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
# this is more reliable in practice than using the SDF gradient
normal = wp.normalize(diff)
if box_sdf(geo_scale_b, query_b) < 0.0:
normal = -normal
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_MESH:
# vertex-based contact
query_a = get_box_vertex(point_id, geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, query_a)
query_b_local = wp.transform_point(X_sw_b, p_a_world)
mesh_b = geo.source[shape_b]
max_dist = (rigid_contact_margin + thickness_a + thickness_b) / min_scale_b
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
# contact direction vector in world frame
diff_b = p_a_world - p_b_world
normal = wp.normalize(diff_b) * sign
distance = wp.dot(diff_b, normal)
else:
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_MESH:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
mesh_b = geo.source[shape_b]
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
query_b_local = wp.transform_point(X_sw_b, p_a_world)
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
min_scale = min(min_scale_a, min_scale_b)
max_dist = (rigid_contact_margin + thickness_a + thickness_b) / min_scale
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
# contact direction vector in world frame
diff_b = p_a_world - p_b_world
normal = wp.normalize(diff_b) * sign
distance = wp.dot(diff_b, normal)
else:
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_PLANE:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_plane(geo_scale_b[0], geo_scale_b[1], query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
distance = wp.length(diff)
# if the plane is infinite or the point is within the plane we fix the normal to prevent intersections
if (
geo_scale_b[0] == 0.0
and geo_scale_b[1] == 0.0
or wp.abs(query_b[0]) < geo_scale_b[0]
and wp.abs(query_b[2]) < geo_scale_b[1]
):
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
else:
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
# ignore extreme penetrations (e.g. when mesh is below the plane)
if distance < -rigid_contact_margin:
contact_shape0[tid] = -1
contact_shape1[tid] = -1
return
else:
print("Unsupported geometry pair in collision handling")
return
thickness = thickness_a + thickness_b
d = distance - thickness
if d < rigid_contact_margin:
# transform from world into body frame (so the contact point includes the shape transform)
contact_point0[tid] = wp.transform_point(X_bw_a, p_a_world)
contact_point1[tid] = wp.transform_point(X_bw_b, p_b_world)
contact_offset0[tid] = wp.transform_vector(X_bw_a, -thickness_a * normal)
contact_offset1[tid] = wp.transform_vector(X_bw_b, thickness_b * normal)
contact_normal[tid] = normal
contact_thickness[tid] = thickness
# wp.printf("distance: %f\tnormal: %.3f %.3f %.3f\tp_a_world: %.3f %.3f %.3f\tp_b_world: %.3f %.3f %.3f\n", distance, normal[0], normal[1], normal[2], p_a_world[0], p_a_world[1], p_a_world[2], p_b_world[0], p_b_world[1], p_b_world[2])
else:
contact_shape0[tid] = -1
contact_shape1[tid] = -1
def collide(model, state, edge_sdf_iter: int = 10):
"""
Generates contact points for the particles and rigid bodies in the model,
to be used in the contact dynamics kernel of the integrator.
Args:
model: the model to be simulated
state: the state of the model
edge_sdf_iter: number of search iterations for finding closest contact points between edges and SDF
"""
# generate soft contacts for particles and shapes except ground plane (last shape)
if model.particle_count and model.shape_count > 1:
# clear old count
model.soft_contact_count.zero_()
wp.launch(
kernel=create_soft_contacts,
dim=(model.particle_count, model.shape_count - 1),
inputs=[
state.particle_q,
model.particle_radius,
model.particle_flags,
state.body_q,
model.shape_transform,
model.shape_body,
model.shape_geo,
model.soft_contact_margin,
model.soft_contact_max,
],
outputs=[
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
],
device=model.device,
)
# clear old count
model.rigid_contact_count.zero_()
if model.shape_contact_pair_count:
wp.launch(
kernel=broadphase_collision_pairs,
dim=model.shape_contact_pair_count,
inputs=[
model.shape_contact_pairs,
state.body_q,
model.shape_transform,
model.shape_body,
model.shape_geo,
model.shape_collision_radius,
model.rigid_contact_max,
model.rigid_contact_margin,
],
outputs=[
model.rigid_contact_count,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.rigid_contact_point_id,
],
device=model.device,
record_tape=False,
)
if model.ground and model.shape_ground_contact_pair_count:
wp.launch(
kernel=broadphase_collision_pairs,
dim=model.shape_ground_contact_pair_count,
inputs=[
model.shape_ground_contact_pairs,
state.body_q,
model.shape_transform,
model.shape_body,
model.shape_geo,
model.shape_collision_radius,
model.rigid_contact_max,
model.rigid_contact_margin,
],
outputs=[
model.rigid_contact_count,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.rigid_contact_point_id,
],
device=model.device,
record_tape=False,
)
if model.shape_contact_pair_count or model.ground and model.shape_ground_contact_pair_count:
wp.launch(
kernel=handle_contact_pairs,
dim=model.rigid_contact_max,
inputs=[
state.body_q,
model.shape_transform,
model.shape_body,
model.shape_geo,
model.rigid_contact_margin,
model.body_com,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.rigid_contact_point_id,
model.rigid_contact_count,
edge_sdf_iter,
],
outputs=[
model.rigid_contact_body0,
model.rigid_contact_body1,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_offset0,
model.rigid_contact_offset1,
model.rigid_contact_normal,
model.rigid_contact_thickness,
],
device=model.device,
)
| warp-main | warp/sim/collide.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 .model import PARTICLE_FLAG_ACTIVE
@wp.func
def particle_force(n: wp.vec3, v: wp.vec3, c: float, k_n: float, k_d: float, k_f: float, k_mu: float):
vn = wp.dot(n, v)
jn = c * k_n
jd = min(vn, 0.0) * k_d
# contact force
fn = jn + jd
# friction force
vt = v - n * vn
vs = wp.length(vt)
if vs > 0.0:
vt = vt / vs
# Coulomb condition
ft = wp.min(vs * k_f, k_mu * wp.abs(fn))
# total force
return -n * fn - vt * ft
@wp.kernel
def eval_particle_forces_kernel(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
k_contact: float,
k_damp: float,
k_friction: float,
k_mu: float,
k_cohesion: float,
max_radius: float,
# outputs
particle_f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
if i == -1:
# hash grid has not been built yet
return
if (particle_flags[i] & PARTICLE_FLAG_ACTIVE) == 0:
return
x = particle_x[i]
v = particle_v[i]
radius = particle_radius[i]
f = wp.vec3()
# particle contact
query = wp.hash_grid_query(grid, x, radius + max_radius + k_cohesion)
index = int(0)
count = int(0)
while wp.hash_grid_query_next(query, index):
if (particle_flags[index] & PARTICLE_FLAG_ACTIVE) != 0 and index != i:
# compute distance to point
n = x - particle_x[index]
d = wp.length(n)
err = d - radius - particle_radius[index]
count += 1
if err <= k_cohesion:
n = n / d
vrel = v - particle_v[index]
f = f + particle_force(n, vrel, err, k_contact, k_damp, k_friction, k_mu)
particle_f[i] = f
def eval_particle_forces(model, state, forces):
if model.particle_max_radius > 0.0:
wp.launch(
kernel=eval_particle_forces_kernel,
dim=model.particle_count,
inputs=[
model.particle_grid.id,
state.particle_q,
state.particle_qd,
model.particle_radius,
model.particle_flags,
model.particle_ke,
model.particle_kd,
model.particle_kf,
model.particle_mu,
model.particle_cohesion,
model.particle_max_radius,
],
outputs=[forces],
device=model.device,
)
| warp-main | warp/sim/particles.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.
"""A module for building simulation models and state.
"""
import copy
import math
from typing import List, Optional, Tuple
import numpy as np
import warp as wp
from .inertia import (
compute_box_inertia,
compute_capsule_inertia,
compute_cone_inertia,
compute_cylinder_inertia,
compute_mesh_inertia,
compute_sphere_inertia,
transform_inertia,
)
Vec3 = List[float]
Vec4 = List[float]
Quat = List[float]
Mat33 = List[float]
Transform = Tuple[Vec3, Quat]
# Particle flags
PARTICLE_FLAG_ACTIVE = wp.constant(wp.uint32(1 << 0))
# Shape geometry types
GEO_SPHERE = wp.constant(0)
GEO_BOX = wp.constant(1)
GEO_CAPSULE = wp.constant(2)
GEO_CYLINDER = wp.constant(3)
GEO_CONE = wp.constant(4)
GEO_MESH = wp.constant(5)
GEO_SDF = wp.constant(6)
GEO_PLANE = wp.constant(7)
GEO_NONE = wp.constant(8)
# Types of joints linking rigid bodies
JOINT_PRISMATIC = wp.constant(0)
JOINT_REVOLUTE = wp.constant(1)
JOINT_BALL = wp.constant(2)
JOINT_FIXED = wp.constant(3)
JOINT_FREE = wp.constant(4)
JOINT_COMPOUND = wp.constant(5)
JOINT_UNIVERSAL = wp.constant(6)
JOINT_DISTANCE = wp.constant(7)
JOINT_D6 = wp.constant(8)
# Joint axis mode types
JOINT_MODE_LIMIT = wp.constant(0)
JOINT_MODE_TARGET_POSITION = wp.constant(1)
JOINT_MODE_TARGET_VELOCITY = wp.constant(2)
def flag_to_int(flag):
"""Converts a flag to an integer."""
if type(flag) in wp.types.int_types:
return flag.value
return int(flag)
# Material properties pertaining to rigid shape contact dynamics
@wp.struct
class ModelShapeMaterials:
ke: wp.array(dtype=float) # The contact elastic stiffness (only used by Euler integrator)
kd: wp.array(dtype=float) # The contact damping stiffness (only used by Euler integrator)
kf: wp.array(dtype=float) # The contact friction stiffness (only used by Euler integrator)
mu: wp.array(dtype=float) # The coefficient of friction
restitution: wp.array(dtype=float) # The coefficient of restitution (only used by XPBD integrator)
# Shape properties of geometry
@wp.struct
class ModelShapeGeometry:
type: wp.array(dtype=wp.int32) # The type of geometry (GEO_SPHERE, GEO_BOX, etc.)
is_solid: wp.array(dtype=wp.uint8) # Indicates whether the shape is solid or hollow
thickness: wp.array(
dtype=float
) # The thickness of the shape (used for collision detection, and inertia computation of hollow shapes)
source: wp.array(dtype=wp.uint64) # Pointer to the source geometry (in case of a mesh, zero otherwise)
scale: wp.array(dtype=wp.vec3) # The 3D scale of the shape
# Axis (linear or angular) of a joint that can have bounds and be driven towards a target
class JointAxis:
"""
Describes a joint axis that can have limits and be driven towards a target.
Attributes:
axis (3D vector): The axis that this JointAxis object describes
limit_lower (float): The lower limit of the joint axis
limit_upper (float): The upper limit of the joint axis
limit_ke (float): The elastic stiffness of the joint axis limits, only respected by SemiImplicitIntegrator
limit_kd (float): The damping stiffness of the joint axis limits, only respected by SemiImplicitIntegrator
target (float): The target position or velocity (depending on the mode, see `Joint modes`_) of the joint axis
target_ke (float): The proportional gain of the joint axis target drive PD controller
target_kd (float): The derivative gain of the joint axis target drive PD controller
mode (int): The mode of the joint axis, see `Joint modes`_
"""
def __init__(
self,
axis,
limit_lower=-np.inf,
limit_upper=np.inf,
limit_ke=100.0,
limit_kd=10.0,
target=None,
target_ke=0.0,
target_kd=0.0,
mode=JOINT_MODE_TARGET_POSITION,
):
self.axis = np.array(wp.normalize(np.array(axis, dtype=np.float32)))
self.limit_lower = limit_lower
self.limit_upper = limit_upper
self.limit_ke = limit_ke
self.limit_kd = limit_kd
if target is not None:
self.target = target
elif limit_lower > 0.0 or limit_upper < 0.0:
self.target = 0.5 * (limit_lower + limit_upper)
else:
self.target = 0.0
self.target_ke = target_ke
self.target_kd = target_kd
self.mode = mode
class SDF:
# Describes a signed distance field for simulation
#
# Attributes:
#
# Either a NanoVDB file name or a numpy array
#
def __init__(self, volume=None, I=np.eye(3, dtype=np.float32), mass=1.0, com=np.array((0.0, 0.0, 0.0))):
self.volume = volume
# Need to specify these for now
self.has_inertia = True
self.is_solid = True
self.mass = mass
self.com = com
self.I = I
def finalize(self, device=None):
return self.volume.id
def __hash__(self):
return hash((self.volume.id))
class Mesh:
"""Describes a triangle collision mesh for simulation
Attributes:
vertices (List[Vec3]): Mesh vertices
indices (List[int]): Mesh indices
I (Mat33): Inertia tensor of the mesh assuming density of 1.0 (around the center of mass)
mass (float): The total mass of the body assuming density of 1.0
com (Vec3): The center of mass of the body
"""
def __init__(self, vertices: List[Vec3], indices: List[int], compute_inertia=True, is_solid=True):
"""Construct a Mesh object from a triangle mesh
The mesh center of mass and inertia tensor will automatically be
calculated using a density of 1.0. This computation is only valid
if the mesh is closed (two-manifold).
Args:
vertices: List of vertices in the mesh
indices: List of triangle indices, 3 per-element
compute_inertia: If True, the mass, inertia tensor and center of mass will be computed assuming density of 1.0
is_solid: If True, the mesh is assumed to be a solid during inertia computation, otherwise it is assumed to be a hollow surface
"""
self.vertices = np.array(vertices).reshape(-1, 3)
self.indices = np.array(indices, dtype=np.int32).flatten()
self.is_solid = is_solid
self.has_inertia = compute_inertia
if compute_inertia:
self.mass, self.com, self.I, _ = compute_mesh_inertia(1.0, vertices, indices, is_solid=is_solid)
else:
self.I = np.eye(3, dtype=np.float32)
self.mass = 1.0
self.com = np.array((0.0, 0.0, 0.0))
# construct simulation ready buffers from points
def finalize(self, device=None):
with wp.ScopedDevice(device):
pos = wp.array(self.vertices, dtype=wp.vec3)
vel = wp.zeros_like(pos)
indices = wp.array(self.indices, dtype=wp.int32)
self.mesh = wp.Mesh(points=pos, velocities=vel, indices=indices)
return self.mesh.id
def __hash__(self):
return hash((tuple(np.array(self.vertices).flatten()), tuple(np.array(self.indices).flatten()), self.is_solid))
class State:
"""The State object holds all *time-varying* data for a model.
Time-varying data includes particle positions, velocities, rigid body states, and
anything that is output from the integrator as derived data, e.g.: forces.
The exact attributes depend on the contents of the model. State objects should
generally be created using the :func:`Model.state()` function.
Attributes:
particle_count (int): Number of particles
body_count (int): Number of rigid bodies
particle_q (wp.array): Tensor of particle positions
particle_qd (wp.array): Tensor of particle velocities
particle_f (wp.array): Tensor of particle forces
body_q (wp.array): Tensor of body coordinates
body_qd (wp.array): Tensor of body velocities
body_f (wp.array): Tensor of body forces
"""
def __init__(self):
self.particle_count = 0
self.body_count = 0
self.particle_q = None
self.particle_qd = None
self.particle_f = None
self.body_q = None
self.body_qd = None
self.body_f = None
def clear_forces(self):
if self.particle_count:
self.particle_f.zero_()
if self.body_count:
self.body_f.zero_()
def flatten(self):
wp.utils.warn(
"Model.flatten() will be removed in a future Warp version.",
DeprecationWarning,
stacklevel=2,
)
arrays = []
# build a list of all tensor attributes
for attr, value in self.__dict__.items():
if isinstance(value, wp.array):
arrays.append(value)
return arrays
def compute_shape_mass(type, scale, src, density, is_solid, thickness):
if density == 0.0 or type == GEO_PLANE: # zero density means fixed
return 0.0, np.zeros(3), np.zeros((3, 3))
if type == GEO_SPHERE:
solid = compute_sphere_inertia(density, scale[0])
if is_solid:
return solid
else:
hollow = compute_sphere_inertia(density, scale[0] - thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_BOX:
w, h, d = np.array(scale[:3]) * 2.0
solid = compute_box_inertia(density, w, h, d)
if is_solid:
return solid
else:
hollow = compute_box_inertia(density, w - thickness, h - thickness, d - thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_CAPSULE:
r, h = scale[0], scale[1] * 2.0
solid = compute_capsule_inertia(density, r, h)
if is_solid:
return solid
else:
hollow = compute_capsule_inertia(density, r - thickness, h - 2.0 * thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_CYLINDER:
r, h = scale[0], scale[1] * 2.0
solid = compute_cylinder_inertia(density, r, h)
if is_solid:
return solid
else:
hollow = compute_cylinder_inertia(density, r - thickness, h - 2.0 * thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_CONE:
r, h = scale[0], scale[1] * 2.0
solid = compute_cone_inertia(density, r, h)
if is_solid:
return solid
else:
hollow = compute_cone_inertia(density, r - thickness, h - 2.0 * thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_MESH or type == GEO_SDF:
if src.has_inertia and src.mass > 0.0 and src.is_solid == is_solid:
m, c, I = src.mass, src.com, src.I
s = np.array(scale[:3])
sx, sy, sz = s
mass_ratio = sx * sy * sz * density
m_new = m * mass_ratio
c_new = c * s
Ixx = I[0, 0] * (sy**2 + sz**2) / 2 * mass_ratio
Iyy = I[1, 1] * (sx**2 + sz**2) / 2 * mass_ratio
Izz = I[2, 2] * (sx**2 + sy**2) / 2 * mass_ratio
Ixy = I[0, 1] * sx * sy * mass_ratio
Ixz = I[0, 2] * sx * sz * mass_ratio
Iyz = I[1, 2] * sy * sz * mass_ratio
I_new = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])
return m_new, c_new, I_new
elif type == GEO_MESH:
# fall back to computing inertia from mesh geometry
vertices = np.array(src.vertices) * np.array(scale[:3])
m, c, I, vol = compute_mesh_inertia(density, vertices, src.indices, is_solid, thickness)
return m, c, I
raise ValueError("Unsupported shape type: {}".format(type))
class Model:
"""Holds the definition of the simulation model
This class holds the non-time varying description of the system, i.e.:
all geometry, constraints, and parameters used to describe the simulation.
Attributes:
requires_grad (float): Indicates whether the model was finalized with gradient computation enabled
num_envs (int): Number of articulation environments that were added to the ModelBuilder via `add_builder`
particle_q (wp.array): Particle positions, shape [particle_count, 3], float
particle_qd (wp.array): Particle velocities, shape [particle_count, 3], float
particle_mass (wp.array): Particle mass, shape [particle_count], float
particle_inv_mass (wp.array): Particle inverse mass, shape [particle_count], float
particle_radius (wp.array): Particle radius, shape [particle_count], float
particle_max_radius (float): Maximum particle radius (useful for HashGrid construction)
particle_ke (wp.array): Particle normal contact stiffness (used by SemiImplicitIntegrator), shape [particle_count], float
particle_kd (wp.array): Particle normal contact damping (used by SemiImplicitIntegrator), shape [particle_count], float
particle_kf (wp.array): Particle friction force stiffness (used by SemiImplicitIntegrator), shape [particle_count], float
particle_mu (wp.array): Particle friction coefficient, shape [particle_count], float
particle_cohesion (wp.array): Particle cohesion strength, shape [particle_count], float
particle_adhesion (wp.array): Particle adhesion strength, shape [particle_count], float
particle_grid (HashGrid): HashGrid instance used for accelerated simulation of particle interactions
particle_flags (wp.array): Particle enabled state, shape [particle_count], bool
particle_max_velocity (float): Maximum particle velocity (to prevent instability)
shape_transform (wp.array): Rigid shape transforms, shape [shape_count, 7], float
shape_body (wp.array): Rigid shape body index, shape [shape_count], int
body_shapes (dict): Mapping from body index to list of attached shape indices
shape_materials (ModelShapeMaterials): Rigid shape contact materials, shape [shape_count], float
shape_shape_geo (ModelShapeGeometry): Shape geometry properties (geo type, scale, thickness, etc.), shape [shape_count, 3], float
shape_geo_src (list): List of `wp.Mesh` instances used for rendering of mesh geometry
shape_collision_group (list): Collision group of each shape, shape [shape_count], int
shape_collision_group_map (dict): Mapping from collision group to list of shape indices
shape_collision_filter_pairs (set): Pairs of shape indices that should not collide
shape_collision_radius (wp.array): Collision radius of each shape used for bounding sphere broadphase collision checking, shape [shape_count], float
shape_ground_collision (list): Indicates whether each shape should collide with the ground, shape [shape_count], bool
shape_contact_pairs (wp.array): Pairs of shape indices that may collide, shape [contact_pair_count, 2], int
shape_ground_contact_pairs (wp.array): Pairs of shape, ground indices that may collide, shape [ground_contact_pair_count, 2], int
spring_indices (wp.array): Particle spring indices, shape [spring_count*2], int
spring_rest_length (wp.array): Particle spring rest length, shape [spring_count], float
spring_stiffness (wp.array): Particle spring stiffness, shape [spring_count], float
spring_damping (wp.array): Particle spring damping, shape [spring_count], float
spring_control (wp.array): Particle spring activation, shape [spring_count], float
tri_indices (wp.array): Triangle element indices, shape [tri_count*3], int
tri_poses (wp.array): Triangle element rest pose, shape [tri_count, 2, 2], float
tri_activations (wp.array): Triangle element activations, shape [tri_count], float
tri_materials (wp.array): Triangle element materials, shape [tri_count, 5], float
edge_indices (wp.array): Bending edge indices, shape [edge_count*4], int
edge_rest_angle (wp.array): Bending edge rest angle, shape [edge_count], float
edge_bending_properties (wp.array): Bending edge stiffness and damping parameters, shape [edge_count, 2], float
tet_indices (wp.array): Tetrahedral element indices, shape [tet_count*4], int
tet_poses (wp.array): Tetrahedral rest poses, shape [tet_count, 3, 3], float
tet_activations (wp.array): Tetrahedral volumetric activations, shape [tet_count], float
tet_materials (wp.array): Tetrahedral elastic parameters in form :math:`k_{mu}, k_{lambda}, k_{damp}`, shape [tet_count, 3]
body_q (wp.array): Poses of rigid bodies used for state initialization, shape [body_count, 7], float
body_qd (wp.array): Velocities of rigid bodies used for state initialization, shape [body_count, 6], float
body_com (wp.array): Rigid body center of mass (in local frame), shape [body_count, 7], float
body_inertia (wp.array): Rigid body inertia tensor (relative to COM), shape [body_count, 3, 3], float
body_inv_inertia (wp.array): Rigid body inverse inertia tensor (relative to COM), shape [body_count, 3, 3], float
body_mass (wp.array): Rigid body mass, shape [body_count], float
body_inv_mass (wp.array): Rigid body inverse mass, shape [body_count], float
body_name (list): Rigid body names, shape [body_count], str
joint_q (wp.array): Generalized joint positions used for state initialization, shape [joint_coord_count], float
joint_qd (wp.array): Generalized joint velocities used for state initialization, shape [joint_dof_count], float
joint_act (wp.array): Generalized joint actuation force, shape [joint_dof_count], float
joint_type (wp.array): Joint type, shape [joint_count], int
joint_parent (wp.array): Joint parent body indices, shape [joint_count], int
joint_child (wp.array): Joint child body indices, shape [joint_count], int
joint_X_p (wp.array): Joint transform in parent frame, shape [joint_count, 7], float
joint_X_c (wp.array): Joint mass frame in child frame, shape [joint_count, 7], float
joint_axis (wp.array): Joint axis in child frame, shape [joint_axis_count, 3], float
joint_armature (wp.array): Armature for each joint, shape [joint_count], float
joint_target (wp.array): Joint target position/velocity (depending on joint axis mode), shape [joint_axis_count], float
joint_target_ke (wp.array): Joint stiffness, shape [joint_axis_count], float
joint_target_kd (wp.array): Joint damping, shape [joint_axis_count], float
joint_axis_start (wp.array): Start index of the first axis per joint, shape [joint_count], int
joint_axis_dim (wp.array): Number of linear and angular axes per joint, shape [joint_count, 2], int
joint_axis_mode (wp.array): Joint axis mode, shape [joint_axis_count], int
joint_linear_compliance (wp.array): Joint linear compliance, shape [joint_count], float
joint_angular_compliance (wp.array): Joint linear compliance, shape [joint_count], float
joint_enabled (wp.array): Joint enabled, shape [joint_count], int
joint_limit_lower (wp.array): Joint lower position limits, shape [joint_count], float
joint_limit_upper (wp.array): Joint upper position limits, shape [joint_count], float
joint_limit_ke (wp.array): Joint position limit stiffness (used by SemiImplicitIntegrator), shape [joint_count], float
joint_limit_kd (wp.array): Joint position limit damping (used by SemiImplicitIntegrator), shape [joint_count], float
joint_twist_lower (wp.array): Joint lower twist limit, shape [joint_count], float
joint_twist_upper (wp.array): Joint upper twist limit, shape [joint_count], float
joint_q_start (wp.array): Start index of the first position coordinate per joint, shape [joint_count], int
joint_qd_start (wp.array): Start index of the first velocity coordinate per joint, shape [joint_count], int
articulation_start (wp.array): Articulation start index, shape [articulation_count], int
joint_name (list): Joint names, shape [joint_count], str
joint_attach_ke (float): Joint attachment force stiffness (used by SemiImplicitIntegrator)
joint_attach_kd (float): Joint attachment force damping (used by SemiImplicitIntegrator)
soft_contact_margin (float): Contact margin for generation of soft contacts
soft_contact_ke (float): Stiffness of soft contacts (used by SemiImplicitIntegrator)
soft_contact_kd (float): Damping of soft contacts (used by SemiImplicitIntegrator)
soft_contact_kf (float): Stiffness of friction force in soft contacts (used by SemiImplicitIntegrator)
soft_contact_mu (float): Friction coefficient of soft contacts
soft_contact_restitution (float): Restitution coefficient of soft contacts (used by XPBDIntegrator)
rigid_contact_margin (float): Contact margin for generation of rigid body contacts
rigid_contact_torsional_friction (float): Torsional friction coefficient for rigid body contacts (used by XPBDIntegrator)
rigid_contact_rolling_friction (float): Rolling friction coefficient for rigid body contacts (used by XPBDIntegrator)
ground (bool): Whether the ground plane and ground contacts are enabled
ground_plane (wp.array): Ground plane 3D normal and offset, shape [4], float
up_vector (np.ndarray): Up vector of the world, shape [3], float
up_axis (int): Up axis, 0 for x, 1 for y, 2 for z
gravity (np.ndarray): Gravity vector, shape [3], float
particle_count (int): Total number of particles in the system
body_count (int): Total number of bodies in the system
shape_count (int): Total number of shapes in the system
joint_count (int): Total number of joints in the system
tri_count (int): Total number of triangles in the system
tet_count (int): Total number of tetrahedra in the system
edge_count (int): Total number of edges in the system
spring_count (int): Total number of springs in the system
contact_count (int): Total number of contacts in the system
muscle_count (int): Total number of muscles in the system
articulation_count (int): Total number of articulations in the system
joint_dof_count (int): Total number of velocity degrees of freedom of all joints in the system
joint_coord_count (int): Total number of position degrees of freedom of all joints in the system
device (wp.Device): Device on which the Model was allocated
Note:
It is strongly recommended to use the ModelBuilder to construct a simulation rather
than creating your own Model object directly, however it is possible to do so if
desired.
"""
def __init__(self, device=None):
self.requires_grad = False
self.num_envs = 0
self.particle_q = None
self.particle_qd = None
self.particle_mass = None
self.particle_inv_mass = None
self._particle_radius = None
self.particle_max_radius = 0.0
self.particle_ke = 1.0e3
self.particle_kd = 1.0e2
self.particle_kf = 1.0e2
self.particle_mu = 0.5
self.particle_cohesion = 0.0
self.particle_adhesion = 0.0
self.particle_grid = None
self.particle_flags = None
self.particle_max_velocity = 1e5
self.shape_transform = None
self.shape_body = None
self.body_shapes = {}
self.shape_materials = ModelShapeMaterials()
self.shape_geo = ModelShapeGeometry()
self.shape_geo_src = None
self.shape_collision_group = None
self.shape_collision_group_map = None
self.shape_collision_filter_pairs = None
self.shape_collision_radius = None
self.shape_ground_collision = None
self.shape_contact_pairs = None
self.shape_ground_contact_pairs = None
self.spring_indices = None
self.spring_rest_length = None
self.spring_stiffness = None
self.spring_damping = None
self.spring_control = None
self.tri_indices = None
self.tri_poses = None
self.tri_activations = None
self.tri_materials = None
self.edge_indices = None
self.edge_rest_angle = None
self.edge_bending_properties = None
self.tet_indices = None
self.tet_poses = None
self.tet_activations = None
self.tet_materials = None
self.body_q = None
self.body_qd = None
self.body_com = None
self.body_inertia = None
self.body_inv_inertia = None
self.body_mass = None
self.body_inv_mass = None
self.body_name = None
self.joint_q = None
self.joint_qd = None
self.joint_act = None
self.joint_type = None
self.joint_parent = None
self.joint_child = None
self.joint_X_p = None
self.joint_X_c = None
self.joint_axis = None
self.joint_armature = None
self.joint_target = None
self.joint_target_ke = None
self.joint_target_kd = None
self.joint_axis_start = None
self.joint_axis_dim = None
self.joint_axis_mode = None
self.joint_linear_compliance = None
self.joint_angular_compliance = None
self.joint_enabled = None
self.joint_limit_lower = None
self.joint_limit_upper = None
self.joint_limit_ke = None
self.joint_limit_kd = None
self.joint_twist_lower = None
self.joint_twist_upper = None
self.joint_q_start = None
self.joint_qd_start = None
self.articulation_start = None
self.joint_name = None
# todo: per-joint values?
self.joint_attach_ke = 1.0e3
self.joint_attach_kd = 1.0e2
self.soft_contact_margin = 0.2
self.soft_contact_ke = 1.0e3
self.soft_contact_kd = 10.0
self.soft_contact_kf = 1.0e3
self.soft_contact_mu = 0.5
self.soft_contact_restitution = 0.0
self.rigid_contact_margin = None
self.rigid_contact_torsional_friction = None
self.rigid_contact_rolling_friction = None
# toggles ground contact for all shapes
self.ground = True
self.ground_plane = None
self.up_vector = np.array((0.0, 1.0, 0.0))
self.up_axis = 1
self.gravity = np.array((0.0, -9.81, 0.0))
self.particle_count = 0
self.body_count = 0
self.shape_count = 0
self.joint_count = 0
self.joint_axis_count = 0
self.tri_count = 0
self.tet_count = 0
self.edge_count = 0
self.spring_count = 0
self.muscle_count = 0
self.articulation_count = 0
self.joint_dof_count = 0
self.joint_coord_count = 0
self.device = wp.get_device(device)
def state(self, requires_grad=None) -> State:
"""Returns a state object for the model
The returned state will be initialized with the initial configuration given in
the model description.
"""
s = State()
if requires_grad is None:
requires_grad = self.requires_grad
s.particle_count = self.particle_count
s.body_count = self.body_count
# --------------------------------
# dynamic state (input, output)
# particles
if self.particle_count:
s.particle_q = wp.clone(self.particle_q)
s.particle_qd = wp.clone(self.particle_qd)
s.particle_f = wp.zeros_like(self.particle_qd)
s.particle_q.requires_grad = requires_grad
s.particle_qd.requires_grad = requires_grad
s.particle_f.requires_grad = requires_grad
# articulations
if self.body_count:
s.body_q = wp.clone(self.body_q)
s.body_qd = wp.clone(self.body_qd)
s.body_f = wp.zeros_like(self.body_qd)
s.body_deltas = wp.zeros(
self.body_count, dtype=wp.spatial_vector, device=s.body_q.device, requires_grad=requires_grad
)
s.body_q.requires_grad = requires_grad
s.body_qd.requires_grad = requires_grad
s.body_f.requires_grad = requires_grad
return s
def allocate_soft_contacts(self, count, requires_grad=False):
self.soft_contact_count = wp.zeros(1, dtype=wp.int32, device=self.device)
self.soft_contact_particle = wp.zeros(count, dtype=int, device=self.device)
self.soft_contact_shape = wp.zeros(count, dtype=int, device=self.device)
self.soft_contact_body_pos = wp.zeros(count, dtype=wp.vec3, device=self.device, requires_grad=requires_grad)
self.soft_contact_body_vel = wp.zeros(count, dtype=wp.vec3, device=self.device, requires_grad=requires_grad)
self.soft_contact_normal = wp.zeros(count, dtype=wp.vec3, device=self.device, requires_grad=requires_grad)
def find_shape_contact_pairs(self):
# find potential contact pairs based on collision groups and collision mask (pairwise filtering)
import copy
import itertools
filters = copy.copy(self.shape_collision_filter_pairs)
for a, b in self.shape_collision_filter_pairs:
filters.add((b, a))
contact_pairs = []
# iterate over collision groups (islands)
for group, shapes in self.shape_collision_group_map.items():
for shape_a, shape_b in itertools.product(shapes, shapes):
if shape_a < shape_b and (shape_a, shape_b) not in filters:
contact_pairs.append((shape_a, shape_b))
if group != -1 and -1 in self.shape_collision_group_map:
# shapes with collision group -1 collide with all other shapes
for shape_a, shape_b in itertools.product(shapes, self.shape_collision_group_map[-1]):
if shape_a < shape_b and (shape_a, shape_b) not in filters:
contact_pairs.append((shape_a, shape_b))
self.shape_contact_pairs = wp.array(np.array(contact_pairs), dtype=wp.int32, device=self.device)
self.shape_contact_pair_count = len(contact_pairs)
# find ground contact pairs
ground_contact_pairs = []
ground_id = self.shape_count - 1
for i in range(ground_id):
if self.shape_ground_collision[i]:
ground_contact_pairs.append((i, ground_id))
self.shape_ground_contact_pairs = wp.array(np.array(ground_contact_pairs), dtype=wp.int32, device=self.device)
self.shape_ground_contact_pair_count = len(ground_contact_pairs)
def count_contact_points(self):
"""
Counts the maximum number of contact points that need to be allocated.
"""
from .collide import count_contact_points
# calculate the potential number of shape pair contact points
contact_count = wp.zeros(1, dtype=wp.int32, device=self.device)
wp.launch(
kernel=count_contact_points,
dim=self.shape_contact_pair_count,
inputs=[
self.shape_contact_pairs,
self.shape_geo,
],
outputs=[contact_count],
device=self.device,
record_tape=False,
)
# count ground contacts
wp.launch(
kernel=count_contact_points,
dim=self.shape_ground_contact_pair_count,
inputs=[
self.shape_ground_contact_pairs,
self.shape_geo,
],
outputs=[contact_count],
device=self.device,
record_tape=False,
)
count = contact_count.numpy()[0]
return int(count)
def allocate_rigid_contacts(self, count=None, requires_grad=False):
if count is not None:
self.rigid_contact_max = count
# serves as counter of the number of active contact points
self.rigid_contact_count = wp.zeros(1, dtype=wp.int32, device=self.device)
# contact point ID within the (shape_a, shape_b) contact pair
self.rigid_contact_point_id = wp.zeros(self.rigid_contact_max, dtype=wp.int32, device=self.device)
# ID of first rigid body
self.rigid_contact_body0 = wp.zeros(self.rigid_contact_max, dtype=wp.int32, device=self.device)
# ID of second rigid body
self.rigid_contact_body1 = wp.zeros(self.rigid_contact_max, dtype=wp.int32, device=self.device)
# position of contact point in body 0's frame before the integration step
self.rigid_contact_point0 = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# position of contact point in body 1's frame before the integration step
self.rigid_contact_point1 = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# moment arm before the integration step resulting from thickness displacement added to contact point 0 in body 0's frame (used in XPBD contact friction handling)
self.rigid_contact_offset0 = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# moment arm before the integration step resulting from thickness displacement added to contact point 1 in body 1's frame (used in XPBD contact friction handling)
self.rigid_contact_offset1 = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# contact normal in world frame
self.rigid_contact_normal = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# combined thickness of both shapes
self.rigid_contact_thickness = wp.zeros(
self.rigid_contact_max, dtype=wp.float32, device=self.device, requires_grad=requires_grad
)
# ID of the first shape in the contact pair
self.rigid_contact_shape0 = wp.zeros(self.rigid_contact_max, dtype=wp.int32, device=self.device)
# ID of the second shape in the contact pair
self.rigid_contact_shape1 = wp.zeros(self.rigid_contact_max, dtype=wp.int32, device=self.device)
# temporary variables used during the XPBD solver iterations:
# world space position of contact point resulting from applying current body 0 transform to its point0
self.rigid_active_contact_point0 = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# world space position of contact point resulting from applying current body 1 transform to its point1
self.rigid_active_contact_point1 = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# current contact distance (negative penetration depth)
self.rigid_active_contact_distance = wp.zeros(
self.rigid_contact_max, dtype=wp.float32, device=self.device, requires_grad=requires_grad
)
# contact distance before the solver iterations
self.rigid_active_contact_distance_prev = wp.zeros(
self.rigid_contact_max, dtype=wp.float32, device=self.device, requires_grad=requires_grad
)
# world space position of point0 before the solver iterations
self.rigid_active_contact_point0_prev = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# world space position of point1 before the solver iterations
self.rigid_active_contact_point1_prev = wp.zeros(
self.rigid_contact_max, dtype=wp.vec3, device=self.device, requires_grad=requires_grad
)
# number of contact constraints per rigid body (used for scaling the constraint contributions, a basic version of mass splitting)
self.rigid_contact_inv_weight = wp.zeros(
len(self.body_q), dtype=wp.float32, device=self.device, requires_grad=requires_grad
)
# number of contact constraints before the solver iterations
self.rigid_contact_inv_weight_prev = wp.zeros(
len(self.body_q), dtype=wp.float32, device=self.device, requires_grad=requires_grad
)
def flatten(self):
"""Returns a list of Tensors stored by the model
This function is intended to be used internal-only but can be used to obtain
a set of all tensors owned by the model.
"""
tensors = []
# build a list of all tensor attributes
for attr, value in self.__dict__.items():
if wp.is_tensor(value):
tensors.append(value)
return tensors
def collide(self, state: State):
wp.utils.warn(
"Model.collide() is not needed anymore and will be removed in a future Warp version.",
DeprecationWarning,
stacklevel=2,
)
@property
def soft_contact_max(self):
"""Maximum number of soft contacts that can be registered"""
return len(self.soft_contact_particle)
@property
def soft_contact_distance(self):
wp.utils.warn(
"Model.soft_contact_distance is deprecated and will be removed in a future Warp version. "
"Particles now have individual radii, returning `Model.particle_max_radius`.",
DeprecationWarning,
stacklevel=2,
)
return self.particle_max_radius
@soft_contact_distance.setter
def soft_contact_distance(self, value):
wp.utils.warn(
"Model.soft_contact_distance is deprecated and will be removed in a future Warp version. "
"Particles now have individual radii, see `Model.particle_radius`.",
DeprecationWarning,
stacklevel=2,
)
@property
def particle_radius(self):
"""Array of per-particle radii"""
return self._particle_radius
@particle_radius.setter
def particle_radius(self, value):
if isinstance(value, float):
wp.utils.warn(
"Model.particle_radius is an array of per-particle radii, assigning with a scalar value "
"is deprecated and will be removed in a future Warp version.",
PendingDeprecationWarning,
stacklevel=2,
)
self._particle_radius.fill_(value)
self.particle_max_radius = value
else:
self._particle_radius = value
# TODO implement max radius update to be compatible with graph capture
device = wp.get_device(self.device)
if not device.is_capturing:
self.particle_max_radius = self._particle_radius.numpy().max()
class ModelBuilder:
"""A helper class for building simulation models at runtime.
Use the ModelBuilder to construct a simulation scene. The ModelBuilder
and builds the scene representation using standard Python data structures (lists),
this means it is not differentiable. Once :func:`finalize()`
has been called the ModelBuilder transfers all data to Warp tensors and returns
an object that may be used for simulation.
Example
-------
.. code-block:: python
import warp as wp
import warp.sim
builder = wp.sim.ModelBuilder()
# anchor point (zero mass)
builder.add_particle((0, 1.0, 0.0), (0.0, 0.0, 0.0), 0.0)
# build chain
for i in range(1,10):
builder.add_particle((i, 1.0, 0.0), (0.0, 0.0, 0.0), 1.0)
builder.add_spring(i-1, i, 1.e+3, 0.0, 0)
# create model
model = builder.finalize("cuda")
state = model.state()
integrator = wp.sim.SemiImplicitIntegrator()
for i in range(100):
state.clear_forces()
integrator.simulate(model, state, state, dt=1.0/60.0)
Note:
It is strongly recommended to use the ModelBuilder to construct a simulation rather
than creating your own Model object directly, however it is possible to do so if
desired.
"""
# Default particle settings
default_particle_radius = 0.1
# Default triangle soft mesh settings
default_tri_ke = 100.0
default_tri_ka = 100.0
default_tri_kd = 10.0
default_tri_drag = 0.0
default_tri_lift = 0.0
# Default distance constraint properties
default_spring_ke = 100.0
default_spring_kd = 0.0
# Default edge bending properties
default_edge_ke = 100.0
default_edge_kd = 0.0
# Default rigid shape contact material properties
default_shape_ke = 1.0e5
default_shape_kd = 1000.0
default_shape_kf = 1000.0
default_shape_mu = 0.5
default_shape_restitution = 0.0
default_shape_density = 1000.0
# Default joint settings
default_joint_limit_ke = 100.0
default_joint_limit_kd = 1.0
# Default geo settings
default_geo_thickness = 1e-5
def __init__(self, up_vector=(0.0, 1.0, 0.0), gravity=-9.80665):
self.num_envs = 0
# particles
self.particle_q = []
self.particle_qd = []
self.particle_mass = []
self.particle_radius = []
self.particle_flags = []
self.particle_max_velocity = 1e5
# shapes (each shape has an entry in these arrays)
# transform from shape to body
self.shape_transform = []
# maps from shape index to body index
self.shape_body = []
self.shape_geo_type = []
self.shape_geo_scale = []
self.shape_geo_src = []
self.shape_geo_is_solid = []
self.shape_geo_thickness = []
self.shape_material_ke = []
self.shape_material_kd = []
self.shape_material_kf = []
self.shape_material_mu = []
self.shape_material_restitution = []
# collision groups within collisions are handled
self.shape_collision_group = []
self.shape_collision_group_map = {}
self.last_collision_group = 0
# radius to use for broadphase collision checking
self.shape_collision_radius = []
# whether the shape collides with the ground
self.shape_ground_collision = []
# filtering to ignore certain collision pairs
self.shape_collision_filter_pairs = set()
# geometry
self.geo_meshes = []
self.geo_sdfs = []
# springs
self.spring_indices = []
self.spring_rest_length = []
self.spring_stiffness = []
self.spring_damping = []
self.spring_control = []
# triangles
self.tri_indices = []
self.tri_poses = []
self.tri_activations = []
self.tri_materials = []
# edges (bending)
self.edge_indices = []
self.edge_rest_angle = []
self.edge_bending_properties = []
# tetrahedra
self.tet_indices = []
self.tet_poses = []
self.tet_activations = []
self.tet_materials = []
# muscles
self.muscle_start = []
self.muscle_params = []
self.muscle_activation = []
self.muscle_bodies = []
self.muscle_points = []
# rigid bodies
self.body_mass = []
self.body_inertia = []
self.body_inv_mass = []
self.body_inv_inertia = []
self.body_com = []
self.body_q = []
self.body_qd = []
self.body_name = []
self.body_shapes = {} # mapping from body to shapes
# rigid joints
self.joint = {}
self.joint_parent = [] # index of the parent body (constant)
self.joint_parents = {} # mapping from joint to parent bodies
self.joint_child = [] # index of the child body (constant)
self.joint_axis = [] # joint axis in child joint frame (constant)
self.joint_X_p = [] # frame of joint in parent (constant)
self.joint_X_c = [] # frame of child com (in child coordinates) (constant)
self.joint_q = []
self.joint_qd = []
self.joint_type = []
self.joint_name = []
self.joint_armature = []
self.joint_target = []
self.joint_target_ke = []
self.joint_target_kd = []
self.joint_axis_mode = []
self.joint_limit_lower = []
self.joint_limit_upper = []
self.joint_limit_ke = []
self.joint_limit_kd = []
self.joint_act = []
self.joint_twist_lower = []
self.joint_twist_upper = []
self.joint_linear_compliance = []
self.joint_angular_compliance = []
self.joint_enabled = []
self.joint_q_start = []
self.joint_qd_start = []
self.joint_axis_start = []
self.joint_axis_dim = []
self.articulation_start = []
self.joint_dof_count = 0
self.joint_coord_count = 0
self.joint_axis_total_count = 0
self.up_vector = np.array(up_vector)
self.up_axis = np.argmax(np.abs(up_vector))
self.gravity = gravity
# indicates whether a ground plane has been created
self._ground_created = False
# constructor parameters for ground plane shape
self._ground_params = dict(
plane=(*up_vector, 0.0),
width=0.0,
length=0.0,
ke=self.default_shape_ke,
kd=self.default_shape_kd,
kf=self.default_shape_kf,
mu=self.default_shape_mu,
restitution=self.default_shape_restitution,
)
# Maximum number of soft contacts that can be registered
self.soft_contact_max = 64 * 1024
# contacts to be generated within the given distance margin to be generated at
# every simulation substep (can be 0 if only one PBD solver iteration is used)
self.rigid_contact_margin = 0.1
# torsional friction coefficient (only considered by XPBD so far)
self.rigid_contact_torsional_friction = 0.5
# rolling friction coefficient (only considered by XPBD so far)
self.rigid_contact_rolling_friction = 0.001
# number of rigid contact points to allocate in the model during self.finalize() per environment
# if setting is None, the number of worst-case number of contacts will be calculated in self.finalize()
self.num_rigid_contacts_per_env = None
@property
def shape_count(self):
return len(self.shape_geo_type)
@property
def body_count(self):
return len(self.body_q)
@property
def joint_count(self):
return len(self.joint_type)
@property
def joint_axis_count(self):
return len(self.joint_axis)
@property
def particle_count(self):
return len(self.particle_q)
@property
def tri_count(self):
return len(self.tri_poses)
@property
def tet_count(self):
return len(self.tet_poses)
@property
def edge_count(self):
return len(self.edge_rest_angle)
@property
def spring_count(self):
return len(self.spring_rest_length)
@property
def muscle_count(self):
return len(self.muscle_start)
@property
def articulation_count(self):
return len(self.articulation_start)
# an articulation is a set of contiguous bodies bodies from articulation_start[i] to articulation_start[i+1]
# these are used for computing forward kinematics e.g.:
#
# model.eval_articulation_fk()
# model.eval_articulation_j()
# model.eval_articulation_m()
#
# articulations are automatically 'closed' when calling finalize
def add_articulation(self):
self.articulation_start.append(self.joint_count)
def add_builder(self, articulation, xform=None, update_num_env_count=True, separate_collision_group=True):
"""Copies a rigid articulation from `articulation`, another `ModelBuilder`.
Args:
articulation: a model builder to add rigid articulation from.
xform: offset transform applied to root bodies.
update_num_env_count: if True, the number of environments is incremented by 1.
separate_collision_group: if True, the shapes from the articulation will all be put into a single new collision group, otherwise, only the shapes in collision group > -1 will be moved to a new group.
"""
start_body_idx = self.body_count
start_shape_idx = self.shape_count
for s, b in enumerate(articulation.shape_body):
if b > -1:
new_b = b + start_body_idx
self.shape_body.append(new_b)
self.shape_transform.append(articulation.shape_transform[s])
else:
self.shape_body.append(-1)
# apply offset transform to root bodies
if xform is not None:
self.shape_transform.append(xform * articulation.shape_transform[s])
for b, shapes in articulation.body_shapes.items():
self.body_shapes[b + start_body_idx] = [s + start_shape_idx for s in shapes]
if articulation.joint_count:
joint_X_p = copy.deepcopy(articulation.joint_X_p)
joint_q = copy.deepcopy(articulation.joint_q)
if xform is not None:
for i in range(len(joint_X_p)):
if articulation.joint_type[i] == wp.sim.JOINT_FREE:
qi = articulation.joint_q_start[i]
xform_prev = wp.transform(joint_q[qi : qi + 3], joint_q[qi + 3 : qi + 7])
tf = xform * xform_prev
joint_q[qi : qi + 3] = tf.p
joint_q[qi + 3 : qi + 7] = tf.q
elif articulation.joint_parent[i] == -1:
joint_X_p[i] = xform * joint_X_p[i]
self.joint_X_p.extend(joint_X_p)
self.joint_q.extend(joint_q)
self.add_articulation()
# offset the indices
self.joint_parent.extend([p + self.joint_count if p != -1 else -1 for p in articulation.joint_parent])
self.joint_child.extend([c + self.joint_count for c in articulation.joint_child])
self.joint_q_start.extend([c + self.joint_coord_count for c in articulation.joint_q_start])
self.joint_qd_start.extend([c + self.joint_dof_count for c in articulation.joint_qd_start])
self.joint_axis_start.extend([a + self.joint_axis_total_count for a in articulation.joint_axis_start])
joint_children = set(articulation.joint_child)
for i in range(articulation.body_count):
if xform is not None and i not in joint_children:
# rigid body is not attached to a joint, so apply input transform directly
self.body_q.append(xform * articulation.body_q[i])
else:
self.body_q.append(articulation.body_q[i])
# apply collision group
if separate_collision_group:
self.shape_collision_group.extend(
[self.last_collision_group + 1 for _ in articulation.shape_collision_group]
)
else:
self.shape_collision_group.extend(
[(g + self.last_collision_group if g > -1 else -1) for g in articulation.shape_collision_group]
)
shape_count = self.shape_count
for i, j in articulation.shape_collision_filter_pairs:
self.shape_collision_filter_pairs.add((i + shape_count, j + shape_count))
for group, shapes in articulation.shape_collision_group_map.items():
if separate_collision_group:
group = self.last_collision_group + 1
else:
group = group + self.last_collision_group if group > -1 else -1
if group not in self.shape_collision_group_map:
self.shape_collision_group_map[group] = []
self.shape_collision_group_map[group].extend([s + shape_count for s in shapes])
# update last collision group counter
if separate_collision_group:
self.last_collision_group += 1
elif articulation.last_collision_group > -1:
self.last_collision_group += articulation.last_collision_group
rigid_articulation_attrs = [
"body_inertia",
"body_mass",
"body_inv_inertia",
"body_inv_mass",
"body_com",
"body_qd",
"body_name",
"joint_type",
"joint_enabled",
"joint_X_c",
"joint_armature",
"joint_axis",
"joint_axis_dim",
"joint_axis_mode",
"joint_name",
"joint_qd",
"joint_act",
"joint_limit_lower",
"joint_limit_upper",
"joint_limit_ke",
"joint_limit_kd",
"joint_target",
"joint_target_ke",
"joint_target_kd",
"joint_linear_compliance",
"joint_angular_compliance",
"shape_geo_type",
"shape_geo_scale",
"shape_geo_src",
"shape_geo_is_solid",
"shape_geo_thickness",
"shape_material_ke",
"shape_material_kd",
"shape_material_kf",
"shape_material_mu",
"shape_material_restitution",
"shape_collision_radius",
"shape_ground_collision",
]
for attr in rigid_articulation_attrs:
getattr(self, attr).extend(getattr(articulation, attr))
self.joint_dof_count += articulation.joint_dof_count
self.joint_coord_count += articulation.joint_coord_count
self.joint_axis_total_count += articulation.joint_axis_total_count
self.up_vector = articulation.up_vector
self.gravity = articulation.gravity
if update_num_env_count:
self.num_envs += 1
# register a rigid body and return its index.
def add_body(
self,
origin: Transform = wp.transform(),
armature: float = 0.0,
com: Vec3 = np.zeros(3),
I_m: Mat33 = np.zeros((3, 3)),
m: float = 0.0,
name: str = None,
) -> int:
"""Adds a rigid body to the model.
Args:
origin: The location of the body in the world frame
armature: Artificial inertia added to the body
com: The center of mass of the body w.r.t its origin
I_m: The 3x3 inertia tensor of the body (specified relative to the center of mass)
m: Mass of the body
name: Name of the body (optional)
Returns:
The index of the body in the model
Note:
If the mass (m) is zero then the body is treated as kinematic with no dynamics
"""
body_id = len(self.body_mass)
# body data
inertia = I_m + np.eye(3) * armature
self.body_inertia.append(inertia)
self.body_mass.append(m)
self.body_com.append(com)
if m > 0.0:
self.body_inv_mass.append(1.0 / m)
else:
self.body_inv_mass.append(0.0)
if inertia.any():
self.body_inv_inertia.append(np.linalg.inv(inertia))
else:
self.body_inv_inertia.append(inertia)
self.body_q.append(origin)
self.body_qd.append(wp.spatial_vector())
self.body_name.append(name or f"body {body_id}")
self.body_shapes[body_id] = []
return body_id
def add_joint(
self,
joint_type: wp.constant,
parent: int,
child: int,
linear_axes: List[JointAxis] = [],
angular_axes: List[JointAxis] = [],
name: str = None,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""
Generic method to add any type of joint to this ModelBuilder.
Args:
joint_type: The type of joint to add (see `Joint types`_)
parent: The index of the parent body (-1 is the world)
child: The index of the child body
linear_axes: The linear axes (see :class:`JointAxis`) of the joint
angular_axes: The angular axes (see :class:`JointAxis`) of the joint
name: The name of the joint
parent_xform: The transform of the joint in the parent body's local frame
child_xform: The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
self.joint_type.append(joint_type)
self.joint_parent.append(parent)
if child not in self.joint_parents:
self.joint_parents[child] = [parent]
else:
self.joint_parents[child].append(parent)
self.joint_child.append(child)
self.joint_X_p.append([*parent_xform])
self.joint_X_c.append([*child_xform])
self.joint_name.append(name or f"joint {self.joint_count}")
self.joint_axis_start.append(len(self.joint_axis))
self.joint_axis_dim.append((len(linear_axes), len(angular_axes)))
self.joint_axis_total_count += len(linear_axes) + len(angular_axes)
self.joint_linear_compliance.append(linear_compliance)
self.joint_angular_compliance.append(angular_compliance)
self.joint_enabled.append(enabled)
def add_axis_dim(dim):
self.joint_axis.append(dim.axis)
self.joint_axis_mode.append(dim.mode)
self.joint_target.append(dim.target)
self.joint_target_ke.append(dim.target_ke)
self.joint_target_kd.append(dim.target_kd)
self.joint_limit_ke.append(dim.limit_ke)
self.joint_limit_kd.append(dim.limit_kd)
if np.isfinite(dim.limit_lower):
self.joint_limit_lower.append(dim.limit_lower)
else:
self.joint_limit_lower.append(-1e6)
if np.isfinite(dim.limit_upper):
self.joint_limit_upper.append(dim.limit_upper)
else:
self.joint_limit_upper.append(1e6)
# self.joint_limit_lower.append(dim.limit_lower)
# self.joint_limit_upper.append(dim.limit_upper)
for dim in linear_axes:
add_axis_dim(dim)
for dim in angular_axes:
add_axis_dim(dim)
if joint_type == JOINT_PRISMATIC:
dof_count = 1
coord_count = 1
elif joint_type == JOINT_REVOLUTE:
dof_count = 1
coord_count = 1
elif joint_type == JOINT_BALL:
dof_count = 3
coord_count = 4
elif joint_type == JOINT_FREE:
dof_count = 6
coord_count = 7
elif joint_type == JOINT_FIXED:
dof_count = 0
coord_count = 0
elif joint_type == JOINT_UNIVERSAL:
dof_count = 2
coord_count = 2
elif joint_type == JOINT_COMPOUND:
dof_count = 3
coord_count = 3
elif joint_type == JOINT_DISTANCE:
# todo use free joint dofs?
dof_count = 0
coord_count = 0
elif joint_type == JOINT_D6:
dof_count = len(linear_axes) + len(angular_axes)
coord_count = dof_count
for i in range(coord_count):
self.joint_q.append(0.0)
for i in range(dof_count):
self.joint_qd.append(0.0)
self.joint_act.append(0.0)
if joint_type == JOINT_FREE or joint_type == JOINT_BALL:
# ensure that a valid quaternion is used for the angular dofs
self.joint_q[-1] = 1.0
self.joint_q_start.append(self.joint_coord_count)
self.joint_qd_start.append(self.joint_dof_count)
self.joint_dof_count += dof_count
self.joint_coord_count += coord_count
if collision_filter_parent and parent > -1:
for child_shape in self.body_shapes[child]:
for parent_shape in self.body_shapes[parent]:
self.shape_collision_filter_pairs.add((parent_shape, child_shape))
return self.joint_count - 1
def add_joint_revolute(
self,
parent: int,
child: int,
parent_xform: wp.transform,
child_xform: wp.transform,
axis: Vec3,
target: float = 0.0,
target_ke: float = 0.0,
target_kd: float = 0.0,
mode: int = JOINT_MODE_TARGET_POSITION,
limit_lower: float = -2 * math.pi,
limit_upper: float = 2 * math.pi,
limit_ke: float = default_joint_limit_ke,
limit_kd: float = default_joint_limit_kd,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a revolute joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform: The transform of the joint in the parent body's local frame
child_xform: The transform of the joint in the child body's local frame
axis: The axis of rotation in the parent body's local frame
target: The target angle (in radians) of the joint
target_ke: The stiffness of the joint target
target_kd: The damping of the joint target
limit_lower: The lower limit of the joint
limit_upper: The upper limit of the joint
limit_ke: The stiffness of the joint limit
limit_kd: The damping of the joint limit
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
ax = JointAxis(
axis=axis,
limit_lower=limit_lower,
limit_upper=limit_upper,
target=target,
target_ke=target_ke,
target_kd=target_kd,
mode=mode,
limit_ke=limit_ke,
limit_kd=limit_kd,
)
return self.add_joint(
JOINT_REVOLUTE,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
angular_axes=[ax],
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_prismatic(
self,
parent: int,
child: int,
parent_xform: wp.transform,
child_xform: wp.transform,
axis: Vec3,
target: float = 0.0,
target_ke: float = 0.0,
target_kd: float = 0.0,
mode: int = JOINT_MODE_TARGET_POSITION,
limit_lower: float = -1e4,
limit_upper: float = 1e4,
limit_ke: float = default_joint_limit_ke,
limit_kd: float = default_joint_limit_kd,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a prismatic joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform: The transform of the joint in the parent body's local frame
child_xform: The transform of the joint in the child body's local frame
axis: The axis of rotation in the parent body's local frame
target: The target position of the joint
target_ke: The stiffness of the joint target
target_kd: The damping of the joint target
limit_lower: The lower limit of the joint
limit_upper: The upper limit of the joint
limit_ke: The stiffness of the joint limit
limit_kd: The damping of the joint limit
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
ax = JointAxis(
axis=axis,
limit_lower=limit_lower,
limit_upper=limit_upper,
target=target,
target_ke=target_ke,
target_kd=target_kd,
mode=mode,
limit_ke=limit_ke,
limit_kd=limit_kd,
)
return self.add_joint(
JOINT_PRISMATIC,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_axes=[ax],
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_ball(
self,
parent: int,
child: int,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a ball joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
return self.add_joint(
JOINT_BALL,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_fixed(
self,
parent: int,
child: int,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a fixed joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
return self.add_joint(
JOINT_FIXED,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_free(
self,
child: int,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
parent: int = -1,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a free joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
return self.add_joint(
JOINT_FREE,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_distance(
self,
parent: int,
child: int,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
min_distance: float = -1.0,
max_distance: float = 1.0,
compliance: float = 0.0,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a distance joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
min_distance: The minimum distance between the bodies (no limit if negative)
max_distance: The maximum distance between the bodies (no limit if negative)
compliance: The compliance of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
ax = JointAxis(
axis=(1.0, 0.0, 0.0),
limit_lower=min_distance,
limit_upper=max_distance,
)
return self.add_joint(
JOINT_DISTANCE,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_axes=[ax],
linear_compliance=compliance,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_universal(
self,
parent: int,
child: int,
axis_0: JointAxis,
axis_1: JointAxis,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a universal joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
axis_0: The first axis of the joint
axis_1: The second axis of the joint
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
return self.add_joint(
JOINT_UNIVERSAL,
parent,
child,
angular_axes=[axis_0, axis_1],
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_compound(
self,
parent: int,
child: int,
axis_0: JointAxis,
axis_1: JointAxis,
axis_2: JointAxis,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a compound joint to the model
Args:
parent: The index of the parent body
child: The index of the child body
axis_0: The first axis of the joint
axis_1: The second axis of the joint
axis_2: The third axis of the joint
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
return self.add_joint(
JOINT_COMPOUND,
parent,
child,
angular_axes=[axis_0, axis_1, axis_2],
parent_xform=parent_xform,
child_xform=child_xform,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_d6(
self,
parent: int,
child: int,
linear_axes: List[JointAxis] = [],
angular_axes: List[JointAxis] = [],
name: str = None,
parent_xform: wp.transform = wp.transform(),
child_xform: wp.transform = wp.transform(),
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
collision_filter_parent: bool = True,
enabled: bool = True,
):
"""Adds a generic joint with custom linear and angular axes.
Args:
parent: The index of the parent body
child: The index of the child body
linear_axes: A list of linear axes
angular_axes: A list of angular axes
name: The name of the joint
parent_xform: The transform of the joint in the parent body's local frame
xform: The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the child body
"""
return self.add_joint(
JOINT_D6,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_axes=linear_axes,
angular_axes=angular_axes,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def collapse_fixed_joints(self, verbose=wp.config.verbose):
"""Removes fixed joints from the model and merges the bodies they connect."""
body_data = {}
body_children = {-1: []}
visited = {}
for i in range(self.body_count):
name = self.body_name[i]
body_data[i] = {
"shapes": self.body_shapes[i],
"q": self.body_q[i],
"qd": self.body_qd[i],
"mass": self.body_mass[i],
"inertia": self.body_inertia[i],
"inv_mass": self.body_inv_mass[i],
"inv_inertia": self.body_inv_inertia[i],
"com": self.body_com[i],
"name": name,
"original_id": i,
}
visited[i] = False
body_children[i] = []
joint_data = {}
for i in range(self.joint_count):
name = self.joint_name[i]
parent = self.joint_parent[i]
child = self.joint_child[i]
body_children[parent].append(child)
q_start = self.joint_q_start[i]
qd_start = self.joint_qd_start[i]
if i < self.joint_count - 1:
q_dim = self.joint_q_start[i + 1] - q_start
qd_dim = self.joint_qd_start[i + 1] - qd_start
else:
q_dim = len(self.joint_q) - q_start
qd_dim = len(self.joint_qd) - qd_start
data = {
"type": self.joint_type[i],
# 'armature': self.joint_armature[i],
"q": self.joint_q[q_start : q_start + q_dim],
"qd": self.joint_qd[qd_start : qd_start + qd_dim],
"act": self.joint_act[qd_start : qd_start + qd_dim],
"q_start": q_start,
"qd_start": qd_start,
"linear_compliance": self.joint_linear_compliance[i],
"angular_compliance": self.joint_angular_compliance[i],
"name": name,
"parent_xform": wp.transform_expand(self.joint_X_p[i]),
"child_xform": wp.transform_expand(self.joint_X_c[i]),
"enabled": self.joint_enabled[i],
"axes": [],
"axis_dim": self.joint_axis_dim[i],
"parent": parent,
"child": child,
"original_id": i,
}
num_lin_axes, num_ang_axes = self.joint_axis_dim[i]
start_ax = self.joint_axis_start[i]
for j in range(start_ax, start_ax + num_lin_axes + num_ang_axes):
data["axes"].append(
{
"axis": self.joint_axis[j],
"axis_mode": self.joint_axis_mode[j],
"target": self.joint_target[j],
"target_ke": self.joint_target_ke[j],
"target_kd": self.joint_target_kd[j],
"limit_ke": self.joint_limit_ke[j],
"limit_kd": self.joint_limit_kd[j],
"limit_lower": self.joint_limit_lower[j],
"limit_upper": self.joint_limit_upper[j],
}
)
joint_data[(parent, child)] = data
# sort body children so we traverse the tree in the same order as the bodies are listed
for children in body_children.values():
children.sort(key=lambda x: body_data[x]["original_id"])
retained_joints = []
retained_bodies = []
body_remap = {-1: -1}
# depth first search over the joint graph
def dfs(parent_body: int, child_body: int, incoming_xform: wp.transform, last_dynamic_body: int):
nonlocal visited
nonlocal retained_joints
nonlocal retained_bodies
nonlocal body_data
nonlocal body_remap
joint = joint_data[(parent_body, child_body)]
if joint["type"] == JOINT_FIXED:
joint_xform = joint["parent_xform"] * wp.transform_inverse(joint["child_xform"])
incoming_xform = incoming_xform * joint_xform
parent_name = self.body_name[parent_body] if parent_body > -1 else "world"
child_name = self.body_name[child_body]
last_dynamic_body_name = self.body_name[last_dynamic_body] if last_dynamic_body > -1 else "world"
if verbose:
print(
f'Remove fixed joint {joint["name"]} between {parent_name} and {child_name}, '
f"merging {child_name} into {last_dynamic_body_name}"
)
child_id = body_data[child_body]["original_id"]
for shape in self.body_shapes[child_id]:
self.shape_transform[shape] = incoming_xform * self.shape_transform[shape]
if verbose:
print(
f" Shape {shape} moved to body {last_dynamic_body_name} with transform {self.shape_transform[shape]}"
)
if last_dynamic_body > -1:
self.shape_body[shape] = body_data[last_dynamic_body]["id"]
# add inertia to last_dynamic_body
m = body_data[child_body]["mass"]
com = body_data[child_body]["com"]
inertia = body_data[child_body]["inertia"]
body_data[last_dynamic_body]["inertia"] += wp.sim.transform_inertia(
m, inertia, incoming_xform.p, incoming_xform.q
)
body_data[last_dynamic_body]["mass"] += m
source_m = body_data[last_dynamic_body]["mass"]
source_com = body_data[last_dynamic_body]["com"]
body_data[last_dynamic_body]["com"] = (m * com + source_m * source_com) / (m + source_m)
body_data[last_dynamic_body]["shapes"].append(shape)
# indicate to recompute inverse mass, inertia for this body
body_data[last_dynamic_body]["inv_mass"] = None
else:
self.shape_body[shape] = -1
else:
joint["parent_xform"] = incoming_xform * joint["parent_xform"]
joint["parent"] = last_dynamic_body
last_dynamic_body = child_body
incoming_xform = wp.transform()
retained_joints.append(joint)
new_id = len(retained_bodies)
body_data[child_body]["id"] = new_id
retained_bodies.append(child_body)
for shape in body_data[child_body]["shapes"]:
self.shape_body[shape] = new_id
visited[parent_body] = True
if visited[child_body] or child_body not in body_children:
return
for child in body_children[child_body]:
if not visited[child]:
dfs(child_body, child, incoming_xform, last_dynamic_body)
for body in body_children[-1]:
if not visited[body]:
dfs(-1, body, wp.transform(), -1)
# repopulate the model
self.body_name.clear()
self.body_q.clear()
self.body_qd.clear()
self.body_mass.clear()
self.body_inertia.clear()
self.body_com.clear()
self.body_inv_mass.clear()
self.body_inv_inertia.clear()
self.body_shapes.clear()
for i in retained_bodies:
body = body_data[i]
new_id = len(self.body_name)
body_remap[body["original_id"]] = new_id
self.body_name.append(body["name"])
self.body_q.append(list(body["q"]))
self.body_qd.append(list(body["qd"]))
m = body["mass"]
inertia = body["inertia"]
self.body_mass.append(m)
self.body_inertia.append(inertia)
self.body_com.append(body["com"])
if body["inv_mass"] is None:
# recompute inverse mass and inertia
if m > 0.0:
self.body_inv_mass.append(1.0 / m)
self.body_inv_inertia.append(np.linalg.inv(inertia))
else:
self.body_inv_mass.append(0.0)
self.body_inv_inertia.append(np.zeros((3, 3)))
else:
self.body_inv_mass.append(body["inv_mass"])
self.body_inv_inertia.append(body["inv_inertia"])
self.body_shapes[new_id] = body["shapes"]
body_remap[body["original_id"]] = new_id
# sort joints so they appear in the same order as before
retained_joints.sort(key=lambda x: x["original_id"])
self.joint_name.clear()
self.joint_type.clear()
self.joint_parent.clear()
self.joint_child.clear()
self.joint_q.clear()
self.joint_qd.clear()
self.joint_q_start.clear()
self.joint_qd_start.clear()
self.joint_enabled.clear()
self.joint_linear_compliance.clear()
self.joint_angular_compliance.clear()
self.joint_X_p.clear()
self.joint_X_c.clear()
self.joint_axis.clear()
self.joint_axis_mode.clear()
self.joint_target.clear()
self.joint_target_ke.clear()
self.joint_target_kd.clear()
self.joint_limit_lower.clear()
self.joint_limit_upper.clear()
self.joint_limit_ke.clear()
self.joint_limit_kd.clear()
self.joint_axis_dim.clear()
self.joint_axis_start.clear()
self.joint_act.clear()
for joint in retained_joints:
self.joint_name.append(joint["name"])
self.joint_type.append(joint["type"])
self.joint_parent.append(body_remap[joint["parent"]])
self.joint_child.append(body_remap[joint["child"]])
self.joint_q_start.append(len(self.joint_q))
self.joint_qd_start.append(len(self.joint_qd))
self.joint_q.extend(joint["q"])
self.joint_qd.extend(joint["qd"])
self.joint_act.extend(joint["act"])
self.joint_enabled.append(joint["enabled"])
self.joint_linear_compliance.append(joint["linear_compliance"])
self.joint_angular_compliance.append(joint["angular_compliance"])
self.joint_X_p.append(list(joint["parent_xform"]))
self.joint_X_c.append(list(joint["child_xform"]))
self.joint_axis_dim.append(joint["axis_dim"])
self.joint_axis_start.append(len(self.joint_axis))
for axis in joint["axes"]:
self.joint_axis.append(axis["axis"])
self.joint_axis_mode.append(axis["axis_mode"])
self.joint_target.append(axis["target"])
self.joint_target_ke.append(axis["target_ke"])
self.joint_target_kd.append(axis["target_kd"])
self.joint_limit_lower.append(axis["limit_lower"])
self.joint_limit_upper.append(axis["limit_upper"])
self.joint_limit_ke.append(axis["limit_ke"])
self.joint_limit_kd.append(axis["limit_kd"])
# muscles
def add_muscle(
self, bodies: List[int], positions: List[Vec3], f0: float, lm: float, lt: float, lmax: float, pen: float
) -> float:
"""Adds a muscle-tendon activation unit
Args:
bodies: A list of body indices for each waypoint
positions: A list of positions of each waypoint in the body's local frame
f0: Force scaling
lm: Muscle length
lt: Tendon length
lmax: Maximally efficient muscle length
Returns:
The index of the muscle in the model
"""
n = len(bodies)
self.muscle_start.append(len(self.muscle_bodies))
self.muscle_params.append((f0, lm, lt, lmax, pen))
self.muscle_activation.append(0.0)
for i in range(n):
self.muscle_bodies.append(bodies[i])
self.muscle_points.append(positions[i])
# return the index of the muscle
return len(self.muscle_start) - 1
# shapes
def add_shape_plane(
self,
plane: Vec4 = (0.0, 1.0, 0.0, 0.0),
pos: Vec3 = None,
rot: Quat = None,
width: float = 10.0,
length: float = 10.0,
body: int = -1,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
thickness: float = 0.0,
has_ground_collision: bool = False,
):
"""
Adds a plane collision shape.
If pos and rot are defined, the plane is assumed to have its normal as (0, 1, 0).
Otherwise, the plane equation is used.
Args:
plane: The plane equation in form a*x + b*y + c*z + d = 0
pos: The position of the plane in world coordinates
rot: The rotation of the plane in world coordinates
width: The extent along x of the plane (infinite if 0)
length: The extent along z of the plane (infinite if 0)
body: The body index to attach the shape to (-1 by default to keep the plane static)
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
thickness: The thickness of the plane (0 by default) for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
if pos is None or rot is None:
# compute position and rotation from plane equation
normal = np.array(plane[:3])
normal /= np.linalg.norm(normal)
pos = plane[3] * normal
if np.allclose(normal, (0.0, 1.0, 0.0)):
# no rotation necessary
rot = (0.0, 0.0, 0.0, 1.0)
else:
c = np.cross(normal, (0.0, 1.0, 0.0))
angle = np.arcsin(np.linalg.norm(c))
axis = c / np.linalg.norm(c)
rot = wp.quat_from_axis_angle(axis, angle)
scale = (width, length, 0.0)
return self._add_shape(
body,
pos,
rot,
GEO_PLANE,
scale,
None,
0.0,
ke,
kd,
kf,
mu,
restitution,
thickness,
has_ground_collision=has_ground_collision,
)
def add_shape_sphere(
self,
body,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
has_ground_collision: bool = True,
):
"""Adds a sphere collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the sphere
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: Whether the sphere is solid or hollow
thickness: Thickness to use for computing inertia of a hollow sphere, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
return self._add_shape(
body,
pos,
rot,
GEO_SPHERE,
(radius, 0.0, 0.0, 0.0),
None,
density,
ke,
kd,
kf,
mu,
restitution,
thickness + radius,
is_solid,
has_ground_collision=has_ground_collision,
)
def add_shape_box(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
hx: float = 0.5,
hy: float = 0.5,
hz: float = 0.5,
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
has_ground_collision: bool = True,
):
"""Adds a box collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
hx: The half-extent along the x-axis
hy: The half-extent along the y-axis
hz: The half-extent along the z-axis
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: Whether the box is solid or hollow
thickness: Thickness to use for computing inertia of a hollow box, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
return self._add_shape(
body,
pos,
rot,
GEO_BOX,
(hx, hy, hz, 0.0),
None,
density,
ke,
kd,
kf,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
)
def add_shape_capsule(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
half_height: float = 0.5,
up_axis: int = 1,
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
has_ground_collision: bool = True,
):
"""Adds a capsule collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the capsule
half_height: The half length of the center cylinder along the up axis
up_axis: The axis along which the capsule is aligned (0=x, 1=y, 2=z)
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: Whether the capsule is solid or hollow
thickness: Thickness to use for computing inertia of a hollow capsule, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
q = rot
sqh = math.sqrt(0.5)
if up_axis == 0:
q = wp.mul(rot, wp.quat(0.0, 0.0, -sqh, sqh))
elif up_axis == 2:
q = wp.mul(rot, wp.quat(sqh, 0.0, 0.0, sqh))
return self._add_shape(
body,
pos,
q,
GEO_CAPSULE,
(radius, half_height, 0.0, 0.0),
None,
density,
ke,
kd,
kf,
mu,
restitution,
thickness + radius,
is_solid,
has_ground_collision=has_ground_collision,
)
def add_shape_cylinder(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
half_height: float = 0.5,
up_axis: int = 1,
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
has_ground_collision: bool = True,
):
"""Adds a cylinder collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the cylinder
half_height: The half length of the cylinder along the up axis
up_axis: The axis along which the cylinder is aligned (0=x, 1=y, 2=z)
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: Whether the cylinder is solid or hollow
thickness: Thickness to use for computing inertia of a hollow cylinder, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
q = rot
sqh = math.sqrt(0.5)
if up_axis == 0:
q = wp.mul(rot, wp.quat(0.0, 0.0, -sqh, sqh))
elif up_axis == 2:
q = wp.mul(rot, wp.quat(sqh, 0.0, 0.0, sqh))
return self._add_shape(
body,
pos,
q,
GEO_CYLINDER,
(radius, half_height, 0.0, 0.0),
None,
density,
ke,
kd,
kf,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
)
def add_shape_cone(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
half_height: float = 0.5,
up_axis: int = 1,
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
has_ground_collision: bool = True,
):
"""Adds a cone collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the cone
half_height: The half length of the cone along the up axis
up_axis: The axis along which the cone is aligned (0=x, 1=y, 2=z)
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: Whether the cone is solid or hollow
thickness: Thickness to use for computing inertia of a hollow cone, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
q = rot
sqh = math.sqrt(0.5)
if up_axis == 0:
q = wp.mul(rot, wp.quat(0.0, 0.0, -sqh, sqh))
elif up_axis == 2:
q = wp.mul(rot, wp.quat(sqh, 0.0, 0.0, sqh))
return self._add_shape(
body,
pos,
q,
GEO_CONE,
(radius, half_height, 0.0, 0.0),
None,
density,
ke,
kd,
kf,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
)
def add_shape_mesh(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
mesh: Mesh = None,
scale: Vec3 = (1.0, 1.0, 1.0),
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
has_ground_collision: bool = True,
):
"""Adds a triangle mesh collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
mesh: The mesh object
scale: Scale to use for the collider
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: If True, the mesh is solid, otherwise it is a hollow surface with the given wall thickness
thickness: Thickness to use for computing inertia of a hollow mesh, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
return self._add_shape(
body,
pos,
rot,
GEO_MESH,
(scale[0], scale[1], scale[2], 0.0),
mesh,
density,
ke,
kd,
kf,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
)
def add_shape_sdf(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
sdf: SDF = None,
scale: Vec3 = (1.0, 1.0, 1.0),
density: float = default_shape_density,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
is_solid: bool = True,
thickness: float = default_geo_thickness,
):
"""Adds SDF collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
sdf: The sdf object
scale: Scale to use for the collider
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
restitution: The coefficient of restitution
is_solid: If True, the mesh is solid, otherwise it is a hollow surface with the given wall thickness
thickness: Thickness to use for computing inertia of a hollow mesh, and for collision handling
has_ground_collision: If True, the mesh will collide with the ground plane if `Model.ground` is True
"""
return self._add_shape(
body,
pos,
rot,
GEO_SDF,
(scale[0], scale[1], scale[2], 0.0),
sdf,
density,
ke,
kd,
kf,
mu,
restitution,
thickness,
is_solid,
)
def _shape_radius(self, type, scale, src):
"""
Calculates the radius of a sphere that encloses the shape, used for broadphase collision detection.
"""
if type == GEO_SPHERE:
return scale[0]
elif type == GEO_BOX:
return np.linalg.norm(scale)
elif type == GEO_CAPSULE or type == GEO_CYLINDER or type == GEO_CONE:
return scale[0] + scale[1]
elif type == GEO_MESH:
vmax = np.max(np.abs(src.vertices), axis=0) * np.max(scale)
return np.linalg.norm(vmax)
elif type == GEO_PLANE:
if scale[0] > 0.0 and scale[1] > 0.0:
# finite plane
return np.linalg.norm(scale)
else:
return 1.0e6
else:
return 10.0
def _add_shape(
self,
body,
pos,
rot,
type,
scale,
src,
density,
ke,
kd,
kf,
mu,
restitution,
thickness=default_geo_thickness,
is_solid=True,
collision_group=-1,
collision_filter_parent=True,
has_ground_collision=True,
):
self.shape_body.append(body)
shape = self.shape_count
if body in self.body_shapes:
# no contacts between shapes of the same body
for same_body_shape in self.body_shapes[body]:
self.shape_collision_filter_pairs.add((same_body_shape, shape))
self.body_shapes[body].append(shape)
else:
self.body_shapes[body] = [shape]
self.shape_transform.append(wp.transform(pos, rot))
self.shape_geo_type.append(type)
self.shape_geo_scale.append((scale[0], scale[1], scale[2]))
self.shape_geo_src.append(src)
self.shape_geo_thickness.append(thickness)
self.shape_geo_is_solid.append(is_solid)
self.shape_material_ke.append(ke)
self.shape_material_kd.append(kd)
self.shape_material_kf.append(kf)
self.shape_material_mu.append(mu)
self.shape_material_restitution.append(restitution)
self.shape_collision_group.append(collision_group)
if collision_group not in self.shape_collision_group_map:
self.shape_collision_group_map[collision_group] = []
self.last_collision_group = max(self.last_collision_group, collision_group)
self.shape_collision_group_map[collision_group].append(shape)
self.shape_collision_radius.append(self._shape_radius(type, scale, src))
if collision_filter_parent and body > -1 and body in self.joint_parents:
for parent_body in self.joint_parents[body]:
if parent_body > -1:
for parent_shape in self.body_shapes[parent_body]:
self.shape_collision_filter_pairs.add((parent_shape, shape))
if body == -1:
has_ground_collision = False
self.shape_ground_collision.append(has_ground_collision)
(m, c, I) = compute_shape_mass(type, scale, src, density, is_solid, thickness)
self._update_body_mass(body, m, I, np.array(pos) + c, np.array(rot))
return shape
# particles
def add_particle(
self, pos: Vec3, vel: Vec3, mass: float, radius: float = None, flags: wp.uint32 = PARTICLE_FLAG_ACTIVE
) -> int:
"""Adds a single particle to the model
Args:
pos: The initial position of the particle
vel: The initial velocity of the particle
mass: The mass of the particle
flags: The flags that control the dynamical behavior of the particle, see PARTICLE_FLAG_* constants
radius: The radius of the particle used in collision handling. If None, the radius is set to the default value (default_particle_radius).
Note:
Set the mass equal to zero to create a 'kinematic' particle that does is not subject to dynamics.
Returns:
The index of the particle in the system
"""
self.particle_q.append(pos)
self.particle_qd.append(vel)
self.particle_mass.append(mass)
if radius is None:
radius = self.default_particle_radius
self.particle_radius.append(radius)
self.particle_flags.append(flags)
return len(self.particle_q) - 1
def add_spring(self, i: int, j, ke: float, kd: float, control: float):
"""Adds a spring between two particles in the system
Args:
i: The index of the first particle
j: The index of the second particle
ke: The elastic stiffness of the spring
kd: The damping stiffness of the spring
control: The actuation level of the spring
Note:
The spring is created with a rest-length based on the distance
between the particles in their initial configuration.
"""
self.spring_indices.append(i)
self.spring_indices.append(j)
self.spring_stiffness.append(ke)
self.spring_damping.append(kd)
self.spring_control.append(control)
# compute rest length
p = self.particle_q[i]
q = self.particle_q[j]
delta = np.subtract(p, q)
l = np.sqrt(np.dot(delta, delta))
self.spring_rest_length.append(l)
def add_triangle(
self,
i: int,
j: int,
k: int,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
) -> float:
"""Adds a triangular FEM element between three particles in the system.
Triangles are modeled as viscoelastic elements with elastic stiffness and damping
Parameters specified on the model. See model.tri_ke, model.tri_kd.
Args:
i: The index of the first particle
j: The index of the second particle
k: The index of the third particle
Return:
The area of the triangle
Note:
The triangle is created with a rest-length based on the distance
between the particles in their initial configuration.
Todo:
* Expose elastic parameters on a per-element basis
"""
# compute basis for 2D rest pose
p = np.array(self.particle_q[i])
q = np.array(self.particle_q[j])
r = np.array(self.particle_q[k])
qp = q - p
rp = r - p
# construct basis aligned with the triangle
n = wp.normalize(wp.cross(qp, rp))
e1 = wp.normalize(qp)
e2 = wp.normalize(wp.cross(n, e1))
R = np.array((e1, e2))
M = np.array((qp, rp))
D = R @ M.T
area = np.linalg.det(D) / 2.0
if area <= 0.0:
print("inverted or degenerate triangle element")
return 0.0
else:
inv_D = np.linalg.inv(D)
self.tri_indices.append((i, j, k))
self.tri_poses.append(inv_D.tolist())
self.tri_activations.append(0.0)
self.tri_materials.append((tri_ke, tri_ka, tri_kd, tri_drag, tri_lift))
return area
def add_triangles(
self,
i: List[int],
j: List[int],
k: List[int],
tri_ke: Optional[List[float]] = None,
tri_ka: Optional[List[float]] = None,
tri_kd: Optional[List[float]] = None,
tri_drag: Optional[List[float]] = None,
tri_lift: Optional[List[float]] = None,
) -> List[float]:
"""Adds triangular FEM elements between groups of three particles in the system.
Triangles are modeled as viscoelastic elements with elastic stiffness and damping
Parameters specified on the model. See model.tri_ke, model.tri_kd.
Args:
i: The indices of the first particle
j: The indices of the second particle
k: The indices of the third particle
Return:
The areas of the triangles
Note:
A triangle is created with a rest-length based on the distance
between the particles in their initial configuration.
"""
# compute basis for 2D rest pose
p = np.array(self.particle_q)[i]
q = np.array(self.particle_q)[j]
r = np.array(self.particle_q)[k]
qp = q - p
rp = r - p
def normalized(a):
l = np.linalg.norm(a, axis=-1, keepdims=True)
l[l == 0] = 1.0
return a / l
n = normalized(np.cross(qp, rp))
e1 = normalized(qp)
e2 = normalized(np.cross(n, e1))
R = np.concatenate((e1[..., None], e2[..., None]), axis=-1)
M = np.concatenate((qp[..., None], rp[..., None]), axis=-1)
D = np.matmul(R.transpose(0, 2, 1), M)
areas = np.linalg.det(D) / 2.0
areas[areas < 0.0] = 0.0
valid_inds = (areas > 0.0).nonzero()[0]
if len(valid_inds) < len(areas):
print("inverted or degenerate triangle elements")
D[areas == 0.0] = np.eye(2)[None, ...]
inv_D = np.linalg.inv(D)
inds = np.concatenate((i[valid_inds, None], j[valid_inds, None], k[valid_inds, None]), axis=-1)
self.tri_indices.extend(inds.tolist())
self.tri_poses.extend(inv_D[valid_inds].tolist())
self.tri_activations.extend([0.0] * len(valid_inds))
def init_if_none(arr, defaultValue):
if arr is None:
return [defaultValue] * len(areas)
return arr
tri_ke = init_if_none(tri_ke, self.default_tri_ke)
tri_ka = init_if_none(tri_ka, self.default_tri_ka)
tri_kd = init_if_none(tri_kd, self.default_tri_kd)
tri_drag = init_if_none(tri_drag, self.default_tri_drag)
tri_lift = init_if_none(tri_lift, self.default_tri_lift)
self.tri_materials.extend(
zip(
np.array(tri_ke)[valid_inds],
np.array(tri_ka)[valid_inds],
np.array(tri_kd)[valid_inds],
np.array(tri_drag)[valid_inds],
np.array(tri_lift)[valid_inds],
)
)
return areas.tolist()
def add_tetrahedron(
self, i: int, j: int, k: int, l: int, k_mu: float = 1.0e3, k_lambda: float = 1.0e3, k_damp: float = 0.0
) -> float:
"""Adds a tetrahedral FEM element between four particles in the system.
Tetrahedra are modeled as viscoelastic elements with a NeoHookean energy
density based on [Smith et al. 2018].
Args:
i: The index of the first particle
j: The index of the second particle
k: The index of the third particle
l: The index of the fourth particle
k_mu: The first elastic Lame parameter
k_lambda: The second elastic Lame parameter
k_damp: The element's damping stiffness
Return:
The volume of the tetrahedron
Note:
The tetrahedron is created with a rest-pose based on the particle's initial configruation
"""
# compute basis for 2D rest pose
p = np.array(self.particle_q[i])
q = np.array(self.particle_q[j])
r = np.array(self.particle_q[k])
s = np.array(self.particle_q[l])
qp = q - p
rp = r - p
sp = s - p
Dm = np.array((qp, rp, sp)).T
volume = np.linalg.det(Dm) / 6.0
if volume <= 0.0:
print("inverted tetrahedral element")
else:
inv_Dm = np.linalg.inv(Dm)
self.tet_indices.append((i, j, k, l))
self.tet_poses.append(inv_Dm.tolist())
self.tet_activations.append(0.0)
self.tet_materials.append((k_mu, k_lambda, k_damp))
return volume
def add_edge(
self,
i: int,
j: int,
k: int,
l: int,
rest: float = None,
edge_ke: float = default_edge_ke,
edge_kd: float = default_edge_kd,
):
"""Adds a bending edge element between four particles in the system.
Bending elements are designed to be between two connected triangles. Then
bending energy is based of [Bridson et al. 2002]. Bending stiffness is controlled
by the `model.tri_kb` parameter.
Args:
i: The index of the first particle
j: The index of the second particle
k: The index of the third particle
l: The index of the fourth particle
rest: The rest angle across the edge in radians, if not specified it will be computed
Note:
The edge lies between the particles indexed by 'k' and 'l' parameters with the opposing
vertices indexed by 'i' and 'j'. This defines two connected triangles with counter clockwise
winding: (i, k, l), (j, l, k).
"""
# compute rest angle
if rest is None:
x1 = np.array(self.particle_q[i])
x2 = np.array(self.particle_q[j])
x3 = np.array(self.particle_q[k])
x4 = np.array(self.particle_q[l])
n1 = wp.normalize(np.cross(x3 - x1, x4 - x1))
n2 = wp.normalize(np.cross(x4 - x2, x3 - x2))
e = wp.normalize(x4 - x3)
d = np.clip(np.dot(n2, n1), -1.0, 1.0)
angle = math.acos(d)
sign = np.sign(np.dot(np.cross(n2, n1), e))
rest = angle * sign
self.edge_indices.append((i, j, k, l))
self.edge_rest_angle.append(rest)
self.edge_bending_properties.append((edge_ke, edge_kd))
def add_edges(
self,
i,
j,
k,
l,
rest: Optional[List[float]] = None,
edge_ke: Optional[List[float]] = None,
edge_kd: Optional[List[float]] = None,
):
"""Adds bending edge elements between groups of four particles in the system.
Bending elements are designed to be between two connected triangles. Then
bending energy is based of [Bridson et al. 2002]. Bending stiffness is controlled
by the `model.tri_kb` parameter.
Args:
i: The indices of the first particle
j: The indices of the second particle
k: The indices of the third particle
l: The indices of the fourth particle
rest: The rest angles across the edges in radians, if not specified they will be computed
Note:
The edge lies between the particles indexed by 'k' and 'l' parameters with the opposing
vertices indexed by 'i' and 'j'. This defines two connected triangles with counter clockwise
winding: (i, k, l), (j, l, k).
"""
if rest is None:
# compute rest angle
x1 = np.array(self.particle_q)[i]
x2 = np.array(self.particle_q)[j]
x3 = np.array(self.particle_q)[k]
x4 = np.array(self.particle_q)[l]
def normalized(a):
l = np.linalg.norm(a, axis=-1, keepdims=True)
l[l == 0] = 1.0
return a / l
n1 = normalized(np.cross(x3 - x1, x4 - x1))
n2 = normalized(np.cross(x4 - x2, x3 - x2))
e = normalized(x4 - x3)
def dot(a, b):
return (a * b).sum(axis=-1)
d = np.clip(dot(n2, n1), -1.0, 1.0)
angle = np.arccos(d)
sign = np.sign(dot(np.cross(n2, n1), e))
rest = angle * sign
inds = np.concatenate((i[:, None], j[:, None], k[:, None], l[:, None]), axis=-1)
self.edge_indices.extend(inds.tolist())
self.edge_rest_angle.extend(rest.tolist())
def init_if_none(arr, defaultValue):
if arr is None:
return [defaultValue] * len(i)
return arr
edge_ke = init_if_none(edge_ke, self.default_edge_ke)
edge_kd = init_if_none(edge_kd, self.default_edge_kd)
self.edge_bending_properties.extend(zip(edge_ke, edge_kd))
def add_cloth_grid(
self,
pos: Vec3,
rot: Quat,
vel: Vec3,
dim_x: int,
dim_y: int,
cell_x: float,
cell_y: float,
mass: float,
reverse_winding: bool = False,
fix_left: bool = False,
fix_right: bool = False,
fix_top: bool = False,
fix_bottom: bool = False,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
edge_ke: float = default_edge_ke,
edge_kd: float = default_edge_kd,
add_springs: bool = False,
spring_ke: float = default_spring_ke,
spring_kd: float = default_spring_kd,
):
"""Helper to create a regular planar cloth grid
Creates a rectangular grid of particles with FEM triangles and bending elements
automatically.
Args:
pos: The position of the cloth in world space
rot: The orientation of the cloth in world space
vel: The velocity of the cloth in world space
dim_x_: The number of rectangular cells along the x-axis
dim_y: The number of rectangular cells along the y-axis
cell_x: The width of each cell in the x-direction
cell_y: The width of each cell in the y-direction
mass: The mass of each particle
reverse_winding: Flip the winding of the mesh
fix_left: Make the left-most edge of particles kinematic (fixed in place)
fix_right: Make the right-most edge of particles kinematic
fix_top: Make the top-most edge of particles kinematic
fix_bottom: Make the bottom-most edge of particles kinematic
"""
def grid_index(x, y, dim_x):
return y * dim_x + x
start_vertex = len(self.particle_q)
start_tri = len(self.tri_indices)
for y in range(0, dim_y + 1):
for x in range(0, dim_x + 1):
g = np.array((x * cell_x, y * cell_y, 0.0))
p = np.array(wp.quat_rotate(rot, g)) + pos
m = mass
if x == 0 and fix_left:
m = 0.0
elif x == dim_x and fix_right:
m = 0.0
elif y == 0 and fix_bottom:
m = 0.0
elif y == dim_y and fix_top:
m = 0.0
self.add_particle(p, vel, m)
if x > 0 and y > 0:
if reverse_winding:
tri1 = (
start_vertex + grid_index(x - 1, y - 1, dim_x + 1),
start_vertex + grid_index(x, y - 1, dim_x + 1),
start_vertex + grid_index(x, y, dim_x + 1),
)
tri2 = (
start_vertex + grid_index(x - 1, y - 1, dim_x + 1),
start_vertex + grid_index(x, y, dim_x + 1),
start_vertex + grid_index(x - 1, y, dim_x + 1),
)
self.add_triangle(*tri1, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
self.add_triangle(*tri2, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
else:
tri1 = (
start_vertex + grid_index(x - 1, y - 1, dim_x + 1),
start_vertex + grid_index(x, y - 1, dim_x + 1),
start_vertex + grid_index(x - 1, y, dim_x + 1),
)
tri2 = (
start_vertex + grid_index(x, y - 1, dim_x + 1),
start_vertex + grid_index(x, y, dim_x + 1),
start_vertex + grid_index(x - 1, y, dim_x + 1),
)
self.add_triangle(*tri1, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
self.add_triangle(*tri2, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
end_vertex = len(self.particle_q)
end_tri = len(self.tri_indices)
# bending constraints, could create these explicitly for a grid but this
# is a good test of the adjacency structure
adj = wp.utils.MeshAdjacency(self.tri_indices[start_tri:end_tri], end_tri - start_tri)
spring_indices = set()
for k, e in adj.edges.items():
# skip open edges
if e.f0 == -1 or e.f1 == -1:
continue
self.add_edge(
e.o0, e.o1, e.v0, e.v1, edge_ke=edge_ke, edge_kd=edge_kd
) # opposite 0, opposite 1, vertex 0, vertex 1
spring_indices.add((min(e.o0, e.o1), max(e.o0, e.o1)))
spring_indices.add((min(e.o0, e.v0), max(e.o0, e.v0)))
spring_indices.add((min(e.o0, e.v1), max(e.o0, e.v1)))
spring_indices.add((min(e.o1, e.v0), max(e.o1, e.v0)))
spring_indices.add((min(e.o1, e.v1), max(e.o1, e.v1)))
spring_indices.add((min(e.v0, e.v1), max(e.v0, e.v1)))
if add_springs:
for i, j in spring_indices:
self.add_spring(i, j, spring_ke, spring_kd, control=0.0)
def add_cloth_mesh(
self,
pos: Vec3,
rot: Quat,
scale: float,
vel: Vec3,
vertices: List[Vec3],
indices: List[int],
density: float,
edge_callback=None,
face_callback=None,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
edge_ke: float = default_edge_ke,
edge_kd: float = default_edge_kd,
add_springs: bool = False,
spring_ke: float = default_spring_ke,
spring_kd: float = default_spring_kd,
):
"""Helper to create a cloth model from a regular triangle mesh
Creates one FEM triangle element and one bending element for every face
and edge in the input triangle mesh
Args:
pos: The position of the cloth in world space
rot: The orientation of the cloth in world space
vel: The velocity of the cloth in world space
vertices: A list of vertex positions
indices: A list of triangle indices, 3 entries per-face
density: The density per-area of the mesh
edge_callback: A user callback when an edge is created
face_callback: A user callback when a face is created
Note:
The mesh should be two manifold.
"""
num_tris = int(len(indices) / 3)
start_vertex = len(self.particle_q)
start_tri = len(self.tri_indices)
# particles
for v in vertices:
p = np.array(wp.quat_rotate(rot, v * scale)) + pos
self.add_particle(p, vel, 0.0)
# triangles
inds = start_vertex + np.array(indices)
inds = inds.reshape(-1, 3)
areas = self.add_triangles(
inds[:, 0],
inds[:, 1],
inds[:, 2],
[tri_ke] * num_tris,
[tri_ka] * num_tris,
[tri_kd] * num_tris,
[tri_drag] * num_tris,
[tri_lift] * num_tris,
)
for t in range(num_tris):
area = areas[t]
self.particle_mass[inds[t, 0]] += density * area / 3.0
self.particle_mass[inds[t, 1]] += density * area / 3.0
self.particle_mass[inds[t, 2]] += density * area / 3.0
end_tri = len(self.tri_indices)
adj = wp.utils.MeshAdjacency(self.tri_indices[start_tri:end_tri], end_tri - start_tri)
edgeinds = np.fromiter(
(x for e in adj.edges.values() if e.f0 != -1 and e.f1 != -1 for x in (e.o0, e.o1, e.v0, e.v1)),
int,
).reshape(-1, 4)
self.add_edges(
edgeinds[:, 0],
edgeinds[:, 1],
edgeinds[:, 2],
edgeinds[:, 0],
edge_ke=[edge_ke] * len(edgeinds),
edge_kd=[edge_kd] * len(edgeinds),
)
if add_springs:
spring_indices = set()
for i, j, k, l in edgeinds:
spring_indices.add((min(i, j), max(i, j)))
spring_indices.add((min(i, k), max(i, k)))
spring_indices.add((min(i, l), max(i, l)))
spring_indices.add((min(j, k), max(j, k)))
spring_indices.add((min(j, l), max(j, l)))
spring_indices.add((min(k, l), max(k, l)))
for i, j in spring_indices:
self.add_spring(i, j, spring_ke, spring_kd, control=0.0)
def add_particle_grid(
self,
pos: Vec3,
rot: Quat,
vel: Vec3,
dim_x: int,
dim_y: int,
dim_z: int,
cell_x: float,
cell_y: float,
cell_z: float,
mass: float,
jitter: float,
radius_mean: float = default_particle_radius,
radius_std: float = 0.0,
):
for z in range(dim_z):
for y in range(dim_y):
for x in range(dim_x):
v = np.array((x * cell_x, y * cell_y, z * cell_z))
m = mass
p = np.array(wp.quat_rotate(rot, v)) + pos + np.random.rand(3) * jitter
if radius_std > 0.0:
r = radius_mean + np.random.randn() * radius_std
else:
r = radius_mean
self.add_particle(p, vel, m, r)
def add_soft_grid(
self,
pos: Vec3,
rot: Quat,
vel: Vec3,
dim_x: int,
dim_y: int,
dim_z: int,
cell_x: float,
cell_y: float,
cell_z: float,
density: float,
k_mu: float,
k_lambda: float,
k_damp: float,
fix_left: bool = False,
fix_right: bool = False,
fix_top: bool = False,
fix_bottom: bool = False,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
):
"""Helper to create a rectangular tetrahedral FEM grid
Creates a regular grid of FEM tetrahedra and surface triangles. Useful for example
to create beams and sheets. Each hexahedral cell is decomposed into 5
tetrahedral elements.
Args:
pos: The position of the solid in world space
rot: The orientation of the solid in world space
vel: The velocity of the solid in world space
dim_x_: The number of rectangular cells along the x-axis
dim_y: The number of rectangular cells along the y-axis
dim_z: The number of rectangular cells along the z-axis
cell_x: The width of each cell in the x-direction
cell_y: The width of each cell in the y-direction
cell_z: The width of each cell in the z-direction
density: The density of each particle
k_mu: The first elastic Lame parameter
k_lambda: The second elastic Lame parameter
k_damp: The damping stiffness
fix_left: Make the left-most edge of particles kinematic (fixed in place)
fix_right: Make the right-most edge of particles kinematic
fix_top: Make the top-most edge of particles kinematic
fix_bottom: Make the bottom-most edge of particles kinematic
"""
start_vertex = len(self.particle_q)
mass = cell_x * cell_y * cell_z * density
for z in range(dim_z + 1):
for y in range(dim_y + 1):
for x in range(dim_x + 1):
v = np.array((x * cell_x, y * cell_y, z * cell_z))
m = mass
if fix_left and x == 0:
m = 0.0
if fix_right and x == dim_x:
m = 0.0
if fix_top and y == dim_y:
m = 0.0
if fix_bottom and y == 0:
m = 0.0
p = np.array(wp.quat_rotate(rot, v)) + pos
self.add_particle(p, vel, m)
# dict of open faces
faces = {}
def add_face(i: int, j: int, k: int):
key = tuple(sorted((i, j, k)))
if key not in faces:
faces[key] = (i, j, k)
else:
del faces[key]
def add_tet(i: int, j: int, k: int, l: int):
self.add_tetrahedron(i, j, k, l, k_mu, k_lambda, k_damp)
add_face(i, k, j)
add_face(j, k, l)
add_face(i, j, l)
add_face(i, l, k)
def grid_index(x, y, z):
return (dim_x + 1) * (dim_y + 1) * z + (dim_x + 1) * y + x
for z in range(dim_z):
for y in range(dim_y):
for x in range(dim_x):
v0 = grid_index(x, y, z) + start_vertex
v1 = grid_index(x + 1, y, z) + start_vertex
v2 = grid_index(x + 1, y, z + 1) + start_vertex
v3 = grid_index(x, y, z + 1) + start_vertex
v4 = grid_index(x, y + 1, z) + start_vertex
v5 = grid_index(x + 1, y + 1, z) + start_vertex
v6 = grid_index(x + 1, y + 1, z + 1) + start_vertex
v7 = grid_index(x, y + 1, z + 1) + start_vertex
if (x & 1) ^ (y & 1) ^ (z & 1):
add_tet(v0, v1, v4, v3)
add_tet(v2, v3, v6, v1)
add_tet(v5, v4, v1, v6)
add_tet(v7, v6, v3, v4)
add_tet(v4, v1, v6, v3)
else:
add_tet(v1, v2, v5, v0)
add_tet(v3, v0, v7, v2)
add_tet(v4, v7, v0, v5)
add_tet(v6, v5, v2, v7)
add_tet(v5, v2, v7, v0)
# add triangles
for k, v in faces.items():
self.add_triangle(v[0], v[1], v[2], tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
def add_soft_mesh(
self,
pos: Vec3,
rot: Quat,
scale: float,
vel: Vec3,
vertices: List[Vec3],
indices: List[int],
density: float,
k_mu: float,
k_lambda: float,
k_damp: float,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
):
"""Helper to create a tetrahedral model from an input tetrahedral mesh
Args:
pos: The position of the solid in world space
rot: The orientation of the solid in world space
vel: The velocity of the solid in world space
vertices: A list of vertex positions
indices: A list of tetrahedron indices, 4 entries per-element
density: The density per-area of the mesh
k_mu: The first elastic Lame parameter
k_lambda: The second elastic Lame parameter
k_damp: The damping stiffness
"""
num_tets = int(len(indices) / 4)
start_vertex = len(self.particle_q)
start_tri = len(self.tri_indices)
# dict of open faces
faces = {}
def add_face(i, j, k):
key = tuple(sorted((i, j, k)))
if key not in faces:
faces[key] = (i, j, k)
else:
del faces[key]
# add particles
for v in vertices:
p = wp.quat_rotate(rot, v * scale) + np.array(pos)
self.add_particle(p, vel, 0.0)
# add tetrahedra
for t in range(num_tets):
v0 = start_vertex + indices[t * 4 + 0]
v1 = start_vertex + indices[t * 4 + 1]
v2 = start_vertex + indices[t * 4 + 2]
v3 = start_vertex + indices[t * 4 + 3]
volume = self.add_tetrahedron(v0, v1, v2, v3, k_mu, k_lambda, k_damp)
# distribute volume fraction to particles
if volume > 0.0:
self.particle_mass[v0] += density * volume / 4.0
self.particle_mass[v1] += density * volume / 4.0
self.particle_mass[v2] += density * volume / 4.0
self.particle_mass[v3] += density * volume / 4.0
# build open faces
add_face(v0, v2, v1)
add_face(v1, v2, v3)
add_face(v0, v1, v3)
add_face(v0, v3, v2)
# add triangles
for k, v in faces.items():
try:
self.add_triangle(v[0], v[1], v[2], tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
except np.linalg.LinAlgError:
continue
# incrementally updates rigid body mass with additional mass and inertia expressed at a local to the body
def _update_body_mass(self, i, m, I, p, q):
if i == -1:
return
# find new COM
new_mass = self.body_mass[i] + m
if new_mass == 0.0: # no mass
return
new_com = (self.body_com[i] * self.body_mass[i] + p * m) / new_mass
# shift inertia to new COM
com_offset = new_com - self.body_com[i]
shape_offset = new_com - p
new_inertia = transform_inertia(
self.body_mass[i], self.body_inertia[i], com_offset, wp.quat_identity()
) + transform_inertia(m, I, shape_offset, q)
self.body_mass[i] = new_mass
self.body_inertia[i] = new_inertia
self.body_com[i] = new_com
if new_mass > 0.0:
self.body_inv_mass[i] = 1.0 / new_mass
else:
self.body_inv_mass[i] = 0.0
if new_inertia.any():
self.body_inv_inertia[i] = np.linalg.inv(new_inertia)
else:
self.body_inv_inertia[i] = new_inertia
def set_ground_plane(
self,
normal=None,
offset=0.0,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
):
"""
Creates a ground plane for the world. If the normal is not specified,
the up_vector of the ModelBuilder is used.
"""
if normal is None:
normal = self.up_vector
self._ground_params = dict(
plane=(*normal, offset), width=0.0, length=0.0, ke=ke, kd=kd, kf=kf, mu=mu, restitution=restitution
)
def _create_ground_plane(self):
ground_id = self.add_shape_plane(**self._ground_params)
self._ground_created = True
# disable ground collisions as they will be treated separately
for i in range(self.shape_count - 1):
self.shape_collision_filter_pairs.add((i, ground_id))
def finalize(self, device=None, requires_grad=False) -> Model:
"""Convert this builder object to a concrete model for simulation.
After building simulation elements this method should be called to transfer
all data to device memory ready for simulation.
Args:
device: The simulation device to use, e.g.: 'cpu', 'cuda'
requires_grad: Whether to enable gradient computation for the model
Returns:
A model object.
"""
# ensure the env count is set correctly
self.num_envs = max(1, self.num_envs)
# add ground plane if not already created
if not self._ground_created:
self._create_ground_plane()
# construct particle inv masses
particle_inv_mass = []
for m in self.particle_mass:
if m > 0.0:
particle_inv_mass.append(1.0 / m)
else:
particle_inv_mass.append(0.0)
with wp.ScopedDevice(device):
# -------------------------------------
# construct Model (non-time varying) data
m = Model(device)
m.requires_grad = requires_grad
m.num_envs = self.num_envs
# ---------------------
# particles
# state (initial)
m.particle_q = wp.array(self.particle_q, dtype=wp.vec3, requires_grad=requires_grad)
m.particle_qd = wp.array(self.particle_qd, dtype=wp.vec3, requires_grad=requires_grad)
m.particle_mass = wp.array(self.particle_mass, dtype=wp.float32, requires_grad=requires_grad)
m.particle_inv_mass = wp.array(particle_inv_mass, dtype=wp.float32, requires_grad=requires_grad)
m._particle_radius = wp.array(self.particle_radius, dtype=wp.float32, requires_grad=requires_grad)
m.particle_flags = wp.array([flag_to_int(f) for f in self.particle_flags], dtype=wp.uint32)
m.particle_max_radius = np.max(self.particle_radius) if len(self.particle_radius) > 0 else 0.0
m.particle_max_velocity = self.particle_max_velocity
# hash-grid for particle interactions
m.particle_grid = wp.HashGrid(128, 128, 128)
# ---------------------
# collision geometry
m.shape_transform = wp.array(self.shape_transform, dtype=wp.transform, requires_grad=requires_grad)
m.shape_body = wp.array(self.shape_body, dtype=wp.int32)
m.body_shapes = self.body_shapes
# build list of ids for geometry sources (meshes, sdfs)
geo_sources = []
finalized_meshes = {} # do not duplicate meshes
for geo in self.shape_geo_src:
geo_hash = hash(geo) # avoid repeated hash computations
if geo:
if geo_hash not in finalized_meshes:
finalized_meshes[geo_hash] = geo.finalize(device=device)
geo_sources.append(finalized_meshes[geo_hash])
else:
# add null pointer
geo_sources.append(0)
m.shape_geo.type = wp.array(self.shape_geo_type, dtype=wp.int32)
m.shape_geo.source = wp.array(geo_sources, dtype=wp.uint64)
m.shape_geo.scale = wp.array(self.shape_geo_scale, dtype=wp.vec3, requires_grad=requires_grad)
m.shape_geo.is_solid = wp.array(self.shape_geo_is_solid, dtype=wp.uint8)
m.shape_geo.thickness = wp.array(self.shape_geo_thickness, dtype=wp.float32, requires_grad=requires_grad)
m.shape_geo_src = self.shape_geo_src # used for rendering
m.shape_materials.ke = wp.array(self.shape_material_ke, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.kd = wp.array(self.shape_material_kd, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.kf = wp.array(self.shape_material_kf, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.mu = wp.array(self.shape_material_mu, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.restitution = wp.array(
self.shape_material_restitution, dtype=wp.float32, requires_grad=requires_grad
)
m.shape_collision_filter_pairs = self.shape_collision_filter_pairs
m.shape_collision_group = self.shape_collision_group
m.shape_collision_group_map = self.shape_collision_group_map
m.shape_collision_radius = wp.array(
self.shape_collision_radius, dtype=wp.float32, requires_grad=requires_grad
)
m.shape_ground_collision = self.shape_ground_collision
# ---------------------
# springs
m.spring_indices = wp.array(self.spring_indices, dtype=wp.int32)
m.spring_rest_length = wp.array(self.spring_rest_length, dtype=wp.float32, requires_grad=requires_grad)
m.spring_stiffness = wp.array(self.spring_stiffness, dtype=wp.float32, requires_grad=requires_grad)
m.spring_damping = wp.array(self.spring_damping, dtype=wp.float32, requires_grad=requires_grad)
m.spring_control = wp.array(self.spring_control, dtype=wp.float32, requires_grad=requires_grad)
m.spring_constraint_lambdas = wp.array(
shape=len(self.spring_rest_length), dtype=wp.float32, requires_grad=requires_grad
)
# ---------------------
# triangles
m.tri_indices = wp.array(self.tri_indices, dtype=wp.int32)
m.tri_poses = wp.array(self.tri_poses, dtype=wp.mat22, requires_grad=requires_grad)
m.tri_activations = wp.array(self.tri_activations, dtype=wp.float32, requires_grad=requires_grad)
m.tri_materials = wp.array(self.tri_materials, dtype=wp.float32, requires_grad=requires_grad)
# ---------------------
# edges
m.edge_indices = wp.array(self.edge_indices, dtype=wp.int32)
m.edge_rest_angle = wp.array(self.edge_rest_angle, dtype=wp.float32, requires_grad=requires_grad)
m.edge_bending_properties = wp.array(
self.edge_bending_properties, dtype=wp.float32, requires_grad=requires_grad
)
m.edge_constraint_lambdas = wp.array(
shape=len(self.edge_rest_angle), dtype=wp.float32, requires_grad=requires_grad
)
# ---------------------
# tetrahedra
m.tet_indices = wp.array(self.tet_indices, dtype=wp.int32)
m.tet_poses = wp.array(self.tet_poses, dtype=wp.mat33, requires_grad=requires_grad)
m.tet_activations = wp.array(self.tet_activations, dtype=wp.float32, requires_grad=requires_grad)
m.tet_materials = wp.array(self.tet_materials, dtype=wp.float32, requires_grad=requires_grad)
# -----------------------
# muscles
# close the muscle waypoint indices
muscle_start = copy.copy(self.muscle_start)
muscle_start.append(len(self.muscle_bodies))
m.muscle_start = wp.array(muscle_start, dtype=wp.int32)
m.muscle_params = wp.array(self.muscle_params, dtype=wp.float32, requires_grad=requires_grad)
m.muscle_bodies = wp.array(self.muscle_bodies, dtype=wp.int32)
m.muscle_points = wp.array(self.muscle_points, dtype=wp.vec3, requires_grad=requires_grad)
m.muscle_activation = wp.array(self.muscle_activation, dtype=wp.float32, requires_grad=requires_grad)
# --------------------------------------
# rigid bodies
m.body_q = wp.array(self.body_q, dtype=wp.transform, requires_grad=requires_grad)
m.body_qd = wp.array(self.body_qd, dtype=wp.spatial_vector, requires_grad=requires_grad)
m.body_inertia = wp.array(self.body_inertia, dtype=wp.mat33, requires_grad=requires_grad)
m.body_inv_inertia = wp.array(self.body_inv_inertia, dtype=wp.mat33, requires_grad=requires_grad)
m.body_mass = wp.array(self.body_mass, dtype=wp.float32, requires_grad=requires_grad)
m.body_inv_mass = wp.array(self.body_inv_mass, dtype=wp.float32, requires_grad=requires_grad)
m.body_com = wp.array(self.body_com, dtype=wp.vec3, requires_grad=requires_grad)
m.body_name = self.body_name
# joints
m.joint_count = self.joint_count
m.joint_axis_count = self.joint_axis_count
m.joint_type = wp.array(self.joint_type, dtype=wp.int32)
m.joint_parent = wp.array(self.joint_parent, dtype=wp.int32)
m.joint_child = wp.array(self.joint_child, dtype=wp.int32)
m.joint_X_p = wp.array(self.joint_X_p, dtype=wp.transform, requires_grad=requires_grad)
m.joint_X_c = wp.array(self.joint_X_c, dtype=wp.transform, requires_grad=requires_grad)
m.joint_axis_start = wp.array(self.joint_axis_start, dtype=wp.int32)
m.joint_axis_dim = wp.array(np.array(self.joint_axis_dim), dtype=wp.int32, ndim=2)
m.joint_axis = wp.array(self.joint_axis, dtype=wp.vec3, requires_grad=requires_grad)
m.joint_q = wp.array(self.joint_q, dtype=wp.float32, requires_grad=requires_grad)
m.joint_qd = wp.array(self.joint_qd, dtype=wp.float32, requires_grad=requires_grad)
m.joint_name = self.joint_name
# dynamics properties
# TODO unused joint_armature
m.joint_armature = wp.array(self.joint_armature, dtype=wp.float32, requires_grad=requires_grad)
m.joint_target = wp.array(self.joint_target, dtype=wp.float32, requires_grad=requires_grad)
m.joint_target_ke = wp.array(self.joint_target_ke, dtype=wp.float32, requires_grad=requires_grad)
m.joint_target_kd = wp.array(self.joint_target_kd, dtype=wp.float32, requires_grad=requires_grad)
m.joint_axis_mode = wp.array(self.joint_axis_mode, dtype=wp.uint8)
m.joint_act = wp.array(self.joint_act, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_lower = wp.array(self.joint_limit_lower, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_upper = wp.array(self.joint_limit_upper, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_ke = wp.array(self.joint_limit_ke, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_kd = wp.array(self.joint_limit_kd, dtype=wp.float32, requires_grad=requires_grad)
m.joint_linear_compliance = wp.array(
self.joint_linear_compliance, dtype=wp.float32, requires_grad=requires_grad
)
m.joint_angular_compliance = wp.array(
self.joint_angular_compliance, dtype=wp.float32, requires_grad=requires_grad
)
m.joint_enabled = wp.array(self.joint_enabled, dtype=wp.int32)
# 'close' the start index arrays with a sentinel value
joint_q_start = copy.copy(self.joint_q_start)
joint_q_start.append(self.joint_coord_count)
joint_qd_start = copy.copy(self.joint_qd_start)
joint_qd_start.append(self.joint_dof_count)
articulation_start = copy.copy(self.articulation_start)
articulation_start.append(self.joint_count)
m.joint_q_start = wp.array(joint_q_start, dtype=wp.int32)
m.joint_qd_start = wp.array(joint_qd_start, dtype=wp.int32)
m.articulation_start = wp.array(articulation_start, dtype=wp.int32)
# counts
m.particle_count = len(self.particle_q)
m.body_count = len(self.body_q)
m.shape_count = len(self.shape_geo_type)
m.tri_count = len(self.tri_poses)
m.tet_count = len(self.tet_poses)
m.edge_count = len(self.edge_rest_angle)
m.spring_count = len(self.spring_rest_length)
m.muscle_count = len(self.muscle_start)
m.articulation_count = len(self.articulation_start)
# contacts
if m.particle_count:
m.allocate_soft_contacts(self.soft_contact_max, requires_grad=requires_grad)
m.find_shape_contact_pairs()
if self.num_rigid_contacts_per_env is None:
contact_count = m.count_contact_points()
else:
contact_count = self.num_rigid_contacts_per_env * self.num_envs
if wp.config.verbose:
print(f"Allocating {contact_count} rigid contacts.")
m.allocate_rigid_contacts(contact_count, requires_grad=requires_grad)
m.rigid_contact_margin = self.rigid_contact_margin
m.rigid_contact_torsional_friction = self.rigid_contact_torsional_friction
m.rigid_contact_rolling_friction = self.rigid_contact_rolling_friction
m.joint_dof_count = self.joint_dof_count
m.joint_coord_count = self.joint_coord_count
# store refs to geometry
m.geo_meshes = self.geo_meshes
m.geo_sdfs = self.geo_sdfs
# enable ground plane
m.ground_plane = wp.array(self._ground_params["plane"], dtype=wp.float32, requires_grad=requires_grad)
m.gravity = np.array(self.up_vector) * self.gravity
m.enable_tri_collisions = False
return m
| warp-main | warp/sim/model.py |
import warp as wp
PI = wp.constant(3.14159265359)
PI_2 = wp.constant(1.57079632679)
@wp.func
def velocity_at_point(qd: wp.spatial_vector, r: wp.vec3):
"""
Returns the velocity of a point relative to the frame with the given spatial velocity.
"""
return wp.cross(wp.spatial_top(qd), r) + wp.spatial_bottom(qd)
@wp.func
def quat_twist(axis: wp.vec3, q: wp.quat):
"""
Returns the twist around an axis.
"""
# project imaginary part onto axis
a = wp.vec3(q[0], q[1], q[2])
proj = wp.dot(a, axis)
a = proj * axis
# if proj < 0.0:
# # ensure twist points in same direction as axis
# a = -a
return wp.normalize(wp.quat(a[0], a[1], a[2], q[3]))
@wp.func
def quat_twist_angle(axis: wp.vec3, q: wp.quat):
"""
Returns the angle of the twist around an axis.
"""
return 2.0 * wp.acos(quat_twist(axis, q)[3])
@wp.func
def quat_decompose(q: wp.quat):
"""
Decompose a quaternion into a sequence of 3 rotations around x,y',z' respectively, i.e.: q = q_z''q_y'q_x.
"""
R = wp.mat33(
wp.quat_rotate(q, wp.vec3(1.0, 0.0, 0.0)),
wp.quat_rotate(q, wp.vec3(0.0, 1.0, 0.0)),
wp.quat_rotate(q, wp.vec3(0.0, 0.0, 1.0)),
)
# https://www.sedris.org/wg8home/Documents/WG80485.pdf
phi = wp.atan2(R[1, 2], R[2, 2])
sinp = -R[0, 2]
if wp.abs(sinp) >= 1.0:
theta = 1.57079632679 * wp.sign(sinp)
else:
theta = wp.asin(-R[0, 2])
psi = wp.atan2(R[0, 1], R[0, 0])
return -wp.vec3(phi, theta, psi)
@wp.func
def quat_to_rpy(q: wp.quat):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
t0 = 2.0 * (w * x + y * z)
t1 = 1.0 - 2.0 * (x * x + y * y)
roll_x = wp.atan2(t0, t1)
t2 = 2.0 * (w * y - z * x)
t2 = wp.clamp(t2, -1.0, 1.0)
pitch_y = wp.asin(t2)
t3 = 2.0 * (w * z + x * y)
t4 = 1.0 - 2.0 * (y * y + z * z)
yaw_z = wp.atan2(t3, t4)
return wp.vec3(roll_x, pitch_y, yaw_z)
@wp.func
def quat_to_euler(q: wp.quat, i: int, j: int, k: int) -> wp.vec3:
"""
Convert a quaternion into euler angles
i, j, k are the indices in [1,2,3] of the axes to use
(i != j, j != k)
"""
# https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0276302
not_proper = True
if i == k:
not_proper = False
k = 6 - i - j # because i + j + k = 1 + 2 + 3 = 6
e = float((i - j) * (j - k) * (k - i)) / 2.0 # Levi-Civita symbol
a = q[0]
b = q[i]
c = q[j]
d = q[k] * e
if not_proper:
a -= q[j]
b += q[k] * e
c += q[0]
d -= q[i]
t2 = wp.acos(2.0 * (a * a + b * b) / (a * a + b * b + c * c + d * d) - 1.0)
tp = wp.atan2(b, a)
tm = wp.atan2(d, c)
t1 = 0.0
t3 = 0.0
if wp.abs(t2) < 1e-6:
t3 = 2.0 * tp - t1
elif wp.abs(t2 - PI_2) < 1e-6:
t3 = 2.0 * tm + t1
else:
t1 = tp - tm
t3 = tp + tm
if not_proper:
t2 -= PI_2
t3 *= e
return wp.vec3(t1, t2, t3)
@wp.func
def transform_twist(t: wp.transform, x: wp.spatial_vector):
# Frank & Park definition 3.20, pg 100
q = wp.transform_get_rotation(t)
p = wp.transform_get_translation(t)
w = wp.spatial_top(x)
v = wp.spatial_bottom(x)
w = wp.quat_rotate(q, w)
v = wp.quat_rotate(q, v) + wp.cross(p, w)
return wp.spatial_vector(w, v)
@wp.func
def transform_wrench(t: wp.transform, x: wp.spatial_vector):
q = wp.transform_get_rotation(t)
p = wp.transform_get_translation(t)
w = wp.spatial_top(x)
v = wp.spatial_bottom(x)
v = wp.quat_rotate(q, v)
w = wp.quat_rotate(q, w) + wp.cross(p, v)
return wp.spatial_vector(w, v)
@wp.func
def transform_inertia(t: wp.transform, I: wp.spatial_matrix):
"""
Computes adj_t^-T*I*adj_t^-1 (tensor change of coordinates).
(Frank & Park, section 8.2.3, pg 290)
"""
t_inv = wp.transform_inverse(t)
q = wp.transform_get_rotation(t_inv)
p = wp.transform_get_translation(t_inv)
r1 = wp.quat_rotate(q, wp.vec3(1.0, 0.0, 0.0))
r2 = wp.quat_rotate(q, wp.vec3(0.0, 1.0, 0.0))
r3 = wp.quat_rotate(q, wp.vec3(0.0, 0.0, 1.0))
R = wp.mat33(r1, r2, r3)
S = wp.mul(wp.skew(p), R)
T = wp.spatial_adjoint(R, S)
return wp.mul(wp.mul(wp.transpose(T), I), T)
@wp.func
def vec_min(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.min(a[0], b[0]), wp.min(a[1], b[1]), wp.min(a[2], b[2]))
@wp.func
def vec_max(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.max(a[0], b[0]), wp.max(a[1], b[1]), wp.max(a[2], b[2]))
@wp.func
def vec_abs(a: wp.vec3):
return wp.vec3(wp.abs(a[0]), wp.abs(a[1]), wp.abs(a[2]))
| warp-main | warp/sim/utils.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 warp.context import synchronize
import warp as wp
import numpy as np
@wp.kernel
def gd_step(arr_x: wp.array(dtype=float), arr_dfdx: wp.array(dtype=float), alpha: float):
tid = wp.tid()
x = arr_x[tid]
dfdx = arr_dfdx[tid]
x = x - dfdx * alpha
arr_x[tid] = x
@wp.kernel
def nesterov1(beta: float, x: wp.array(dtype=float), x_prev: wp.array(dtype=float), y: wp.array(dtype=float)):
tid = wp.tid()
y[tid] = x[tid] + beta * (x[tid] - x_prev[tid])
@wp.kernel
def nesterov2(
alpha: float,
beta: wp.array(dtype=float),
eta: wp.array(dtype=float),
x: wp.array(dtype=float),
x_prev: wp.array(dtype=float),
y: wp.array(dtype=float),
dfdx: wp.array(dtype=float),
):
# if (eta > 0.0):
# # adaptive restart
# x_prev = x
# b = 0
# else:
# # nesterov update
# x_prev = x
# x = y - alpha*dfdx
tid = wp.tid()
x_prev[tid] = x[tid]
x[tid] = y[tid] - alpha * dfdx[tid]
def inner(a, b, out):
from warp.utils import array_inner
array_inner(a, b, out)
class Optimizer:
def __init__(self, n, mode, device):
self.n = n
self.mode = mode
self.device = device
# allocate space for residual buffers
self.dfdx = wp.zeros(n, dtype=float, device=device)
if mode == "nesterov":
self.x_prev = wp.zeros(n, dtype=float, device=device)
self.y = wp.zeros(n, dtype=float, device=device)
self.eta = wp.zeros(1, dtype=float, device=device)
self.eta_prev = wp.zeros(1, dtype=float, device=device)
self.beta = wp.zeros(1, dtype=int, device=device)
def solve(self, x, grad_func, max_iters=20, alpha=0.01, report=False):
if report:
stats = {}
# reset stats
stats["evals"] = 0
stats["residual"] = []
if self.mode == "gd":
for i in range(max_iters):
# compute residual
grad_func(x, self.dfdx)
# gradient step
wp.launch(kernel=gd_step, dim=self.n, inputs=[x, self.dfdx, alpha], device=self.device)
if report:
stats["evals"] += 1
r = np.linalg.norm(self.dfdx.to("cpu").numpy())
stats["residual"].append(r)
elif self.mode == "nesterov":
wp.copy(self.x_prev, x)
# momentum index (reset after restart)
b = 0
for iter in range(max_iters):
beta = (b - 1.0) / (b + 2.0)
b += 1
# y = x + beta*(x - x_prev)
wp.launch(kernel=nesterov1, dim=self.n, inputs=[beta, x, self.x_prev, self.y], device=self.device)
# grad
grad_func(self.y, self.dfdx)
# inner()
# np.dot(dfdx, x - x_prev)
# x = y - alpha*dfdx
wp.launch(
kernel=nesterov2,
dim=self.n,
inputs=[alpha, None, None, x, self.x_prev, self.y, self.dfdx],
device=self.device,
)
if report:
stats["evals"] += 1
r = np.linalg.norm(self.dfdx.to("cpu").numpy())
stats["residual"].append(r)
else:
raise RuntimeError("Unknown optimizer")
if report:
print(stats)
| warp-main | warp/sim/optimizer.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 numpy as np
import os
import xml.etree.ElementTree as ET
import warp as wp
# SNU file format parser
class MuscleUnit:
def __init__(self):
self.name = ""
self.bones = []
self.points = []
class Skeleton:
def __init__(self, root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0):
self.parse_skeleton(skeleton_file, builder, filter, root_xform, armature)
self.parse_muscles(muscle_file, builder)
def parse_skeleton(self, filename, builder, filter, root_xform, armature):
file = ET.parse(filename)
root = file.getroot()
self.node_map = {} # map node names to link indices
self.xform_map = {} # map node names to parent transforms
self.mesh_map = {} # map mesh names to link indices objects
self.coord_start = builder.joint_coord_count
self.dof_start = builder.joint_dof_count
type_map = {
"Ball": wp.sim.JOINT_BALL,
"Revolute": wp.sim.JOINT_REVOLUTE,
"Prismatic": wp.sim.JOINT_PRISMATIC,
"Free": wp.sim.JOINT_FREE,
"Fixed": wp.sim.JOINT_FIXED,
}
builder.add_articulation()
for child in root:
if child.tag == "Node":
body = child.find("Body")
joint = child.find("Joint")
name = child.attrib["name"]
parent = child.attrib["parent"]
parent_X_s = wp.transform_identity()
if parent in self.node_map:
parent_link = self.node_map[parent]
parent_X_s = self.xform_map[parent]
else:
parent_link = -1
body_xform = body.find("Transformation")
joint_xform = joint.find("Transformation")
body_mesh = body.attrib["obj"]
body_size = np.fromstring(body.attrib["size"], sep=" ")
body_type = body.attrib["type"]
body_mass = body.attrib["mass"]
body_R_s = np.fromstring(body_xform.attrib["linear"], sep=" ").reshape((3, 3))
body_t_s = np.fromstring(body_xform.attrib["translation"], sep=" ")
joint_R_s = np.fromstring(joint_xform.attrib["linear"], sep=" ").reshape((3, 3))
joint_t_s = np.fromstring(joint_xform.attrib["translation"], sep=" ")
joint_type = type_map[joint.attrib["type"]]
joint_lower = np.array([-1.0e3])
joint_upper = np.array([1.0e3])
try:
joint_lower = np.fromstring(joint.attrib["lower"], sep=" ")
joint_upper = np.fromstring(joint.attrib["upper"], sep=" ")
except:
pass
if "axis" in joint.attrib:
joint_axis = np.fromstring(joint.attrib["axis"], sep=" ")
else:
joint_axis = np.array((0.0, 0.0, 0.0))
body_X_s = wp.transform(body_t_s, wp.quat_from_matrix(body_R_s))
joint_X_s = wp.transform(joint_t_s, wp.quat_from_matrix(joint_R_s))
mesh_base = os.path.splitext(body_mesh)[0]
mesh_file = mesh_base + ".usd"
# -----------------------------------
# one time conversion, put meshes into local body space (and meter units)
# stage = Usd.Stage.Open("./assets/snu/OBJ/" + mesh_file)
# geom = UsdGeom.Mesh.Get(stage, "/" + mesh_base + "_obj/defaultobject/defaultobject")
# body_X_bs = wp.transform_inverse(body_X_s)
# joint_X_bs = wp.transform_inverse(joint_X_s)
# points = geom.GetPointsAttr().Get()
# for i in range(len(points)):
# p = wp.transform_point(joint_X_bs, points[i]*0.01)
# points[i] = Gf.Vec3f(p.tolist()) # cm -> meters
# geom.GetPointsAttr().Set(points)
# extent = UsdGeom.Boundable.ComputeExtentFromPlugins(geom, 0.0)
# geom.GetExtentAttr().Set(extent)
# stage.Save()
# --------------------------------------
link = -1
if len(filter) == 0 or name in filter:
joint_X_p = wp.transform_multiply(wp.transform_inverse(parent_X_s), joint_X_s)
body_X_c = wp.transform_multiply(wp.transform_inverse(joint_X_s), body_X_s)
if parent_link == -1:
joint_X_p = wp.transform_identity()
# add link
link = builder.add_body(
parent=parent_link,
origin=wp.transform_multiply(root_xform, joint_X_s),
joint_xform=joint_X_p,
joint_axis=joint_axis,
joint_type=joint_type,
joint_target_ke=5.0,
joint_target_kd=2.0,
joint_limit_lower=joint_lower[0],
joint_limit_upper=joint_upper[0],
joint_limit_ke=1.0e3,
joint_limit_kd=1.0e2,
joint_armature=armature,
)
# add shape
shape = builder.add_shape_box(
body=link,
pos=body_X_c.p,
rot=body_X_c.q,
hx=body_size[0] * 0.5,
hy=body_size[1] * 0.5,
hz=body_size[2] * 0.5,
ke=1.0e3 * 5.0,
kd=1.0e2 * 2.0,
kf=1.0e3,
mu=0.5,
)
# add lookup in name->link map
# save parent transform
self.xform_map[name] = joint_X_s
self.node_map[name] = link
self.mesh_map[mesh_base] = link
def parse_muscles(self, filename, builder):
# list of MuscleUnits
muscles = []
file = ET.parse(filename)
root = file.getroot()
self.muscle_start = len(builder.muscle_activation)
for child in root:
if child.tag == "Unit":
unit_name = child.attrib["name"]
unit_f0 = float(child.attrib["f0"])
unit_lm = float(child.attrib["lm"])
unit_lt = float(child.attrib["lt"])
unit_lmax = float(child.attrib["lmax"])
unit_pen = float(child.attrib["pen_angle"])
m = MuscleUnit()
m.name = unit_name
incomplete = False
for waypoint in child.iter("Waypoint"):
way_bone = waypoint.attrib["body"]
way_link = self.node_map[way_bone]
way_loc = np.fromstring(waypoint.attrib["p"], sep=" ", dtype=np.float32)
if way_link == -1:
incomplete = True
break
# transform loc to joint local space
joint_X_s = self.xform_map[way_bone]
way_loc = wp.transform_point(wp.transform_inverse(joint_X_s), way_loc)
m.bones.append(way_link)
m.points.append(way_loc)
if not incomplete:
muscles.append(m)
builder.add_muscle(
m.bones, m.points, f0=unit_f0, lm=unit_lm, lt=unit_lt, lmax=unit_lmax, pen=unit_pen
)
self.muscles = muscles
def parse_snu(root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0):
return Skeleton(root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0)
| warp-main | warp/sim/import_snu.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 re
import warp as wp
from . import ModelBuilder
def parse_usd(
filename,
builder: ModelBuilder,
default_density=1.0e3,
only_load_enabled_rigid_bodies=False,
only_load_enabled_joints=True,
default_ke=1e5,
default_kd=250.0,
default_kf=500.0,
default_mu=0.0,
default_restitution=0.0,
default_thickness=0.0,
joint_limit_ke=100.0,
joint_limit_kd=10.0,
verbose=False,
ignore_paths=[],
export_usda=False,
):
"""
Parses a USD file containing UsdPhysics schema definitions for rigid-body articulations and adds the bodies, shapes and joints to the given ModelBuilder.
Args:
filename (str): The file path or URL to the USD file to parse.
builder (ModelBuilder): The :class:`ModelBuilder` to add the bodies and joints to.
default_density (float): The default density to use for bodies without a density attribute.
only_load_enabled_rigid_bodies (bool): If True, only rigid bodies which do not have `physics:rigidBodyEnabled` set to False are loaded.
only_load_enabled_joints (bool): If True, only joints which do not have `physics:jointEnabled` set to False are loaded.
default_ke (float): The default contact stiffness to use, only considered by SemiImplicitIntegrator.
default_kd (float): The default contact damping to use, only considered by SemiImplicitIntegrator.
default_kf (float): The default friction stiffness to use, only considered by SemiImplicitIntegrator.
default_mu (float): The default friction coefficient to use if a shape has not friction coefficient defined.
default_restitution (float): The default coefficient of restitution to use if a shape has not coefficient of restitution defined.
default_thickness (float): The thickness to add to the shape geometry.
joint_limit_ke (float): The default stiffness to use for joint limits, only considered by SemiImplicitIntegrator.
joint_limit_kd (float): The default damping to use for joint limits, only considered by SemiImplicitIntegrator.
verbose (bool): If True, print additional information about the parsed USD file.
ignore_paths (List[str]): A list of regular expressions matching prim paths to ignore.
export_usda (bool): If True and the filename is a URL, export the downloaded USD file to a USDA file.
Returns:
dict: Dictionary with the following entries: "fps": USD stage frames per second. "duration": Difference between end time code and start time code of the USD stage. "up_axis": Upper-case string of the stage up axis.
Note:
This importer is experimental and only supports a subset of the USD Physics schema. Please report any issues you encounter.
"""
try:
from pxr import Usd, UsdGeom, UsdPhysics
except ImportError:
raise ImportError("Failed to import pxr. Please install USD.")
if filename.startswith("http://") or filename.startswith("https://"):
# download file
import requests
import os
import datetime
response = requests.get(filename, allow_redirects=True)
if response.status_code != 200:
raise RuntimeError(f"Failed to download USD file. Status code: {response.status_code}")
file = response.content
dot = os.path.extsep
base = os.path.basename(filename)
url_folder = os.path.dirname(filename)
base_name = dot.join(base.split(dot)[:-1])
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
folder_name = os.path.join(".usd_cache", f"{base_name}_{timestamp}")
os.makedirs(folder_name, exist_ok=True)
target_filename = os.path.join(folder_name, base)
with open(target_filename, "wb") as f:
f.write(file)
stage = Usd.Stage.Open(target_filename, Usd.Stage.LoadNone)
stage_str = stage.GetRootLayer().ExportToString()
print(f"Downloaded USD file to {target_filename}.")
if export_usda:
usda_filename = os.path.join(folder_name, base_name + ".usda")
with open(usda_filename, "w") as f:
f.write(stage_str)
print(f"Exported USDA file to {usda_filename}.")
# parse referenced USD files like `references = @./franka_collisions.usd@`
downloaded = set()
for match in re.finditer(r"references.=.@(.*?)@", stage_str):
refname = match.group(1)
if refname.startswith("./"):
refname = refname[2:]
if refname in downloaded:
continue
try:
response = requests.get(f"{url_folder}/{refname}", allow_redirects=True)
if response.status_code != 200:
print(f"Failed to download reference {refname}. Status code: {response.status_code}")
continue
file = response.content
refdir = os.path.dirname(refname)
if refdir:
os.makedirs(os.path.join(folder_name, refdir), exist_ok=True)
ref_filename = os.path.join(folder_name, refname)
with open(ref_filename, "wb") as f:
f.write(file)
downloaded.add(refname)
print(f"Downloaded USD reference {refname} to {ref_filename}.")
if export_usda:
ref_stage = Usd.Stage.Open(ref_filename, Usd.Stage.LoadNone)
ref_stage_str = ref_stage.GetRootLayer().ExportToString()
base = os.path.basename(ref_filename)
base_name = dot.join(base.split(dot)[:-1])
usda_filename = os.path.join(folder_name, base_name + ".usda")
with open(usda_filename, "w") as f:
f.write(ref_stage_str)
print(f"Exported USDA file to {usda_filename}.")
except Exception:
print(f"Failed to download {refname}.")
filename = target_filename
def get_attribute(prim, name):
if "*" in name:
regex = name.replace("*", ".*")
for attr in prim.GetAttributes():
if re.match(regex, attr.GetName()):
return attr
else:
return prim.GetAttribute(name)
def has_attribute(prim, name):
attr = get_attribute(prim, name)
return attr.IsValid() and attr.HasAuthoredValue()
def parse_float(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
val = attr.Get()
if np.isfinite(val):
return val
return default
def parse_quat(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
val = attr.Get()
quat = wp.quat(*val.imaginary, val.real)
l = wp.length(quat)
if np.isfinite(l) and l > 0.0:
return quat
return default
def parse_vec(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
val = attr.Get()
if np.isfinite(val).all():
return np.array(val, dtype=np.float32)
return default
def parse_generic(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
return attr.Get()
def str2axis(s: str) -> np.ndarray:
axis = np.zeros(3, dtype=np.float32)
axis["XYZ".index(s.upper())] = 1.0
return axis
stage = Usd.Stage.Open(filename, Usd.Stage.LoadAll)
if UsdPhysics.StageHasAuthoredKilogramsPerUnit(stage):
mass_unit = UsdPhysics.GetStageKilogramsPerUnit(stage)
else:
mass_unit = 1.0
if UsdGeom.StageHasAuthoredMetersPerUnit(stage):
linear_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
linear_unit = 1.0
def parse_xform(prim):
xform = UsdGeom.Xform(prim)
mat = np.array(xform.GetLocalTransformation(), dtype=np.float32)
rot = wp.quat_from_matrix(wp.mat33(mat[:3, :3].flatten()))
pos = mat[3, :3] * linear_unit
scale = np.ones(3, dtype=np.float32)
for op in xform.GetOrderedXformOps():
if op.GetOpType() == UsdGeom.XformOp.TypeScale:
scale = np.array(op.Get(), dtype=np.float32)
return wp.transform(pos, rot), scale
def parse_axis(prim, type, joint_data, is_angular, axis=None):
# parse joint axis data
schemas = prim.GetAppliedSchemas()
schemas_str = "".join(schemas)
if f"DriveAPI:{type}" not in schemas_str and f"PhysicsLimitAPI:{type}" not in schemas_str:
return
drive_type = parse_generic(prim, f"drive:{type}:physics:type", "force")
if drive_type != "force":
print(f"Warning: only force drive type is supported, ignoring drive:{type} for joint {path}")
return
stiffness = parse_float(prim, f"drive:{type}:physics:stiffness", 0.0)
damping = parse_float(prim, f"drive:{type}:physics:damping", 0.0)
low = parse_float(prim, f"limit:{type}:physics:low")
high = parse_float(prim, f"limit:{type}:physics:high")
target_pos = parse_float(prim, f"drive:{type}:physics:targetPosition")
target_vel = parse_float(prim, f"drive:{type}:physics:targetVelocity")
if is_angular:
stiffness *= mass_unit * linear_unit**2
stiffness = np.deg2rad(stiffness)
damping *= mass_unit * linear_unit**2
damping = np.deg2rad(damping)
if target_pos is not None:
target_pos = np.deg2rad(target_pos)
if target_vel is not None:
target_vel = np.deg2rad(target_vel)
if low is None:
low = joint_data["lowerLimit"]
else:
low = np.deg2rad(low)
if high is None:
high = joint_data["upperLimit"]
else:
high = np.deg2rad(high)
else:
stiffness *= mass_unit
damping *= mass_unit
if target_pos is not None:
target_pos *= linear_unit
if target_vel is not None:
target_vel *= linear_unit
if low is None:
low = joint_data["lowerLimit"]
else:
low *= linear_unit
if high is None:
high = joint_data["upperLimit"]
else:
high *= linear_unit
mode = wp.sim.JOINT_MODE_LIMIT
if f"DriveAPI:{type}" in schemas_str:
if target_vel is not None and target_vel != 0.0:
mode = wp.sim.JOINT_MODE_TARGET_VELOCITY
else:
mode = wp.sim.JOINT_MODE_TARGET_POSITION
if low > high:
low = (low + high) / 2
high = low
axis = wp.sim.JointAxis(
axis=(axis or joint_data["axis"]),
limit_lower=low,
limit_upper=high,
target=(target_pos or target_vel or (low + high) / 2),
target_ke=stiffness,
target_kd=damping,
mode=mode,
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
if is_angular:
joint_data["angular_axes"].append(axis)
else:
joint_data["linear_axes"].append(axis)
upaxis = str2axis(UsdGeom.GetStageUpAxis(stage))
shape_types = {"Cube", "Sphere", "Mesh", "Capsule", "Plane", "Cylinder", "Cone"}
path_body_map = {}
path_shape_map = {}
# maps prim path name to its world transform
path_world_poses = {}
# transform from body frame to where the actual joint child frame is
# so that the link's children will use the right parent tf for the joint
prim_joint_xforms = {}
path_collision_filters = set()
no_collision_shapes = set()
body_density = {} # mapping from body ID to defined density
# first find all joints and materials
joint_data = {} # mapping from path of child link to joint USD settings
materials = {} # mapping from material path to material USD settings
joint_parents = set() # paths of joint parents
for prim in stage.Traverse():
type_name = str(prim.GetTypeName())
path = str(prim.GetPath())
# if verbose:
# print(path, type_name)
if type_name.endswith("Joint"):
# the type name can sometimes be "DistancePhysicsJoint" or "PhysicsDistanceJoint" ...
type_name = type_name.replace("Physics", "").replace("Joint", "")
child = str(prim.GetRelationship("physics:body1").GetTargets()[0])
pos0 = parse_vec(prim, "physics:localPos0", np.zeros(3, dtype=np.float32)) * linear_unit
pos1 = parse_vec(prim, "physics:localPos1", np.zeros(3, dtype=np.float32)) * linear_unit
rot0 = parse_quat(prim, "physics:localRot0", wp.quat_identity())
rot1 = parse_quat(prim, "physics:localRot1", wp.quat_identity())
joint_data[child] = {
"type": type_name,
"name": str(prim.GetName()),
"parent_tf": wp.transform(pos0, rot0),
"child_tf": wp.transform(pos1, rot1),
"enabled": parse_generic(prim, "physics:jointEnabled", True),
"collisionEnabled": parse_generic(prim, "physics:collisionEnabled", False),
"excludeFromArticulation": parse_generic(prim, "physics:excludeFromArticulation", False),
"axis": str2axis(parse_generic(prim, "physics:axis", "X")),
"breakForce": parse_float(prim, "physics:breakForce", np.inf),
"breakTorque": parse_float(prim, "physics:breakTorque", np.inf),
"linear_axes": [],
"angular_axes": [],
}
if only_load_enabled_joints and not joint_data[child]["enabled"]:
print("Skipping disabled joint", path)
continue
# parse joint limits
lower = parse_float(prim, "physics:lowerLimit", -np.inf)
upper = parse_float(prim, "physics:upperLimit", np.inf)
if type_name == "Distance":
# if distance is negative the joint is not limited
joint_data[child]["lowerLimit"] = parse_float(prim, "physics:minDistance", -1.0) * linear_unit
joint_data[child]["upperLimit"] = parse_float(prim, "physics:maxDistance", -1.0) * linear_unit
elif type_name == "Prismatic":
joint_data[child]["lowerLimit"] = lower * linear_unit
joint_data[child]["upperLimit"] = upper * linear_unit
else:
joint_data[child]["lowerLimit"] = np.deg2rad(lower) if np.isfinite(lower) else lower
joint_data[child]["upperLimit"] = np.deg2rad(upper) if np.isfinite(upper) else upper
if joint_data[child]["lowerLimit"] > joint_data[child]["upperLimit"]:
joint_data[child]["lowerLimit"] = (
joint_data[child]["lowerLimit"] + joint_data[child]["upperLimit"]
) / 2
joint_data[child]["upperLimit"] = joint_data[child]["lowerLimit"]
parents = prim.GetRelationship("physics:body0").GetTargets()
if len(parents) > 0:
parent_path = str(parents[0])
joint_data[child]["parent"] = parent_path
joint_parents.add(parent_path)
else:
joint_data[child]["parent"] = None
# parse joint drive
parse_axis(prim, "angular", joint_data[child], is_angular=True)
parse_axis(prim, "rotX", joint_data[child], is_angular=True, axis=(1.0, 0.0, 0.0))
parse_axis(prim, "rotY", joint_data[child], is_angular=True, axis=(0.0, 1.0, 0.0))
parse_axis(prim, "rotZ", joint_data[child], is_angular=True, axis=(0.0, 0.0, 1.0))
parse_axis(prim, "linear", joint_data[child], is_angular=False)
parse_axis(prim, "transX", joint_data[child], is_angular=False, axis=(1.0, 0.0, 0.0))
parse_axis(prim, "transY", joint_data[child], is_angular=False, axis=(0.0, 1.0, 0.0))
parse_axis(prim, "transZ", joint_data[child], is_angular=False, axis=(0.0, 0.0, 1.0))
elif type_name == "Material":
material = {}
if has_attribute(prim, "physics:density"):
material["density"] = parse_float(prim, "physics:density") * mass_unit # / (linear_unit**3)
if has_attribute(prim, "physics:restitution"):
material["restitution"] = parse_float(prim, "physics:restitution", default_restitution)
if has_attribute(prim, "physics:staticFriction"):
material["staticFriction"] = parse_float(prim, "physics:staticFriction", default_mu)
if has_attribute(prim, "physics:dynamicFriction"):
material["dynamicFriction"] = parse_float(prim, "physics:dynamicFriction", default_mu)
materials[path] = material
elif type_name == "PhysicsScene":
scene = UsdPhysics.Scene(prim)
g_vec = scene.GetGravityDirectionAttr()
g_mag = scene.GetGravityMagnitudeAttr()
if g_mag.HasAuthoredValue() and np.isfinite(g_mag.Get()):
builder.gravity = g_mag.Get() * linear_unit
if g_vec.HasAuthoredValue() and np.linalg.norm(g_vec.Get()) > 0.0:
builder.up_vector = np.array(g_vec.Get(), dtype=np.float32) # TODO flip sign?
else:
builder.up_vector = upaxis
def parse_prim(prim, incoming_xform, incoming_scale, parent_body: int = -1):
nonlocal builder
nonlocal joint_data
nonlocal path_body_map
nonlocal path_shape_map
nonlocal path_world_poses
nonlocal prim_joint_xforms
nonlocal path_collision_filters
nonlocal no_collision_shapes
nonlocal body_density
path = str(prim.GetPath())
for pattern in ignore_paths:
if re.match(pattern, path):
return
type_name = str(prim.GetTypeName())
if (
type_name.endswith("Joint")
or type_name.endswith("Light")
or type_name.endswith("Scene")
or type_name.endswith("Material")
):
return
schemas = set(prim.GetAppliedSchemas())
children_refs = prim.GetChildren()
prim_joint_xforms[path] = wp.transform()
local_xform, scale = parse_xform(prim)
scale = incoming_scale * scale
xform = wp.mul(incoming_xform, local_xform)
path_world_poses[path] = xform
geo_tf = local_xform
body_id = parent_body
is_rigid_body = "PhysicsRigidBodyAPI" in schemas and parent_body == -1
create_rigid_body = is_rigid_body or path in joint_parents
if create_rigid_body:
body_id = builder.add_body(
origin=xform,
name=prim.GetName(),
)
path_body_map[path] = body_id
body_density[body_id] = 0.0
parent_body = body_id
geo_tf = wp.transform()
# set up joints between rigid bodies after the children have been added
if path in joint_data:
joint = joint_data[path]
joint_params = dict(
child=body_id,
linear_axes=joint["linear_axes"],
angular_axes=joint["angular_axes"],
name=joint["name"],
enabled=joint["enabled"],
parent_xform=joint["parent_tf"],
child_xform=joint["child_tf"],
)
parent_path = joint["parent"]
if parent_path is None:
joint_params["parent"] = -1
parent_tf = wp.transform()
else:
joint_params["parent"] = path_body_map[parent_path]
parent_tf = path_world_poses[parent_path]
# the joint to which we are connected will transform this body already
geo_tf = wp.transform()
if verbose:
print(f"Adding joint {joint['name']} between {joint['parent']} and {path}")
print(" parent_xform", joint["parent_tf"])
print(" child_xform ", joint["child_tf"])
print(" parent_tf ", parent_tf)
print(f" geo_tf at {path} = {geo_tf} (xform was {xform})")
if joint["type"] == "Revolute":
joint_params["joint_type"] = wp.sim.JOINT_REVOLUTE
if len(joint_params["angular_axes"]) == 0:
joint_params["angular_axes"].append(
wp.sim.JointAxis(
joint["axis"],
limit_lower=joint["lowerLimit"],
limit_upper=joint["upperLimit"],
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
)
elif joint["type"] == "Prismatic":
joint_params["joint_type"] = wp.sim.JOINT_PRISMATIC
if len(joint_params["linear_axes"]) == 0:
joint_params["linear_axes"].append(
wp.sim.JointAxis(
joint["axis"],
limit_lower=joint["lowerLimit"],
limit_upper=joint["upperLimit"],
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
)
elif joint["type"] == "Spherical":
joint_params["joint_type"] = wp.sim.JOINT_BALL
elif joint["type"] == "Fixed":
joint_params["joint_type"] = wp.sim.JOINT_FIXED
elif joint["type"] == "Distance":
joint_params["joint_type"] = wp.sim.JOINT_DISTANCE
# we have to add a dummy linear X axis to define the joint limits
joint_params["linear_axes"].append(
wp.sim.JointAxis(
(1.0, 0.0, 0.0),
limit_lower=joint["lowerLimit"],
limit_upper=joint["upperLimit"],
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
)
elif joint["type"] == "":
joint_params["joint_type"] = wp.sim.JOINT_D6
else:
print(f"Warning: unsupported joint type {joint['type']} for {path}")
builder.add_joint(**joint_params)
elif is_rigid_body:
builder.add_joint_free(child=body_id)
# free joint; we set joint_q/qd, not body_q/qd since eval_fk is used after model creation
builder.joint_q[-4:] = xform.q
builder.joint_q[-7:-4] = xform.p
linear_vel = parse_vec(prim, "physics:velocity", np.zeros(3, dtype=np.float32)) * linear_unit
angular_vel = parse_vec(prim, "physics:angularVelocity", np.zeros(3, dtype=np.float32)) * linear_unit
builder.joint_qd[-6:-3] = angular_vel
builder.joint_qd[-3:] = linear_vel
if verbose:
print(f"added {type_name} body {body_id} ({path}) at {xform}")
density = None
material = None
if prim.HasRelationship("material:binding:physics"):
other_paths = prim.GetRelationship("material:binding:physics").GetTargets()
if len(other_paths) > 0:
material = materials[str(other_paths[0])]
if material is not None:
if "density" in material:
density = material["density"]
if has_attribute(prim, "physics:density"):
d = parse_float(prim, "physics:density")
density = d * mass_unit # / (linear_unit**3)
# assert prim.GetAttribute('orientation').Get() == "rightHanded", "Only right-handed orientations are supported."
enabled = parse_generic(prim, "physics:rigidBodyEnabled", True)
if only_load_enabled_rigid_bodies and not enabled:
if verbose:
print("Skipping disabled rigid body", path)
return
mass = parse_float(prim, "physics:mass")
if is_rigid_body:
if density is None:
density = default_density
body_density[body_id] = density
elif density is None:
if body_id >= 0:
density = body_density[body_id]
else:
density = 0.0
com = parse_vec(prim, "physics:centerOfMass", np.zeros(3, dtype=np.float32))
i_diag = parse_vec(prim, "physics:diagonalInertia", np.zeros(3, dtype=np.float32))
i_rot = parse_quat(prim, "physics:principalAxes", wp.quat_identity())
# parse children
if type_name == "Xform":
if prim.IsInstance():
proto = prim.GetPrototype()
for child in proto.GetChildren():
parse_prim(child, xform, scale, parent_body)
else:
for child in children_refs:
parse_prim(child, xform, scale, parent_body)
elif type_name == "Scope":
for child in children_refs:
parse_prim(child, incoming_xform, incoming_scale, parent_body)
elif type_name in shape_types:
# parse shapes
shape_params = dict(
ke=default_ke, kd=default_kd, kf=default_kf, mu=default_mu, restitution=default_restitution
)
if material is not None:
if "restitution" in material:
shape_params["restitution"] = material["restitution"]
if "dynamicFriction" in material:
shape_params["mu"] = material["dynamicFriction"]
if has_attribute(prim, "doubleSided") and not prim.GetAttribute("doubleSided").Get():
print(f"Warning: treating {path} as double-sided because single-sided collisions are not supported.")
if type_name == "Cube":
size = parse_float(prim, "size", 2.0)
if has_attribute(prim, "extents"):
extents = parse_vec(prim, "extents") * scale
# TODO position geom at extents center?
geo_pos = 0.5 * (extents[0] + extents[1])
extents = extents[1] - extents[0]
else:
extents = scale * size
shape_id = builder.add_shape_box(
body_id,
geo_tf.p,
geo_tf.q,
hx=extents[0] / 2,
hy=extents[1] / 2,
hz=extents[2] / 2,
density=density,
thickness=default_thickness,
**shape_params,
)
elif type_name == "Sphere":
if not (scale[0] == scale[1] == scale[2]):
print("Warning: Non-uniform scaling of spheres is not supported.")
if has_attribute(prim, "extents"):
extents = parse_vec(prim, "extents") * scale
# TODO position geom at extents center?
geo_pos = 0.5 * (extents[0] + extents[1])
extents = extents[1] - extents[0]
if not (extents[0] == extents[1] == extents[2]):
print("Warning: Non-uniform extents of spheres are not supported.")
radius = extents[0]
else:
radius = parse_float(prim, "radius", 1.0) * scale[0]
shape_id = builder.add_shape_sphere(
body_id, geo_tf.p, geo_tf.q, radius, density=density, **shape_params
)
elif type_name == "Plane":
normal_str = parse_generic(prim, "axis", "Z").upper()
geo_rot = geo_tf.q
if normal_str != "Y":
normal = str2axis(normal_str)
c = np.cross(normal, (0.0, 1.0, 0.0))
angle = np.arcsin(np.linalg.norm(c))
axis = c / np.linalg.norm(c)
geo_rot = wp.mul(geo_rot, wp.quat_from_axis_angle(axis, angle))
width = parse_float(prim, "width", 0.0) * scale[0]
length = parse_float(prim, "length", 0.0) * scale[1]
shape_id = builder.add_shape_plane(
body=body_id,
pos=geo_tf.p,
rot=geo_rot,
width=width,
length=length,
thickness=default_thickness,
**shape_params,
)
elif type_name == "Capsule":
axis_str = parse_generic(prim, "axis", "Z").upper()
radius = parse_float(prim, "radius", 0.5) * scale[0]
half_height = parse_float(prim, "height", 2.0) / 2 * scale[1]
assert not has_attribute(prim, "extents"), "Capsule extents are not supported."
shape_id = builder.add_shape_capsule(
body_id,
geo_tf.p,
geo_tf.q,
radius,
half_height,
density=density,
up_axis="XYZ".index(axis_str),
**shape_params,
)
elif type_name == "Cylinder":
axis_str = parse_generic(prim, "axis", "Z").upper()
radius = parse_float(prim, "radius", 0.5) * scale[0]
half_height = parse_float(prim, "height", 2.0) / 2 * scale[1]
assert not has_attribute(prim, "extents"), "Cylinder extents are not supported."
shape_id = builder.add_shape_cylinder(
body_id,
geo_tf.p,
geo_tf.q,
radius,
half_height,
density=density,
up_axis="XYZ".index(axis_str),
**shape_params,
)
elif type_name == "Cone":
axis_str = parse_generic(prim, "axis", "Z").upper()
radius = parse_float(prim, "radius", 0.5) * scale[0]
half_height = parse_float(prim, "height", 2.0) / 2 * scale[1]
assert not has_attribute(prim, "extents"), "Cone extents are not supported."
shape_id = builder.add_shape_cone(
body_id,
geo_tf.p,
geo_tf.q,
radius,
half_height,
density=density,
up_axis="XYZ".index(axis_str),
**shape_params,
)
elif type_name == "Mesh":
mesh = UsdGeom.Mesh(prim)
points = np.array(mesh.GetPointsAttr().Get(), dtype=np.float32)
indices = np.array(mesh.GetFaceVertexIndicesAttr().Get(), dtype=np.float32)
counts = mesh.GetFaceVertexCountsAttr().Get()
faces = []
face_id = 0
for count in counts:
if count == 3:
faces.append(indices[face_id : face_id + 3])
elif count == 4:
faces.append(indices[face_id : face_id + 3])
faces.append(indices[[face_id, face_id + 2, face_id + 3]])
else:
# assert False, f"Error while parsing USD mesh {path}: encountered polygon with {count} vertices, but only triangles and quads are supported."
continue
face_id += count
m = wp.sim.Mesh(points, np.array(faces, dtype=np.int32).flatten())
shape_id = builder.add_shape_mesh(
body_id,
geo_tf.p,
geo_tf.q,
scale=scale,
mesh=m,
density=density,
thickness=default_thickness,
**shape_params,
)
else:
print(f"Warning: Unsupported geometry type {type_name} at {path}.")
return
path_body_map[path] = body_id
path_shape_map[path] = shape_id
if prim.HasRelationship("physics:filteredPairs"):
other_paths = prim.GetRelationship("physics:filteredPairs").GetTargets()
for other_path in other_paths:
path_collision_filters.add((path, str(other_path)))
if "PhysicsCollisionAPI" not in schemas or not parse_generic(prim, "physics:collisionEnabled", True):
no_collision_shapes.add(shape_id)
else:
print(f"Warning: encountered unsupported prim type {type_name}")
# update mass properties of rigid bodies in cases where properties are defined with higher precedence
if body_id >= 0:
com = parse_vec(prim, "physics:centerOfMass")
if com is not None:
# overwrite COM
builder.body_com[body_id] = com * scale
if mass is not None and not (is_rigid_body and mass == 0.0):
mass_ratio = mass / builder.body_mass[body_id]
# mass has precedence over density, so we overwrite the mass computed from density
builder.body_mass[body_id] = mass * mass_unit
if mass > 0.0:
builder.body_inv_mass[body_id] = 1.0 / builder.body_mass[body_id]
else:
builder.body_inv_mass[body_id] = 0.0
# update inertia
builder.body_inertia[body_id] *= mass_ratio
if builder.body_inertia[body_id].any():
builder.body_inv_inertia[body_id] = np.linalg.inv(builder.body_inertia[body_id])
else:
builder.body_inv_inertia[body_id] = np.zeros((3, 3), dtype=np.float32)
if np.linalg.norm(i_diag) > 0.0:
rot = np.array(wp.quat_to_matrix(i_rot), dtype=np.float32).reshape(3, 3)
inertia = rot @ np.diag(i_diag) @ rot.T
builder.body_inertia[body_id] = inertia
if inertia.any():
builder.body_inv_inertia[body_id] = np.linalg.inv(inertia)
else:
builder.body_inv_inertia[body_id] = np.zeros((3, 3), dtype=np.float32)
parse_prim(
stage.GetDefaultPrim(), incoming_xform=wp.transform(), incoming_scale=np.ones(3, dtype=np.float32) * linear_unit
)
shape_count = len(builder.shape_geo_type)
# apply collision filters now that we have added all shapes
for path1, path2 in path_collision_filters:
shape1 = path_shape_map[path1]
shape2 = path_shape_map[path2]
builder.shape_collision_filter_pairs.add((shape1, shape2))
# apply collision filters to all shapes that have no collision
for shape_id in no_collision_shapes:
for other_shape_id in range(shape_count):
if other_shape_id != shape_id:
builder.shape_collision_filter_pairs.add((shape_id, other_shape_id))
# return stage parameters
return {
"fps": stage.GetFramesPerSecond(),
"duration": stage.GetEndTimeCode() - stage.GetStartTimeCode(),
"up_axis": UsdGeom.GetStageUpAxis(stage).upper(),
}
| warp-main | warp/sim/import_usd.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 .utils import quat_decompose, quat_twist, quat_twist_angle
@wp.kernel
def eval_articulation_fk(
articulation_start: wp.array(dtype=int),
articulation_mask: wp.array(
dtype=int
), # used to enable / disable FK for an articulation, if None then treat all as enabled
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
body_com: wp.array(dtype=wp.vec3),
# outputs
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
# early out if disabling FK for this articulation
if articulation_mask:
if articulation_mask[tid] == 0:
return
joint_start = articulation_start[tid]
joint_end = articulation_start[tid + 1]
for i in range(joint_start, joint_end):
parent = joint_parent[i]
child = joint_child[i]
X_wp = wp.transform_identity()
v_wp = wp.spatial_vector()
if parent >= 0:
X_wp = body_q[parent]
v_wp = body_qd[parent]
# compute transform across the joint
type = joint_type[i]
X_pj = joint_X_p[i]
X_cj = joint_X_c[i]
q_start = joint_q_start[i]
qd_start = joint_qd_start[i]
axis_start = joint_axis_start[i]
lin_axis_count = joint_axis_dim[i, 0]
ang_axis_count = joint_axis_dim[i, 1]
X_jc = wp.transform_identity()
v_jc = wp.spatial_vector(wp.vec3(), wp.vec3())
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
q = joint_q[q_start]
qd = joint_qd[qd_start]
X_jc = wp.transform(axis * q, wp.quat_identity())
v_jc = wp.spatial_vector(wp.vec3(), axis * qd)
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
q = joint_q[q_start]
qd = joint_qd[qd_start]
X_jc = wp.transform(wp.vec3(), wp.quat_from_axis_angle(axis, q))
v_jc = wp.spatial_vector(axis * qd, wp.vec3())
if type == wp.sim.JOINT_BALL:
r = wp.quat(joint_q[q_start + 0], joint_q[q_start + 1], joint_q[q_start + 2], joint_q[q_start + 3])
w = wp.vec3(joint_qd[qd_start + 0], joint_qd[qd_start + 1], joint_qd[qd_start + 2])
# print(r)
X_jc = wp.transform(wp.vec3(), r)
v_jc = wp.spatial_vector(w, wp.vec3())
if type == wp.sim.JOINT_FREE:
t = wp.transform(
wp.vec3(joint_q[q_start + 0], joint_q[q_start + 1], joint_q[q_start + 2]),
wp.quat(joint_q[q_start + 3], joint_q[q_start + 4], joint_q[q_start + 5], joint_q[q_start + 6]),
)
v = wp.spatial_vector(
wp.vec3(joint_qd[qd_start + 0], joint_qd[qd_start + 1], joint_qd[qd_start + 2]),
wp.vec3(joint_qd[qd_start + 3], joint_qd[qd_start + 4], joint_qd[qd_start + 5]),
)
X_jc = t
v_jc = v
if type == wp.sim.JOINT_COMPOUND:
axis = joint_axis[axis_start]
# reconstruct rotation axes, todo: can probably use fact that rz'*ry'*rx' == rx*ry*rz to avoid some work here
axis_0 = axis
q_0 = wp.quat_from_axis_angle(axis_0, joint_q[q_start + 0])
axis_1 = joint_axis[axis_start + 1]
q_1 = wp.quat_from_axis_angle(axis_1, joint_q[q_start + 1])
axis_2 = joint_axis[axis_start + 2]
q_2 = wp.quat_from_axis_angle(axis_2, joint_q[q_start + 2])
t = wp.transform(wp.vec3(), q_2 * q_1 * q_0)
v = wp.spatial_vector(
axis_0 * joint_qd[qd_start + 0] + axis_1 * joint_qd[qd_start + 1] + axis_2 * joint_qd[qd_start + 2],
wp.vec3(),
)
X_jc = t
v_jc = v
if type == wp.sim.JOINT_UNIVERSAL:
# reconstruct rotation axes
axis_0 = joint_axis[axis_start]
q_0 = wp.quat_from_axis_angle(axis_0, joint_q[q_start + 0])
axis_1 = joint_axis[axis_start + 1]
q_1 = wp.quat_from_axis_angle(axis_1, joint_q[q_start + 1])
t = wp.transform(wp.vec3(), q_1 * q_0)
v = wp.spatial_vector(axis_0 * joint_qd[qd_start + 0] + axis_1 * joint_qd[qd_start + 1], wp.vec3())
X_jc = t
v_jc = v
if type == wp.sim.JOINT_D6:
pos = wp.vec3(0.0)
rot = wp.quat_identity()
vel_v = wp.vec3(0.0)
vel_w = wp.vec3(0.0)
# unroll for loop to ensure joint actions remain differentiable
# (since differentiating through a for loop that updates a local variable is not supported)
if lin_axis_count > 0:
axis = joint_axis[axis_start + 0]
pos += axis * joint_q[q_start + 0]
vel_v += axis * joint_qd[qd_start + 0]
if lin_axis_count > 1:
axis = joint_axis[axis_start + 1]
pos += axis * joint_q[q_start + 1]
vel_v += axis * joint_qd[qd_start + 1]
if lin_axis_count > 2:
axis = joint_axis[axis_start + 2]
pos += axis * joint_q[q_start + 2]
vel_v += axis * joint_qd[qd_start + 2]
if ang_axis_count > 0:
axis = joint_axis[axis_start + lin_axis_count + 0]
qi = wp.quat_from_axis_angle(axis, joint_q[q_start + lin_axis_count + 0])
rot = qi * rot
vel_w += joint_qd[qd_start + lin_axis_count + 0] * axis
if ang_axis_count > 1:
axis = joint_axis[axis_start + lin_axis_count + 1]
qi = wp.quat_from_axis_angle(axis, joint_q[q_start + lin_axis_count + 1])
rot = qi * rot
vel_w += joint_qd[qd_start + lin_axis_count + 1] * axis
if ang_axis_count > 2:
axis = joint_axis[axis_start + lin_axis_count + 2]
qi = wp.quat_from_axis_angle(axis, joint_q[q_start + lin_axis_count + 2])
rot = qi * rot
vel_w += joint_qd[qd_start + lin_axis_count + 2] * axis
X_jc = wp.transform(pos, rot)
v_jc = wp.spatial_vector(vel_w, vel_v)
X_wj = X_wp * X_pj
X_wc = X_wj * X_jc
X_wc *= wp.transform_inverse(X_cj)
# transform velocity across the joint to world space
angular_vel = wp.transform_vector(X_wj, wp.spatial_top(v_jc))
linear_vel = wp.transform_vector(X_wj, wp.spatial_bottom(v_jc))
v_wc = v_wp + wp.spatial_vector(angular_vel, linear_vel + wp.cross(angular_vel, body_com[i]))
body_q[child] = X_wc
body_qd[child] = v_wc
# updates state body information based on joint coordinates
def eval_fk(model, joint_q, joint_qd, mask, state):
wp.launch(
kernel=eval_articulation_fk,
dim=model.articulation_count,
inputs=[
model.articulation_start,
mask,
joint_q,
joint_qd,
model.joint_q_start,
model.joint_qd_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
model.body_com,
],
outputs=[
state.body_q,
state.body_qd,
],
device=model.device,
)
@wp.kernel
def eval_articulation_ik(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
):
tid = wp.tid()
c_parent = joint_parent[tid]
c_child = joint_child[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
r_p = wp.vec3()
w_p = wp.vec3()
v_p = wp.vec3()
# parent transform and moment arm
if c_parent >= 0:
X_wp = body_q[c_parent] * X_wp
r_wp = wp.transform_get_translation(X_wp) - wp.transform_point(body_q[c_parent], body_com[c_parent])
twist_p = body_qd[c_parent]
w_p = wp.spatial_top(twist_p)
v_p = wp.spatial_bottom(twist_p) + wp.cross(w_p, r_wp)
# child transform and moment arm
X_wc = body_q[c_child] * joint_X_c[tid]
r_c = wp.transform_get_translation(X_wc) - wp.transform_point(body_q[c_child], body_com[c_child])
twist_c = body_qd[c_child]
w_c = wp.spatial_top(twist_c)
v_c = wp.spatial_bottom(twist_c) + wp.cross(w_c, r_c)
# joint properties
type = joint_type[tid]
x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
# translational error
x_err = x_c - x_p
v_err = v_c - v_p
w_err = w_c - w_p
q_start = joint_q_start[tid]
qd_start = joint_qd_start[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
# world space joint axis
axis_p = wp.transform_vector(X_wp, axis)
# evaluate joint coordinates
q = wp.dot(x_err, axis_p)
qd = wp.dot(v_err, axis_p)
joint_q[q_start] = q
joint_qd[qd_start] = qd
return
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
axis_p = wp.transform_vector(X_wp, axis)
axis_c = wp.transform_vector(X_wc, axis)
# swing twist decomposition
q_pc = wp.quat_inverse(q_p) * q_c
twist = quat_twist(axis, q_pc)
q = wp.acos(twist[3]) * 2.0 * wp.sign(wp.dot(axis, wp.vec3(twist[0], twist[1], twist[2])))
qd = wp.dot(w_err, axis_p)
joint_q[q_start] = q
joint_qd[qd_start] = qd
return
if type == wp.sim.JOINT_BALL:
q_pc = wp.quat_inverse(q_p) * q_c
joint_q[q_start + 0] = q_pc[0]
joint_q[q_start + 1] = q_pc[1]
joint_q[q_start + 2] = q_pc[2]
joint_q[q_start + 3] = q_pc[3]
joint_qd[qd_start + 0] = w_err[0]
joint_qd[qd_start + 1] = w_err[1]
joint_qd[qd_start + 2] = w_err[2]
return
if type == wp.sim.JOINT_FIXED:
return
if type == wp.sim.JOINT_FREE:
q_pc = wp.quat_inverse(q_p) * q_c
joint_q[q_start + 0] = x_err[0]
joint_q[q_start + 1] = x_err[1]
joint_q[q_start + 2] = x_err[2]
joint_q[q_start + 3] = q_pc[0]
joint_q[q_start + 4] = q_pc[1]
joint_q[q_start + 5] = q_pc[2]
joint_q[q_start + 6] = q_pc[3]
joint_qd[qd_start + 0] = w_err[0]
joint_qd[qd_start + 1] = w_err[1]
joint_qd[qd_start + 2] = w_err[2]
joint_qd[qd_start + 3] = v_err[0]
joint_qd[qd_start + 4] = v_err[1]
joint_qd[qd_start + 5] = v_err[2]
if type == wp.sim.JOINT_COMPOUND:
q_off = wp.transform_get_rotation(X_cj)
q_pc = wp.quat_inverse(q_off) * wp.quat_inverse(q_p) * q_c * q_off
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# reconstruct rotation axes
axis_0 = wp.vec3(1.0, 0.0, 0.0)
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, wp.vec3(0.0, 0.0, 1.0))
q_2 = wp.quat_from_axis_angle(axis_2, angles[2])
q_w = q_p * q_off
joint_q[q_start + 0] = angles[0]
joint_q[q_start + 1] = angles[1]
joint_q[q_start + 2] = angles[2]
joint_qd[qd_start + 0] = wp.dot(wp.quat_rotate(q_w, axis_0), w_err)
joint_qd[qd_start + 1] = wp.dot(wp.quat_rotate(q_w, axis_1), w_err)
joint_qd[qd_start + 2] = wp.dot(wp.quat_rotate(q_w, axis_2), w_err)
return
if type == wp.sim.JOINT_UNIVERSAL:
q_off = wp.transform_get_rotation(X_cj)
q_pc = wp.quat_inverse(q_off) * wp.quat_inverse(q_p) * q_c * q_off
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# reconstruct rotation axes
axis_0 = wp.vec3(1.0, 0.0, 0.0)
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
q_w = q_p * q_off
joint_q[q_start + 0] = angles[0]
joint_q[q_start + 1] = angles[1]
joint_qd[qd_start + 0] = wp.dot(wp.quat_rotate(q_w, axis_0), w_err)
joint_qd[qd_start + 1] = wp.dot(wp.quat_rotate(q_w, axis_1), w_err)
return
if type == wp.sim.JOINT_D6:
if lin_axis_count > 0:
axis = wp.transform_vector(X_wp, joint_axis[axis_start + 0])
joint_q[q_start + 0] = wp.dot(x_err, axis)
joint_qd[qd_start + 0] = wp.dot(v_err, axis)
if lin_axis_count > 1:
axis = wp.transform_vector(X_wp, joint_axis[axis_start + 1])
joint_q[q_start + 1] = wp.dot(x_err, axis)
joint_qd[qd_start + 1] = wp.dot(v_err, axis)
if lin_axis_count > 2:
axis = wp.transform_vector(X_wp, joint_axis[axis_start + 2])
joint_q[q_start + 2] = wp.dot(x_err, axis)
joint_qd[qd_start + 2] = wp.dot(v_err, axis)
q_pc = wp.quat_inverse(q_p) * q_c
if ang_axis_count > 0:
axis = wp.transform_vector(X_wp, joint_axis[axis_start + lin_axis_count + 0])
joint_q[q_start + lin_axis_count + 0] = quat_twist_angle(axis, q_pc)
joint_qd[qd_start + lin_axis_count + 0] = wp.dot(w_err, axis)
if ang_axis_count > 1:
axis = wp.transform_vector(X_wp, joint_axis[axis_start + lin_axis_count + 1])
joint_q[q_start + lin_axis_count + 1] = quat_twist_angle(axis, q_pc)
joint_qd[qd_start + lin_axis_count + 1] = wp.dot(w_err, axis)
if ang_axis_count > 2:
axis = wp.transform_vector(X_wp, joint_axis[axis_start + lin_axis_count + 2])
joint_q[q_start + lin_axis_count + 2] = quat_twist_angle(axis, q_pc)
joint_qd[qd_start + lin_axis_count + 2] = wp.dot(w_err, axis)
return
# given maximal coordinate model computes ik (closest point projection)
def eval_ik(model, state, joint_q, joint_qd):
wp.launch(
kernel=eval_articulation_ik,
dim=model.joint_count,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_q_start,
model.joint_qd_start,
],
outputs=[joint_q, joint_qd],
device=model.device,
)
| warp-main | warp/sim/articulation.py |
import ctypes
_c_str_dltensor = b"dltensor"
class DLDeviceType(ctypes.c_int):
"""The enum that encodes the type of the device where
DLTensor memory is allocated.
"""
kDLCPU = 1
kDLCUDA = 2
kDLCUDAHost = 3
kDLOpenCL = 4
kDLVulkan = 7
kDLMetal = 8
kDLVPI = 9
kDLROCM = 10
kDLROCMHost = 11
kDLCUDAManaged = 13
kDLOneAPI = 14
def __str__(self):
return {
self.kDLCPU: "CPU",
self.kDLCUDA: "CUDA",
self.kDLCUDAHost: "CUDAHost",
self.kDLOpenCL: "OpenCL",
self.kDLVulkan: "Vulkan",
self.kDLMetal: "Metal",
self.kDLVPI: "VPI",
self.kDLROCM: "ROCM",
self.kDLROCMHost: "ROMCHost",
self.kDLCUDAManaged: "CUDAManaged",
self.kDLOneAPI: "oneAPI",
}[self.value]
class DLDevice(ctypes.Structure):
"""Represents the device where DLTensor memory is allocated.
The device is represented by the pair of fields:
device_type: DLDeviceType
device_id: c_int
"""
_fields_ = [
("device_type", DLDeviceType),
("device_id", ctypes.c_int),
]
class DLDataTypeCode(ctypes.c_uint8):
"""An integer that encodes the category of DLTensor elements' data type."""
kDLInt = 0
kDLUInt = 1
kDLFloat = 2
kDLOpaquePointer = 3
kDLBfloat = 4
kDLComplex = 5
def __str__(self):
return {
self.kDLInt: "int",
self.kDLUInt: "uint",
self.kDLFloat: "float",
self.kDLBfloat: "bfloat",
self.kDLComplex: "complex",
self.kDLOpaquePointer: "void_p",
}[self.value]
class DLDataType(ctypes.Structure):
"""Descriptor of data type for elements of DLTensor.
The data type is described by a triple, `DLDataType.type_code`,
`DLDataType.bits`, and `DLDataType.lanes`.
The element is understood as packed `lanes` repetitions of
elements from `type_code` data-category of width `bits`.
"""
_fields_ = [
("type_code", DLDataTypeCode),
("bits", ctypes.c_uint8),
("lanes", ctypes.c_uint16),
]
TYPE_MAP = {
"bool": (DLDataTypeCode.kDLUInt, 1, 1),
"int8": (DLDataTypeCode.kDLInt, 8, 1),
"int16": (DLDataTypeCode.kDLInt, 16, 1),
"int32": (DLDataTypeCode.kDLInt, 32, 1),
"int64": (DLDataTypeCode.kDLInt, 64, 1),
"uint8": (DLDataTypeCode.kDLUInt, 8, 1),
"uint16": (DLDataTypeCode.kDLUInt, 16, 1),
"uint32": (DLDataTypeCode.kDLUInt, 32, 1),
"uint64": (DLDataTypeCode.kDLUInt, 64, 1),
"float16": (DLDataTypeCode.kDLFloat, 16, 1),
"float32": (DLDataTypeCode.kDLFloat, 32, 1),
"float64": (DLDataTypeCode.kDLFloat, 64, 1),
"complex64": (DLDataTypeCode.kDLComplex, 64, 1),
"complex128": (DLDataTypeCode.kDLComplex, 128, 1),
}
class DLTensor(ctypes.Structure):
"""Structure describing strided layout of DLTensor.
Fields are:
data: void pointer
device: DLDevice
ndim: number of indices needed to reference an
element of the tensor
dtype: data type descriptor
shape: tuple with lengths of the corresponding
tensor dimensions
strides: tuple of numbers of array elements to
step in each dimension when traversing
the tensor
byte_offset: data + byte_offset gives the address of
tensor element with index (0,) * ndim
"""
_fields_ = [
("data", ctypes.c_void_p),
("device", DLDevice),
("ndim", ctypes.c_int),
("dtype", DLDataType),
("shape", ctypes.POINTER(ctypes.c_int64)),
("strides", ctypes.POINTER(ctypes.c_int64)),
("byte_offset", ctypes.c_uint64),
]
class DLManagedTensor(ctypes.Structure):
"""Structure storing the pointer to the tensor descriptor,
deleter callable for the tensor descriptor, and pointer to
some additional data. These are stored in fields `dl_tensor`,
`deleter`, and `manager_ctx`."""
_fields_ = [
("dl_tensor", DLTensor),
("manager_ctx", ctypes.c_void_p),
("deleter", ctypes.CFUNCTYPE(None, ctypes.c_void_p)),
]
| warp-main | warp/thirdparty/dlpack.py |
warp-main | warp/thirdparty/__init__.py |
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2005-2010 ActiveState Software Inc.
# Copyright (c) 2013 Eddy Petrișor
"""Utilities for determining application-specific dirs.
See <http://github.com/ActiveState/appdirs> for details and usage.
"""
# Dev Notes:
# - MSDN on where to store app data files:
# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html
# - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
__version__ = "1.4.4"
__version_info__ = tuple(int(segment) for segment in __version__.split("."))
import sys
import os
PY3 = sys.version_info[0] == 3
if PY3:
unicode = str
if sys.platform.startswith("java"):
import platform
os_name = platform.java_ver()[3][0]
if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc.
system = "win32"
elif os_name.startswith("Mac"): # "Mac OS X", etc.
system = "darwin"
else: # "Linux", "SunOS", "FreeBSD", etc.
# Setting this to "linux2" is not ideal, but only Windows or Mac
# are actually checked for and the rest of the module expects
# *sys.platform* style strings.
system = "linux2"
else:
system = sys.platform
def user_data_dir(appname=None, appauthor=None, version=None, roaming=False):
r"""Return full path to the user-specific data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user data directories are:
Mac OS X: ~/Library/Application Support/<AppName>
Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
That means, by default "~/.local/share/<AppName>".
"""
if system == "win32":
if appauthor is None:
appauthor = appname
const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
path = os.path.normpath(_get_win_folder(const))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
elif system == "darwin":
path = os.path.expanduser("~/Library/Application Support/")
if appname:
path = os.path.join(path, appname)
else:
path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
r"""Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"multipath" is an optional parameter only applicable to *nix
which indicates that the entire list of data dirs should be
returned. By default, the first item from XDG_DATA_DIRS is
returned, or '/usr/local/share/<AppName>',
if XDG_DATA_DIRS is not set
Typical site data directories are:
Mac OS X: /Library/Application Support/<AppName>
Unix: /usr/local/share/<AppName> or /usr/share/<AppName>
Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName>
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7.
For Unix, this is using the $XDG_DATA_DIRS[0] default.
WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
"""
if system == "win32":
if appauthor is None:
appauthor = appname
path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
elif system == "darwin":
path = os.path.expanduser("/Library/Application Support")
if appname:
path = os.path.join(path, appname)
else:
# XDG default for $XDG_DATA_DIRS
# only first, if multipath is False
path = os.getenv("XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"]))
pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
if appname:
if version:
appname = os.path.join(appname, version)
pathlist = [os.sep.join([x, appname]) for x in pathlist]
if multipath:
path = os.pathsep.join(pathlist)
else:
path = pathlist[0]
return path
if appname and version:
path = os.path.join(path, version)
return path
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
r"""Return full path to the user-specific config dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user config directories are:
Mac OS X: same as user_data_dir
Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined
Win *: same as user_data_dir
For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
That means, by default "~/.config/<AppName>".
"""
if system in ["win32", "darwin"]:
path = user_data_dir(appname, appauthor, None, roaming)
else:
path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def site_config_dir(appname=None, appauthor=None, version=None, multipath=False):
r"""Return full path to the user-shared data dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"multipath" is an optional parameter only applicable to *nix
which indicates that the entire list of config dirs should be
returned. By default, the first item from XDG_CONFIG_DIRS is
returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set
Typical site config directories are:
Mac OS X: same as site_data_dir
Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in
$XDG_CONFIG_DIRS
Win *: same as site_data_dir
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False
WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
"""
if system in ["win32", "darwin"]:
path = site_data_dir(appname, appauthor)
if appname and version:
path = os.path.join(path, version)
else:
# XDG default for $XDG_CONFIG_DIRS
# only first, if multipath is False
path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg")
pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
if appname:
if version:
appname = os.path.join(appname, version)
pathlist = [os.sep.join([x, appname]) for x in pathlist]
if multipath:
path = os.pathsep.join(pathlist)
else:
path = pathlist[0]
return path
def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
r"""Return full path to the user-specific cache dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"opinion" (boolean) can be False to disable the appending of
"Cache" to the base app data dir for Windows. See
discussion below.
Typical user cache directories are:
Mac OS X: ~/Library/Caches/<AppName>
Unix: ~/.cache/<AppName> (XDG default)
Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache
On Windows the only suggestion in the MSDN docs is that local settings go in
the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming
app data dir (the default returned by `user_data_dir` above). Apps typically
put cache data somewhere *under* the given dir here. Some examples:
...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
...\Acme\SuperApp\Cache\1.0
OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
This can be disabled with the `opinion=False` option.
"""
if system == "win32":
if appauthor is None:
appauthor = appname
path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
if appname:
if appauthor is not False:
path = os.path.join(path, appauthor, appname)
else:
path = os.path.join(path, appname)
if opinion:
path = os.path.join(path, "Cache")
elif system == "darwin":
path = os.path.expanduser("~/Library/Caches")
if appname:
path = os.path.join(path, appname)
else:
path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def user_state_dir(appname=None, appauthor=None, version=None, roaming=False):
r"""Return full path to the user-specific state dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"roaming" (boolean, default False) can be set True to use the Windows
roaming appdata directory. That means that for users on a Windows
network setup for roaming profiles, this user data will be
sync'd on login. See
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
for a discussion of issues.
Typical user state directories are:
Mac OS X: same as user_data_dir
Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined
Win *: same as user_data_dir
For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>
to extend the XDG spec and support $XDG_STATE_HOME.
That means, by default "~/.local/state/<AppName>".
"""
if system in ["win32", "darwin"]:
path = user_data_dir(appname, appauthor, None, roaming)
else:
path = os.getenv("XDG_STATE_HOME", os.path.expanduser("~/.local/state"))
if appname:
path = os.path.join(path, appname)
if appname and version:
path = os.path.join(path, version)
return path
def user_log_dir(appname=None, appauthor=None, version=None, opinion=True):
r"""Return full path to the user-specific log dir for this application.
"appname" is the name of application.
If None, just the system directory is returned.
"appauthor" (only used on Windows) is the name of the
appauthor or distributing body for this application. Typically
it is the owning company name. This falls back to appname. You may
pass False to disable it.
"version" is an optional version path element to append to the
path. You might want to use this if you want multiple versions
of your app to be able to run independently. If used, this
would typically be "<major>.<minor>".
Only applied when appname is present.
"opinion" (boolean) can be False to disable the appending of
"Logs" to the base app data dir for Windows, and "log" to the
base cache dir for Unix. See discussion below.
Typical user log directories are:
Mac OS X: ~/Library/Logs/<AppName>
Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined
Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs
On Windows the only suggestion in the MSDN docs is that local settings
go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
examples of what some windows apps use for a logs dir.)
OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
value for Windows and appends "log" to the user cache dir for Unix.
This can be disabled with the `opinion=False` option.
"""
if system == "darwin":
path = os.path.join(os.path.expanduser("~/Library/Logs"), appname)
elif system == "win32":
path = user_data_dir(appname, appauthor, version)
version = False
if opinion:
path = os.path.join(path, "Logs")
else:
path = user_cache_dir(appname, appauthor, version)
version = False
if opinion:
path = os.path.join(path, "log")
if appname and version:
path = os.path.join(path, version)
return path
class AppDirs(object):
"""Convenience wrapper for getting application dirs."""
def __init__(self, appname=None, appauthor=None, version=None, roaming=False, multipath=False):
self.appname = appname
self.appauthor = appauthor
self.version = version
self.roaming = roaming
self.multipath = multipath
@property
def user_data_dir(self):
return user_data_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming)
@property
def site_data_dir(self):
return site_data_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath)
@property
def user_config_dir(self):
return user_config_dir(self.appname, self.appauthor, version=self.version, roaming=self.roaming)
@property
def site_config_dir(self):
return site_config_dir(self.appname, self.appauthor, version=self.version, multipath=self.multipath)
@property
def user_cache_dir(self):
return user_cache_dir(self.appname, self.appauthor, version=self.version)
@property
def user_state_dir(self):
return user_state_dir(self.appname, self.appauthor, version=self.version)
@property
def user_log_dir(self):
return user_log_dir(self.appname, self.appauthor, version=self.version)
# ---- internal support stuff
def _get_win_folder_from_registry(csidl_name):
"""This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
"""
if PY3:
import winreg as _winreg
else:
import _winreg
shell_folder_name = {
"CSIDL_APPDATA": "AppData",
"CSIDL_COMMON_APPDATA": "Common AppData",
"CSIDL_LOCAL_APPDATA": "Local AppData",
}[csidl_name]
key = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
dir, type = _winreg.QueryValueEx(key, shell_folder_name)
return dir
def _get_win_folder_with_pywin32(csidl_name):
from win32com.shell import shellcon, shell
dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)
# Try to make this a unicode path because SHGetFolderPath does
# not return unicode strings when there is unicode data in the
# path.
try:
dir = unicode(dir)
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in dir:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
try:
import win32api
dir = win32api.GetShortPathName(dir)
except ImportError:
pass
except UnicodeError:
pass
return dir
def _get_win_folder_with_ctypes(csidl_name):
import ctypes
csidl_const = {
"CSIDL_APPDATA": 26,
"CSIDL_COMMON_APPDATA": 35,
"CSIDL_LOCAL_APPDATA": 28,
}[csidl_name]
buf = ctypes.create_unicode_buffer(1024)
ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in buf:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
buf2 = ctypes.create_unicode_buffer(1024)
if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
buf = buf2
return buf.value
def _get_win_folder_with_jna(csidl_name):
import array
from com.sun import jna
from com.sun.jna.platform import win32
buf_size = win32.WinDef.MAX_PATH * 2
buf = array.zeros("c", buf_size)
shell = win32.Shell32.INSTANCE
shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
dir = jna.Native.toString(buf.tostring()).rstrip("\0")
# Downgrade to short path name if have highbit chars. See
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
has_high_char = False
for c in dir:
if ord(c) > 255:
has_high_char = True
break
if has_high_char:
buf = array.zeros("c", buf_size)
kernel = win32.Kernel32.INSTANCE
if kernel.GetShortPathName(dir, buf, buf_size):
dir = jna.Native.toString(buf.tostring()).rstrip("\0")
return dir
if system == "win32":
try:
import win32com.shell
_get_win_folder = _get_win_folder_with_pywin32
except ImportError:
try:
from ctypes import windll
_get_win_folder = _get_win_folder_with_ctypes
except ImportError:
try:
import com.sun.jna
_get_win_folder = _get_win_folder_with_jna
except ImportError:
_get_win_folder = _get_win_folder_from_registry
# ---- self test code
if __name__ == "__main__":
appname = "MyApp"
appauthor = "MyCompany"
props = (
"user_data_dir",
"user_config_dir",
"user_cache_dir",
"user_state_dir",
"user_log_dir",
"site_data_dir",
"site_config_dir",
)
print("-- app dirs %s --" % __version__)
print("-- app dirs (with optional 'version')")
dirs = AppDirs(appname, appauthor, version="1.0")
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
print("\n-- app dirs (without optional 'version')")
dirs = AppDirs(appname, appauthor)
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
print("\n-- app dirs (without optional 'appauthor')")
dirs = AppDirs(appname)
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
print("\n-- app dirs (with disabled 'appauthor')")
dirs = AppDirs(appname, appauthor=False)
for prop in props:
print("%s: %s" % (prop, getattr(dirs, prop)))
| warp-main | warp/thirdparty/appdirs.py |
#!/usr/bin/python3
#
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# @file converter.py
# @author Nikolaus Binder, NVIDIA
# @description Converts a matlab data file to a binary file that can be used
# with the loader in binary_file_reader.h
# Requires sio, numpy, and scipy
from array import array
import scipy.io as sio
import sys
import numpy
if len(sys.argv) < 2:
print("Usage: converter.py [file1.mat] [file2.mat] ...")
exit(1)
else:
input_files = sys.argv
input_files.pop(0)
def get_sizes(data):
lengths = []
lengths.append(len(data))
if hasattr(data[0], "__len__"):
lengths += get_sizes(data[0])
elif isinstance(data[0], complex) or isinstance(data[0], numpy.complex64):
lengths += [2]
return lengths
def print_data(m, output_file):
if hasattr(m, "__len__"):
for i in m:
print_data(i, output_file)
elif isinstance(m, complex) or isinstance(m, numpy.complex64):
array('f', [float(m.real), float(m.imag)]).tofile(output_file)
else:
array('f', [m]).tofile(output_file)
for input_filename in input_files:
output_filename = input_filename.replace('.mat', '.bin')
input_data = sio.loadmat(input_filename)
items = []
for key, item in input_data.items():
if not key.startswith("__"):
sizes = get_sizes(input_data[key])
items.append((key, sizes))
print(items)
with open(output_filename, 'wb') as output_file:
array('i', [len(items)]).tofile(output_file) # number of keys
for item in items:
key_bytes = array('b')
key_bytes.frombytes(item[0].encode())
array('i', [len(key_bytes)]).tofile(output_file)
key_bytes.tofile(output_file)
for item in items:
array('i', [len(item[1])]).tofile(output_file)
array('i', item[1]).tofile(output_file)
print_data(input_data[item[0]], output_file)
| nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/ncu/apsm/cpp/lib/binary/converter.py |
from conans import ConanFile
class ArgparseConan(ConanFile):
name = "argparse"
version = "1.0"
exports_sources = "include/argparse.hpp"
no_copy_source = True
def package(self):
self.copy("argparse.hpp") | nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/ncu/apsm/cpp/external/argparse/conanfile.py |
# BSD 3-Clause License
#
# Copyright (c) 2021, NVIDIA CORPORATION
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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 __future__ import print_function
import argparse
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
if args.dry_run:
break
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--dry-run', action='store_true', default=False,
help='quickly check a single pass')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {'batch_size': args.batch_size}
test_kwargs = {'batch_size': args.test_batch_size}
if use_cuda:
cuda_kwargs = {'num_workers': 1,
'shuffle': True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
scriptPath = os.path.dirname(os.path.realpath(__file__))
dataDir = os.path.join(scriptPath, 'data')
dataset1 = datasets.MNIST(dataDir, train=True, download=True,
transform=transform)
dataset2 = datasets.MNIST(dataDir, train=False,
transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
# Start profiling from 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStart()
train(args, model, device, train_loader, optimizer, epoch)
test(model, device, test_loader)
scheduler.step()
# Stop profiling at the end of 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStop()
if args.save_model:
torch.save(model.state_dict(), "mnist_cnn.pt")
if __name__ == '__main__':
main()
| nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/nsys/application/main_baseline.py |
# BSD 3-Clause License
#
# Copyright (c) 2021, NVIDIA CORPORATION
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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 __future__ import print_function
import argparse
import os
import multiprocessing
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.cuda import nvtx
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
with torch.autograd.profiler.emit_nvtx():
nvtx.range_push("Data loading");
for batch_idx, (data, target) in enumerate(train_loader):
nvtx.range_pop();# Data loading
nvtx.range_push("Batch " + str(batch_idx))
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop() # Copy to device
nvtx.range_push("Forward pass")
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
nvtx.range_pop() # Forward pass
nvtx.range_push("Backward pass")
loss.backward()
optimizer.step()
nvtx.range_pop() # Backward pass
nvtx.range_pop() # Batch
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
if args.dry_run:
break
nvtx.range_push("Data loading");
nvtx.range_pop(); # Data loading
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop(); # Copy to device
nvtx.range_push("Test forward pass")
output = model(data)
nvtx.range_pop() # Test forward pass
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--dry-run', action='store_true', default=False,
help='quickly check a single pass')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {'batch_size': args.batch_size}
test_kwargs = {'batch_size': args.test_batch_size}
if use_cuda:
cuda_kwargs = {'num_workers': multiprocessing.cpu_count(),
'pin_memory': True,
'shuffle': True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
scriptPath = os.path.dirname(os.path.realpath(__file__))
dataDir = os.path.join(scriptPath, 'data')
dataset1 = datasets.MNIST(dataDir, train=True, download=True,
transform=transform)
dataset2 = datasets.MNIST(dataDir, train=False,
transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
# Start profiling from 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStart()
nvtx.range_push("Epoch " + str(epoch))
nvtx.range_push("Train")
train(args, model, device, train_loader, optimizer, epoch)
nvtx.range_pop() # Train
nvtx.range_push("Test")
test(model, device, test_loader)
nvtx.range_pop() # Test
scheduler.step()
nvtx.range_pop() # Epoch
# Stop profiling at the end of 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStop()
if args.save_model:
torch.save(model.state_dict(), "mnist_cnn.pt")
if __name__ == '__main__':
main()
| nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/nsys/application/main_opt2.py |
# BSD 3-Clause License
#
# Copyright (c) 2021, NVIDIA CORPORATION
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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 __future__ import print_function
import argparse
import os
import multiprocessing
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.cuda import nvtx
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
with torch.autograd.profiler.emit_nvtx():
nvtx.range_push("Data loading");
for batch_idx, (data, target) in enumerate(train_loader):
nvtx.range_pop();# Data loading
nvtx.range_push("Batch " + str(batch_idx))
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop() # Copy to device
nvtx.range_push("Forward pass")
optimizer.zero_grad()
# Enables autocasting for the forward pass
with torch.cuda.amp.autocast(enabled=True):
output = model(data)
loss = F.nll_loss(output, target)
nvtx.range_pop() # Forward pass
nvtx.range_push("Backward pass")
loss.backward()
optimizer.step()
nvtx.range_pop() # Backward pass
nvtx.range_pop() # Batch
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
if args.dry_run:
break
nvtx.range_push("Data loading");
nvtx.range_pop(); # Data loading
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop(); # Copy to device
nvtx.range_push("Test forward pass")
output = model(data)
nvtx.range_pop() # Test forward pass
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--dry-run', action='store_true', default=False,
help='quickly check a single pass')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {'batch_size': args.batch_size}
test_kwargs = {'batch_size': args.test_batch_size}
if use_cuda:
cuda_kwargs = {'num_workers': multiprocessing.cpu_count(),
'pin_memory': True,
'shuffle': True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
scriptPath = os.path.dirname(os.path.realpath(__file__))
dataDir = os.path.join(scriptPath, 'data')
dataset1 = datasets.MNIST(dataDir, train=True, download=True,
transform=transform)
dataset2 = datasets.MNIST(dataDir, train=False,
transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
# Start profiling from 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStart()
nvtx.range_push("Epoch " + str(epoch))
nvtx.range_push("Train")
train(args, model, device, train_loader, optimizer, epoch)
nvtx.range_pop() # Train
nvtx.range_push("Test")
test(model, device, test_loader)
nvtx.range_pop() # Test
scheduler.step()
nvtx.range_pop() # Epoch
# Stop profiling at the end of 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStop()
if args.save_model:
torch.save(model.state_dict(), "mnist_cnn.pt")
if __name__ == '__main__':
main()
| nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/nsys/application/main_opt3.py |
# BSD 3-Clause License
#
# Copyright (c) 2021, NVIDIA CORPORATION
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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 __future__ import print_function
import argparse
import os
import multiprocessing
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.cuda import nvtx
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
with torch.autograd.profiler.emit_nvtx():
nvtx.range_push("Data loading");
for batch_idx, (data, target) in enumerate(train_loader):
nvtx.range_pop();# Data loading
nvtx.range_push("Batch " + str(batch_idx))
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop() # Copy to device
nvtx.range_push("Forward pass")
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
nvtx.range_pop() # Forward pass
nvtx.range_push("Backward pass")
loss.backward()
optimizer.step()
nvtx.range_pop() # Backward pass
nvtx.range_pop() # Batch
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
if args.dry_run:
break
nvtx.range_push("Data loading");
nvtx.range_pop(); # Data loading
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop(); # Copy to device
nvtx.range_push("Test forward pass")
output = model(data)
nvtx.range_pop() # Test forward pass
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--dry-run', action='store_true', default=False,
help='quickly check a single pass')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {'batch_size': args.batch_size}
test_kwargs = {'batch_size': args.test_batch_size}
if use_cuda:
cuda_kwargs = {'num_workers': multiprocessing.cpu_count(),
'shuffle': True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
scriptPath = os.path.dirname(os.path.realpath(__file__))
dataDir = os.path.join(scriptPath, 'data')
dataset1 = datasets.MNIST(dataDir, train=True, download=True,
transform=transform)
dataset2 = datasets.MNIST(dataDir, train=False,
transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
# Start profiling from 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStart()
nvtx.range_push("Epoch " + str(epoch))
nvtx.range_push("Train")
train(args, model, device, train_loader, optimizer, epoch)
nvtx.range_pop() # Train
nvtx.range_push("Test")
test(model, device, test_loader)
nvtx.range_pop() # Test
scheduler.step()
nvtx.range_pop() # Epoch
# Stop profiling at the end of 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStop()
if args.save_model:
torch.save(model.state_dict(), "mnist_cnn.pt")
if __name__ == '__main__':
main()
| nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/nsys/application/main_opt1.py |
# BSD 3-Clause License
#
# Copyright (c) 2021, NVIDIA CORPORATION
# Copyright (c) 2017,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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 __future__ import print_function
import argparse
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from torch.cuda import nvtx
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
output = F.log_softmax(x, dim=1)
return output
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
with torch.autograd.profiler.emit_nvtx():
nvtx.range_push("Data loading");
for batch_idx, (data, target) in enumerate(train_loader):
nvtx.range_pop();# Data loading
nvtx.range_push("Batch " + str(batch_idx))
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop() # Copy to device
nvtx.range_push("Forward pass")
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
nvtx.range_pop() # Forward pass
nvtx.range_push("Backward pass")
loss.backward()
optimizer.step()
nvtx.range_pop() # Backward pass
nvtx.range_pop() # Batch
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
if args.dry_run:
break
nvtx.range_push("Data loading");
nvtx.range_pop(); # Data loading
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
nvtx.range_push("Copy to device")
data, target = data.to(device), target.to(device)
nvtx.range_pop(); # Copy to device
nvtx.range_push("Test forward pass")
output = model(data)
nvtx.range_pop() # Test forward pass
test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 14)')
parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
help='learning rate (default: 1.0)')
parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
help='Learning rate step gamma (default: 0.7)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--dry-run', action='store_true', default=False,
help='quickly check a single pass')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {'batch_size': args.batch_size}
test_kwargs = {'batch_size': args.test_batch_size}
if use_cuda:
cuda_kwargs = {'num_workers': 1,
'shuffle': True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
scriptPath = os.path.dirname(os.path.realpath(__file__))
dataDir = os.path.join(scriptPath, 'data')
dataset1 = datasets.MNIST(dataDir, train=True, download=True,
transform=transform)
dataset2 = datasets.MNIST(dataDir, train=False,
transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
# Start profiling from 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStart()
nvtx.range_push("Epoch " + str(epoch))
nvtx.range_push("Train")
train(args, model, device, train_loader, optimizer, epoch)
nvtx.range_pop() # Train
nvtx.range_push("Test")
test(model, device, test_loader)
nvtx.range_pop() # Test
scheduler.step()
nvtx.range_pop() # Epoch
# Stop profiling at the end of 2nd epoch
if epoch == 2:
torch.cuda.cudart().cudaProfilerStop()
if args.save_model:
torch.save(model.state_dict(), "mnist_cnn.pt")
if __name__ == '__main__':
main()
| nsight-training-master | cuda/2021_gtc/x-ac-03-v1/task1/task/nsys/application/main_baseline_nvtx.py |
#!/usr/bin/python
import argparse
import os
import shutil
import sys
skipped_steps = [2]
class SourceFile:
def __init__(self, src, dst_name=None):
self.src = src
self.dst_name = dst_name
def copy(self, dst, step):
if not os.path.isfile(self.src):
print("Failed to find src file " + self.src)
return False
if self.dst_name == None:
dst_file = os.path.basename(self.src)
else:
dst_file = self.dst_name.replace("VAR(STEP)", str(step))
dst_loc = dst + "/" + dst_file
print("Copying " + self.src + " to " + dst_loc)
shutil.copyfile(self.src, dst_loc)
return True
class TemplateFile:
def __init__(self, src, dst):
self.src = src
self.dst = dst
self.template = []
def load(self):
if not os.path.isfile(self.src):
print("Failed to find template file " + self.src)
return False
with open(self.src) as f:
for line in f:
self.template.append(line)
return True
def write(self, path, step, platform, src_dir):
with open(path + "/" + self.dst, "w") as f:
for line in self.template:
tmp = line
tmp = tmp.replace("VAR(STEP)", step)
tmp = tmp.replace("VAR(PLATFORM)", platform)
tmp = tmp.replace("VAR(DST_DIR)", path)
tmp = tmp.replace("VAR(SRC_DIR)", "SRC_DIR=" + src_dir)
f.write(tmp)
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument("--src", help="Lab content directory")
parser.add_argument("--dst", help="Project destination directory")
parser.add_argument("--steps", help="Number of steps to generate, starting with 0")
parser.add_argument("--force", action="store_true", help="Force overwrite")
return parser.parse_args()
def main():
args = parse_command_line()
if args.src == None:
args.src = "../code"
if args.steps == None:
args.steps = 7
if not args.dst:
print("Missing --dst flag")
return 1
# create projects in workspace
src_files = [
SourceFile(os.path.abspath(args.src + "/imgserver.cu"), "imgserver_VAR(STEP).cu"),
SourceFile(os.path.abspath(args.src + "/Makefile")),
SourceFile(os.path.abspath(args.src + "/findgllib.mk")),
]
templates = [TemplateFile("project.template", ".project"), TemplateFile("cproject.template", ".cproject")]
for template in templates:
if not template.load():
print("Failed to load " + template.src)
return 1
platform = "desktop=1"
arch = "x86_64"
compute_proj_ext = "nsight-cuproj"
for step in range(0, int(args.steps) + 1):
if step in skipped_steps:
print("Skipping step " + str(step))
continue
dst_dir = args.dst + "/step_" + str(step)
print("Creating " + dst_dir)
if os.path.exists(dst_dir):
if not args.force:
print("Target directory " + dst_dir + " exists, use --force to overwrite")
return 1
shutil.rmtree(dst_dir)
os.mkdir(dst_dir)
for src_file in src_files:
src_file.copy(dst_dir, step)
for template in templates:
template.write(dst_dir, str(step), platform, os.path.abspath(args.src) + "/")
# create launch config for this project
print("Creating launch config")
launch_config = TemplateFile("launch_{0}.launch".format(arch), "launch_step_{0}.launch".format(step))
if not launch_config.load():
print("Failed to load " + launch_config)
return 1
launch_config.write(args.dst, str(step), platform, os.path.abspath(args.src) + "/")
# copy nsight systems/compute projects to workspace
perf_proj_templates = [TemplateFile("nsight_compute_" + arch + "." + compute_proj_ext, "nsight_compute." + compute_proj_ext)]
for template in perf_proj_templates:
if not template.load():
print("Failed to load " + template.src)
return 1
template.write(args.dst, str(step), platform, os.path.abspath(args.src) + "/")
# copy image resources to workspace
img_dir = args.dst + "/img"
print("Copying img dir to " + img_dir)
if os.path.exists(img_dir):
if not args.force:
print("Target directory " + img_dir + " exists, use --force to overwrite")
return 1
shutil.rmtree(img_dir)
shutil.copytree(os.path.abspath(args.src + "/../img"), img_dir)
print("done")
return 0
if __name__ == "__main__":
sys.exit(main())
| nsight-training-master | cuda/2020_gtc/projects/generate_nsightee_projects.py |
##Basic mcq
from ipywidgets import widgets, Layout, Box, GridspecLayout
def create_multipleChoice_widget(description, options, correct_answer, tip):
if correct_answer not in options:
options.append(correct_answer)
correct_answer_index = options.index(correct_answer)
radio_options = [(words, i) for i, words in enumerate(options)]
alternativ = widgets.RadioButtons(
options = radio_options,
description = '',
disabled = False,
indent = False,
align = 'center',
)
description_out = widgets.Output(layout=Layout(width='auto'))
with description_out:
print(description)
feedback_out = widgets.Output()
def check_selection(b):
a = int(alternativ.value)
if a==correct_answer_index:
s = '\x1b[6;30;42m' + "correct" + '\x1b[0m' +"\n"
else:
s = '\x1b[5;30;41m' + "try again" + '\x1b[0m' +"\n"
with feedback_out:
feedback_out.clear_output()
print(s)
return
check = widgets.Button(description="check")
check.on_click(check_selection)
tip_out = widgets.Output()
def tip_selection(b):
with tip_out:
print(tip)
with feedback_out:
feedback_out.clear_output()
print(tip)
tipbutton = widgets.Button(description="tip")
tipbutton.on_click(tip_selection)
return widgets.VBox([description_out,
alternativ,
widgets.HBox([tipbutton, check]), feedback_out],
layout=Layout(display='flex',
flex_flow='column',
align_items='stretch',
width='auto')) | nsight-training-master | grfx/2021_gtc/x-gd-01-v1/task1/lab/task/graphics/mcq.py |
#!/usr/bin/python
import ctypes
from cuda import cudart
from datetime import datetime as dt
from glob import glob
import numpy as np
import os
import sys
import tensorrt as trt
from calibrator import DecoderCalibrator
basePath = "./"
onnxFile = sorted(glob(basePath + "decoderV*.onnx"))[-1]
trtFile = basePath + "decoder.plan"
isForSubmit = True
isConvertToStaticNetwork = False
isPrintNetwork = False
additionOutput = []
useInt8 = False
calibrationDataFile = "/workspace/data/calibration.npz"
int8CacheFile = basePath + "encoder-int8.cache"
strictTypeLayer = []
useTimeCache = True
timeCacheFile = "./decoder.cache"
nTestBS = 4
nTestSL = 64
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
for soFile in glob(basePath + "*.so"):
ctypes.cdll.LoadLibrary(soFile)
timeCache = b""
if useTimeCache and os.path.isfile(timeCacheFile):
with open(timeCacheFile, 'rb') as f:
timeCache = f.read()
if timeCache == None:
print("Failed getting serialized timing cache!")
exit()
print("Succeeded getting serialized timing cache!")
if os.path.isfile(trtFile):
print("Engine existed!")
with open(trtFile, 'rb') as f:
engineString = f.read()
else:
builder = trt.Builder(logger)
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
profile = builder.create_optimization_profile()
config = builder.create_builder_config()
if useTimeCache:
cache = config.create_timing_cache(timeCache)
config.set_timing_cache(cache, False)
if isForSubmit:
config.max_workspace_size = 22 << 30
config.flags = 1 << int(trt.BuilderFlag.FP16)
config.flags = config.flags & ~(1 << int(trt.BuilderFlag.TF32))
if useInt8:
config.flags = config.flags | (1 << int(trt.BuilderFlag.INT8))
config.int8_calibrator = DecoderCalibrator(calibrationDataFile, int8CacheFile, 16, 64)
else:
config.max_workspace_size = 6 << 30
config.flags = config.flags & ~(1 << int(trt.BuilderFlag.TF32))
config.flags = config.flags | (1 << int(trt.BuilderFlag.DEBUG))
config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
if useInt8:
config.flags = config.flags | (1 << int(trt.BuilderFlag.INT8))
config.int8_calibrator = DecoderCalibrator(calibrationDataFile, int8CacheFile, 16, 64)
parser = trt.OnnxParser(network, logger)
if not os.path.exists(onnxFile):
print("Failed finding ONNX file!")
exit()
print("Succeeded finding ONNX file!")
with open(onnxFile, 'rb') as model:
if not parser.parse(model.read()):
print("Failed parsing ONNX file!")
for error in range(parser.num_errors):
print(parser.get_error(error))
exit()
print("Succeeded parsing ONNX file!")
if isForSubmit:
inputT0 = network.get_input(0)
inputT0.shape = [-1, -1, 256]
profile.set_shape(inputT0.name, (1, 16, 256), (64, 1024, 256), (64, 1024, 256))
inputT1 = network.get_input(1)
inputT1.shape = [-1]
profile.set_shape(inputT1.name, (1, ), (64, ), (64, ))
inputT2 = network.get_input(2)
#inputT2.shape = [-1,10,-1]
#profile.set_shape(inputT2.name, (1,10,32), (4,10,64), (16,10,128))
inputT2.shape = [-1, 10, 64]
profile.set_shape(inputT2.name, (1, 10, 64), (64, 10, 64), (64, 10, 64))
inputT3 = network.get_input(3)
inputT3.shape = [-1, 10]
profile.set_shape(inputT3.name, (1, 10), (64, 10), (64, 10))
inputT4 = network.get_input(4)
inputT4.shape = [-1, 10]
profile.set_shape(inputT4.name, (1, 10), (64, 10), (64, 10))
config.add_optimization_profile(profile)
else:
if isConvertToStaticNetwork:
inputT0 = network.get_input(0)
inputT0.shape = [3, 17, 256]
inputT1 = network.get_input(1)
inputT1.shape = [3]
inputT2 = network.get_input(2)
inputT2.shape = [3, 10, 64]
inputT3 = network.get_input(3)
inputT3.shape = [3, 10]
inputT4 = network.get_input(4)
inputT4.shape = [3, 10]
else:
inputT0 = network.get_input(0)
inputT0.shape = [-1, -1, 256]
profile.set_shape(inputT0.name, (1, 16, 256), (4, 64, 256), (4, 64, 256))
inputT1 = network.get_input(1)
inputT1.shape = [-1]
profile.set_shape(inputT1.name, (1, ), (4, ), (4, ))
inputT2 = network.get_input(2)
inputT2.shape = [-1, 10, 64]
profile.set_shape(inputT2.name, (1, 10, 64), (4, 10, 64), (4, 10, 64))
inputT3 = network.get_input(3)
inputT3.shape = [-1, 10]
profile.set_shape(inputT3.name, (1, 10), (4, 10), (4, 10))
inputT4 = network.get_input(4)
inputT4.shape = [-1, 10]
profile.set_shape(inputT4.name, (1, 10), (4, 10), (4, 10))
config.add_optimization_profile(profile)
if isPrintNetwork:
for i in range(network.num_layers):
layer = network.get_layer(i)
print(i, "%s,in=%d,out=%d,%s" % (str(layer.type)[10:], layer.num_inputs, layer.num_outputs, layer.name))
for j in range(layer.num_inputs):
tensor = layer.get_input(j)
if tensor == None:
print("\tInput %2d:" % j, "None")
else:
print("\tInput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name))
for j in range(layer.num_outputs):
tensor = layer.get_output(j)
if tensor == None:
print("\tOutput %2d:" % j, "None")
else:
print("\tOutput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name))
exit()
if len(strictTypeLayer) > 0:
for index in strictTypeLayer:
layer = network.get_layer(i)
layer.precision = trt.float32
layer.get_output(0).dtype = trt.float32
if len(additionOutput) > 0:
for index in additionOutput:
network.mark_output(network.get_layer(index).get_output(0))
#network.mark_output(network.get_layer(index).get_input(0))
engineString = builder.build_serialized_network(network, config)
if engineString == None:
print("Failed building engine!")
exit()
if useTimeCache and not os.path.isfile(timeCacheFile):
timeCache = config.get_timing_cache()
timeCacheString = timeCache.serialize()
with open(timeCacheFile, 'wb') as f:
f.write(timeCacheString)
print("Succeeded saving .cache file!")
print("Succeeded building engine!")
with open(trtFile, 'wb') as f:
f.write(engineString)
'''
engine = trt.Runtime(logger).deserialize_cuda_engine(engineString)
context = engine.create_execution_context()
context.set_binding_shape(0, [nTestBS,nTestSL,256])
context.set_binding_shape(1, [nTestBS])
context.set_binding_shape(2, [nTestBS,10,64])
context.set_binding_shape(3, [nTestBS,10])
context.set_binding_shape(4, [nTestBS,10])
nInput = np.sum([engine.binding_is_input(i) for i in range(engine.num_bindings)])
nOutput = engine.num_bindings - nInput
for i in range(nInput):
print("Bind[%2d]:i[%2d]->" % (i, i), engine.get_binding_dtype(i), engine.get_binding_shape(i), context.get_binding_shape(i), engine.get_binding_name(i))
for i in range(nInput,nInput+nOutput):
print("Bind[%2d]:o[%2d]->" % (i, i - nInput), engine.get_binding_dtype(i), engine.get_binding_shape(i), context.get_binding_shape(i), engine.get_binding_name(i))
dd = np.load("/workspace/data/decoder-%d-%d.npz"%(nTestBS,nTestSL))
bufferH = []
bufferH.append(np.ascontiguousarray(dd['encoder_out'][:nTestBS,:nTestSL].reshape(-1)))
bufferH.append(np.ascontiguousarray(dd['encoder_out_lens'][:nTestBS].reshape(-1)))
#bufferH.append(np.ascontiguousarray(np.array([2,3,4],dtype=np.int32).reshape(-1)))
bufferH.append(np.ascontiguousarray(dd['hyps_pad_sos_eos'][:nTestBS].reshape(-1)))
bufferH.append(np.ascontiguousarray(dd['hyps_lens_sos'][:nTestBS].reshape(-1)))
bufferH.append(np.ascontiguousarray(dd['ctc_score'][:nTestBS].reshape(-1)))
for i in range(nInput, nInput + nOutput):
bufferH.append(np.empty(context.get_binding_shape(i), dtype=trt.nptype(engine.get_binding_dtype(i))))
bufferD = []
for i in range(nInput + nOutput):
bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1])
for i in range(nInput):
cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
context.execute_v2(bufferD)
for i in range(nInput, nInput + nOutput):
cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost)
out={}
for i in range(nInput + nOutput):
print(engine.get_binding_name(i))
print(bufferH[i].reshape(context.get_binding_shape(i)))
out[str(i)] = bufferH[i]
np.savez('decoderOut.npz',**out)
for b in bufferD:
cudart.cudaFree(b)
print("Finished building Decoder engine!")
'''
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/decoder.py |
from collections import OrderedDict
from copy import deepcopy
import numpy as np
import onnx
import onnx_graphsurgeon as gs
onnxFilePath = "/workspace/"
#onnxFilePath = "./" # local host
sourceOnnx = "./decoderV2.onnx"
destinationOnnx = "./decoderV3.onnx"
bConvertToStaticNetwork = False
bDebug = False
nWili = 0
bNot = False
nNot = 0
bLayerNormPlugin = True
nLayerNormPlugin = 0
bShapeOperation = True
nShapeOperation = 0
b2DMM = True
n2DMM = 0
#graph = gs.import_onnx(onnx.load(sourceOnnx))
graph = gs.import_onnx(onnx.shape_inference.infer_shapes(onnx.load(sourceOnnx)))
if bConvertToStaticNetwork:
graph.inputs[0].shape = [3, 17, 256]
graph.inputs[1].shape = [3]
graph.inputs[2].shape = [3, 10, 64]
graph.inputs[3].shape = [3, 10]
graph.inputs[4].shape = [3, 10]
else:
graph.inputs[0].shape = ['B', 'T', 256]
graph.inputs[1].shape = ['B']
graph.inputs[2].shape = ['B', 10, 64]
#graph.inputs[2].shape = ['B',10,'T2']
# Round 0: ceate useful constant tensor or collect useful shape tensor
wiliConstant0 = gs.Constant("wiliConstant0", np.ascontiguousarray(np.array([0], dtype=np.int64))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
wiliConstant1 = gs.Constant("wiliConstant1", np.ascontiguousarray(np.array([1], dtype=np.int64)))
wiliConstant10 = gs.Constant("wiliConstant10", np.ascontiguousarray(np.array([10], dtype=np.int64)))
wiliConstant63 = gs.Constant("wiliConstant63", np.ascontiguousarray(np.array([63], dtype=np.int64)))
wiliConstant64 = gs.Constant("wiliConstant64", np.ascontiguousarray(np.array([64], dtype=np.int64)))
wiliConstant256 = gs.Constant("wiliConstant256", np.ascontiguousarray(np.array([256], dtype=np.int64)))
wiliConstant4233 = gs.Constant("wiliConstant4233", np.ascontiguousarray(np.array([4233], dtype=np.int64)))
wiliConstantS0 = gs.Constant("wiliConstantS0", np.array(0, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(0, dtype=np.dtype(np.int64)))
wiliConstantS1 = gs.Constant("wiliConstantS1", np.array(1, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(1, dtype=np.dtype(np.int64)))
wiliConstantS63 = gs.Constant("wiliConstantS63", np.array(63, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(63, dtype=np.dtype(np.int64)))
wiliConstantRange63 = gs.Constant("wiliConstantRange63", np.ascontiguousarray(np.arange(63, dtype=np.int64).reshape(1, 63)))
data = np.ones([1, 63, 63], dtype=np.int32)
for i in range(63):
data[0, i, :(i + 1)] = 0
wiliConstant1x63x63 = gs.Constant("wiliConstant1x63x63", np.ascontiguousarray(data.astype(bool)))
wiliShapeV = gs.Variable("wiliShapeV-" + str(nWili), np.dtype(np.int64), [3])
wiliShapeN = gs.Node("Shape", "wiliShapeN-" + str(nWili), inputs=[graph.inputs[0]], outputs=[wiliShapeV])
graph.nodes.append(wiliShapeN)
nWili += 1
# shape = [], value = ['B']
bTensorScalar = gs.Variable("bTensorScalar", np.dtype(np.int64), [])
wiliGatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[wiliShapeV, wiliConstantS0], outputs=[bTensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliGatherN)
nWili += 1
# shape = [1,], value = ['B']
bTensor = gs.Variable("bTensor", np.dtype(np.int64), [1])
wiliUnsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[bTensorScalar, wiliConstant0], outputs=[bTensor])
graph.nodes.append(wiliUnsqueezeN)
nWili += 1
# shape = [], value = ['T']
tTensorScalar = gs.Variable("tTensorScalar", np.dtype(np.int64), [])
wiliGatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[wiliShapeV, wiliConstantS1], outputs=[tTensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliGatherN)
nWili += 1
# shape = [1,], value = ['T']
tTensor = gs.Variable("tTensor", np.dtype(np.int64), [1])
wiliUnsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[tTensorScalar, wiliConstant0], outputs=[tTensor])
graph.nodes.append(wiliUnsqueezeN)
nWili += 1
# shape = [2,], value = ['B','T']
bCommaTTensor = gs.Variable("bCommaTTensor", np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, tTensor], outputs=[bCommaTTensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [1,], value = ['B'* 10]
b10Tensor = gs.Variable("b10Tensor", np.dtype(np.int64), [1])
wiliMulN = gs.Node("Mul", "wiliMulN-" + str(nWili), inputs=[bTensor, wiliConstant10], outputs=[b10Tensor])
graph.nodes.append(wiliMulN)
nWili += 1
# shape = [3,], value = ['B'*10,'T',256]
b10CommaTComma256Tensor = gs.Variable("b10CommaTComma256Tensor", np.dtype(np.int64), [3])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[b10Tensor, tTensor, wiliConstant256], outputs=[b10CommaTComma256Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [2,], value = ['B',10]
bComma10Tensor = gs.Variable("bComma10Tensor", np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, wiliConstant10], outputs=[bComma10Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [2,], value = ['B'*10,63]
b10Comma63Tensor = gs.Variable("b10Comma63Tensor", np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[b10Tensor, wiliConstant63], outputs=[b10Comma63Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [2,], value = ['B'*10,64]
b10Comma64Tensor = gs.Variable("b10Comma64Tensor", np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[b10Tensor, wiliConstant64], outputs=[b10Comma64Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [1,], value = ['B'*10*63]
b1063Tensor = gs.Variable("b1063Tensor", np.dtype(np.int64), [1])
wiliMulN = gs.Node("Mul", "wiliMulN-" + str(nWili), inputs=[b10Tensor, wiliConstant63], outputs=[b1063Tensor])
graph.nodes.append(wiliMulN)
nWili += 1
# shape = [4,], value = ['B'*10,1,1,'T']
b10Comma1Comma1CommaTTensor = gs.Variable("b10Comma1Comma1CommaTTensor", np.dtype(np.int64), [4])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[b10Tensor, wiliConstant1, wiliConstant1, tTensor], outputs=[b10Comma1Comma1CommaTTensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [4,], value = ['B',10,63,4233]
bComma10Comma63Comma4233Tensor = gs.Variable("bComma10Comma63Comma4233Tensor", np.dtype(np.int64), [4])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, wiliConstant10, wiliConstant63, wiliConstant4233], outputs=[bComma10Comma63Comma4233Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [2,], value = ['B'*10*63,256]
b1063Comma256Tensor = gs.Variable("b1063Comma256Tensor", np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[b1063Tensor, wiliConstant256], outputs=[b1063Comma256Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [3,], value = ['B'*10,63,256]
b10Comma63Comma256Tensor = gs.Variable("b10Comma63Comma256Tensor", np.dtype(np.int64), [3])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[b10Tensor, wiliConstant63, wiliConstant256], outputs=[b10Comma63Comma256Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# Round 1: Not
if bNot:
for node in graph.nodes:
if "Not" in node.name:
castV = gs.Variable("castV-" + str(5000 + nNot), np.dtype(bool), None)
castN = gs.Node("Cast", "CastN-" + str(6000 + nNot), inputs=[node.inputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.BOOL)]))
graph.nodes.append(castN)
nNot += 1
node.inputs = [castV]
continue
# Round 2: Layer Normalization
if bLayerNormPlugin:
for node in graph.nodes:
if node.op == 'ReduceMean' and \
node.o().op == 'Sub' and node.o().inputs[0] == node.inputs[0] and \
node.o().o(0).op =='Pow' and node.o().o(1).op =='Div' and \
node.o().o(0).o().op == 'ReduceMean' and \
node.o().o(0).o().o().op == 'Add' and \
node.o().o(0).o().o().o().op == 'Sqrt' and \
node.o().o(0).o().o().o().o().op == 'Div' and node.o().o(0).o().o().o().o() == node.o().o(1) and \
node.o().o(0).o().o().o().o().o().op == 'Mul' and \
node.o().o(0).o().o().o().o().o().o().op == 'Add':
inputTensor = node.inputs[0]
lastMultipyNode = node.o().o(0).o().o().o().o().o()
index = ['weight' in i.name for i in lastMultipyNode.inputs].index(True)
b = np.array(deepcopy(lastMultipyNode.inputs[index].values.tolist()), dtype=np.float32)
constantB = gs.Constant("LayerNormB-" + str(nLayerNormPlugin), np.ascontiguousarray(b.reshape(-1))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
lastAddNode = node.o().o(0).o().o().o().o().o().o()
index = ['bias' in i.name for i in lastAddNode.inputs].index(True)
a = np.array(deepcopy(lastAddNode.inputs[index].values.tolist()), dtype=np.float32)
constantA = gs.Constant("LayerNormA-" + str(nLayerNormPlugin), np.ascontiguousarray(a.reshape(-1)))
inputList = [inputTensor, constantB, constantA]
layerNormV = gs.Variable("LayerNormV-" + str(nLayerNormPlugin), np.dtype(np.float32), None)
layerNormN = gs.Node("LayerNorm", "LayerNormN-" + str(nLayerNormPlugin), inputs=inputList, outputs=[layerNormV])
graph.nodes.append(layerNormN)
nLayerNormPlugin += 1
for n in graph.nodes:
if lastAddNode.outputs[0] in n.inputs:
index = n.inputs.index(lastAddNode.outputs[0])
n.inputs[index] = layerNormN.outputs[0]
lastAddNode.outputs = []
continue
# Round 3: Shape operation
if bShapeOperation:
for node in graph.nodes:
if node.op == 'Expand' and node.name == 'Expand_111':
node.inputs[0] = wiliConstantRange63
node.inputs[1] = b10Comma63Tensor
nShapeOperation += 2
if node.op == 'And' and node.name == 'And_152':
node.op = 'Or'
node.name = 'wiliOr-' + str(nShapeOperation)
nShapeOperation += 1
node.inputs[0] = node.i().i().i().i().outputs[0] # Remove Not
node.inputs[1] = wiliConstant1x63x63
outTensor = node.o().outputs[0]
node.o().outputs = []
unsqueezeV = gs.Variable("wiliUnsqueezeV-" + str(nShapeOperation), np.dtype(bool), None)
unsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nShapeOperation), inputs=[node.outputs[0], wiliConstant1], outputs=[outTensor])
graph.nodes.append(unsqueezeN)
nShapeOperation += 1
for node in graph.nodes:
if node.op == "Softmax" and node.name in ['Softmax_217', 'Softmax_358', 'Softmax_499', 'Softmax_640', 'Softmax_781', 'Softmax_922']:
node.i().inputs[0] = outTensor
node.o().inputs[0] = outTensor
nShapeOperation += 2
continue
if node.op == "Not" and node.name == "Not_1064":
for oldNode in graph.nodes:
if oldNode.op == "GreaterOrEqual" and oldNode.name == "GreaterOrEqual_115":
node.inputs[0] = oldNode.outputs[0]
if node.op == 'Expand' and node.name == 'Expand_43':
node.inputs[1] = bCommaTTensor
nShapeOperation += 1
if node.op == 'Reshape' and node.name == 'Reshape_60':
node.i().inputs[0] = node.i().i().i().inputs[0] # Remove Not and Expand
node.inputs[1] = b10Comma1Comma1CommaTTensor
outTensor = node.outputs[0]
for node in graph.nodes:
if node.op == "Softmax" and node.name in ['Softmax_279', 'Softmax_420', 'Softmax_561', 'Softmax_702', 'Softmax_843', 'Softmax_984']:
node.i().inputs[0] = outTensor
node.o().inputs[0] = outTensor
nShapeOperation += 2
continue
if node.op == 'Reshape' and node.name == 'Reshape_1087':
node.inputs[1] = bComma10Tensor
if node.op == 'Reshape' and node.name == 'Reshape_73':
node.inputs[1] = b10Comma64Tensor
if node.op == 'Reshape' and node.name == 'Reshape_77':
node.inputs[1] = b10Tensor
if node.op == 'Range' and node.name == 'Range_27':
node.inputs[1] = tTensorScalar
if node.op == 'Gather' and node.name == 'Gather_154':
value = node.inputs[0].values
wiliConstantGather154 = gs.Constant("wiliConstantGather154", np.ascontiguousarray(value * 16))
node.inputs[0] = wiliConstantGather154
node.o(1).o().inputs[0] = node.outputs[0]
if node.op == 'Slice' and node.name == 'Slice_164':
node.inputs[2] = wiliConstant63
if node.op == 'Reshape' and node.name == 'Reshape_1038':
node.o().inputs[0] = node.inputs[0]
node.inputs[1] = bComma10Comma63Comma4233Tensor
graph.outputs[0].name = 'deprecated[decoder_out]'
node.outputs[0].name = 'decoder_out'
graph.outputs[0] = node.outputs[0]
if node.op == 'Reshape' and node.name == 'Reshape_22':
node.i().inputs[0] = graph.inputs[0]
node.inputs[1] = b10CommaTComma256Tensor
'''
# Error operation but keep output correct!
if node.op == 'ArgMax' and node.name == 'ArgMax_1091':
node.inputs[0] = node.i().inputs[0]
'''
# Round 4: 2D Matrix multiplication
if b2DMM:
for node in graph.nodes:
if node.op == 'LayerNorm' and node.name in ['LayerNormN-' + str(i) for i in range(2, 18, 3)]:
reshape1V = gs.Variable("wiliReshape1V-" + str(n2DMM), np.dtype(np.float32), ['B*10*63', 256])
reshape1N = gs.Node("Reshape", "wiliReshape1N-" + str(n2DMM), inputs=[node.outputs[0], b1063Comma256Tensor], outputs=[reshape1V])
graph.nodes.append(reshape1N)
n2DMM += 1
lastNode = node.o().o().o().o().o() # Add
outputTensor = lastNode.outputs[0]
reshape2V = gs.Variable("wiliReshape2V-" + str(n2DMM), np.dtype(np.float32), ['B*10', 63, 256])
reshape2N = gs.Node("Reshape", "wiliReshape2N-" + str(n2DMM), inputs=[reshape2V, b10Comma63Comma256Tensor], outputs=[outputTensor])
graph.nodes.append(reshape2N)
n2DMM += 1
lastNode.outputs[0] = reshape2V
node.o().inputs[0] = reshape1V
# for debug
if bDebug:
for node in graph.nodes:
if node.name == "LayerNormN-2":
#graph.outputs.append( node.inputs[0] )
graph.outputs.append(node.outputs[0])
#graph.outputs = [node.outputs[0]]
graph.cleanup()
onnx.save(gs.export_onnx(graph), destinationOnnx)
print("finish decoder onnx-graphsurgeon!")
print("%4d Not" % (nNot))
print("%4d LayerNormPlugin" % nLayerNormPlugin)
print("%4d ShapeOperation" % nShapeOperation)
print("%4d 2DMM" % n2DMM)
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/decoder-surgeonV3.py |
from collections import OrderedDict
from copy import deepcopy
import numpy as np
import onnx
import onnx_graphsurgeon as gs
sourceOnnx = "./encoderV2.onnx"
destinationOnnx = "./encoderV3.onnx"
bConvertToStaticNetwork = False
debugNodeList = []
nWili = 0
bSimplifyOutput = True
bNotV3 = True
nNotV3 = 0
bLayerNormPlugin = True
nLayerNormPlugin = 0
bConstantFold = True
nConstantFold = 0
bReshapeMatmulToConv = True
nReshapeMatmulToConv = 0
bExpand = True
nExpand = 0
b2DMM = True
n2DMM = 0
bAttentionMM = False
nAttentionMM = 0
bAttentionPlugin = True
nAttentionPlugin = 0
#graph = gs.import_onnx(onnx.load(sourceOnnx))
graph = gs.import_onnx(onnx.shape_inference.infer_shapes(onnx.load(sourceOnnx)))
if bConvertToStaticNetwork:
graph.inputs[0].shape = [3, 17, 256]
graph.inputs[1].shape = [3]
else:
graph.inputs[0].shape = ['B', 'T', 80]
graph.inputs[1].shape = ['B']
# Round 0: ceate useful constant tensor or collect useful shape tensor
wiliConstant0 = gs.Constant("wiliConstant0", np.ascontiguousarray(np.array([0], dtype=np.int64))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
wiliConstant1 = gs.Constant("wiliConstant1", np.ascontiguousarray(np.array([1], dtype=np.int64)))
wiliConstant3 = gs.Constant("wiliConstant3", np.ascontiguousarray(np.array([3], dtype=np.int64)))
wiliConstant4 = gs.Constant("wiliConstant4", np.ascontiguousarray(np.array([4], dtype=np.int64)))
wiliConstantM4 = gs.Constant("wiliConstantM4", np.ascontiguousarray(np.array([-4], dtype=np.int64))) # minus four
wiliConstant64 = gs.Constant("wiliConstant64", np.ascontiguousarray(np.array([64], dtype=np.int64)))
wiliConstant256 = gs.Constant("wiliConstant256", np.ascontiguousarray(np.array([256], dtype=np.int64)))
wiliConstantS0 = gs.Constant("wiliConstantS0", np.array(0, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(0, dtype=np.dtype(np.int64)))
wiliConstantS1 = gs.Constant("wiliConstantS1", np.array(1, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(1, dtype=np.dtype(np.int64)))
wiliConstantS2 = gs.Constant("wiliConstantS2", np.array(2, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(2, dtype=np.dtype(np.int64)))
wiliShapeV = gs.Variable("wiliShapeV-" + str(nWili), np.dtype(np.int64), [3])
wiliShapeN = gs.Node("Shape", "wiliShapeN-" + str(nWili), inputs=[graph.inputs[0]], outputs=[wiliShapeV])
graph.nodes.append(wiliShapeN)
nWili += 1
# shape = [], value = ['B']
bTensorScalar = gs.Variable("bTensorScalar", np.dtype(np.int64), [])
wiliGatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[wiliShapeV, wiliConstantS0], outputs=[bTensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliGatherN)
nWili += 1
# shape = [1,], value = ['B']
bTensor = gs.Variable("bTensor", np.dtype(np.int64), [1])
wiliUnsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[bTensorScalar, wiliConstant0], outputs=[bTensor])
graph.nodes.append(wiliUnsqueezeN)
nWili += 1
# shape = [], value = ['T']
tTensorScalar = gs.Variable("tTensorScalar", np.dtype(np.int64), [])
wiliGatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[wiliShapeV, wiliConstantS1], outputs=[tTensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliGatherN)
nWili += 1
# shape = [1,], value = ['T']
tTensor = gs.Variable("tTensor", np.dtype(np.int64), [1])
wiliUnsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[tTensorScalar, wiliConstant0], outputs=[tTensor])
graph.nodes.append(wiliUnsqueezeN)
nWili += 1
# shape = [1,], value = ['t4'], t4 = floor('T'/4) - 1
for node in graph.nodes:
if node.op == 'Relu' and node.name == 'Relu_38':
shapeV = gs.Variable("wiliShapeV-" + str(nWili), np.dtype(np.int64), [4])
shapeN = gs.Node("Shape", "wiliShapeN-" + str(nWili), inputs=[node.outputs[0]], outputs=[shapeV])
graph.nodes.append(shapeN)
nWili += 1
t4TensorScalar = gs.Variable("t4TensorScalar", np.dtype(np.int64), [])
gatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[shapeV, wiliConstantS2], outputs=[t4TensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(gatherN)
nWili += 1
t4Tensor = gs.Variable("t4Tensor", np.dtype(np.int64), [1])
unsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[t4TensorScalar, wiliConstant0], outputs=[t4Tensor])
graph.nodes.append(unsqueezeN)
nWili += 1
# shape = [1,], value = ['B'*'t4']
bt4Tensor = gs.Variable("bt4Tensor-" + str(nWili), np.dtype(np.int64), [1])
wiliMulN = gs.Node("Mul", "wiliMulN-" + str(nWili), inputs=[bTensor, t4Tensor], outputs=[bt4Tensor])
graph.nodes.append(wiliMulN)
nWili += 1
# shape = [2,], value = ['B'*'t4',256]
bt4Comma256Tensor = gs.Variable("bt4Comma256Tensor-" + str(nWili), np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bt4Tensor, wiliConstant256], outputs=[bt4Comma256Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [3,], value = ['B','t4',256]
bCommat4Comma64Tensor = gs.Variable("bCommat4Comma64Tensor-" + str(nWili), np.dtype(np.int64), [3])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, t4Tensor, wiliConstant256], outputs=[bCommat4Comma64Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [4,], value = ['B','t4',4,64]
bCommat4Comma4Comma64Tensor = gs.Variable("bCommat4Comma4Comma64Tensor-" + str(nWili), np.dtype(np.int64), [4])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, t4Tensor, wiliConstant4, wiliConstant64], outputs=[bCommat4Comma4Comma64Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# Round 0.5: output tensor
if bSimplifyOutput:
for node in graph.nodes:
graph.outputs[0].name = 'deprecated[encoder_out]'
graph.outputs[1].name = 'deprecated[encoder_out_lens]'
graph.outputs = graph.outputs[:2]
wiliAddV0 = gs.Variable("wiliAddV-0", np.dtype(np.int32), ['B'])
wiliAddN0 = gs.Node("Add", "wiliAddN-0", inputs=[graph.inputs[1], wiliConstant3], outputs=[wiliAddV0])
graph.nodes.append(wiliAddN0)
wiliDivV0 = gs.Variable("wiliDevV-0", np.dtype(np.int32), ['B'])
wiliDivN0 = gs.Node("Div", "wiliDivN-0", inputs=[wiliAddV0, wiliConstant4], outputs=[wiliDivV0])
graph.nodes.append(wiliDivN0)
wiliMinV0 = gs.Variable("encoder_out_lens", np.dtype(np.int32), ['B'])
wiliMinN0 = gs.Node("Min", "wiliMinN-0", inputs=[wiliDivV0, t4Tensor], outputs=[wiliMinV0])
graph.nodes.append(wiliMinN0)
graph.outputs[1] = wiliMinV0
# Round 1: Not version 3, adjust Not to fit Attention Plugin
if bNotV3:
for node in graph.nodes:
if node.op == 'Slice' and node.name == 'Slice_79':
# adjust node before Slice_79
greaterOrEqualNode = node.i().i().i()
greaterOrEqualNode.op = 'Less'
greaterOrEqualNode.name = 'LessN-' + str(nNotV3)
nNotV3 += 1
castV = gs.Variable("wiliCastV-" + str(nNotV3), np.dtype(np.int32), None)
castN = gs.Node("Cast", "wiliCastN-" + str(nNotV3), inputs=[greaterOrEqualNode.outputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.INT32)]))
graph.nodes.append(castN)
nNotV3 += 1
# adjust Slice_79
node.inputs[0] = castV
node.inputs[2] = wiliConstantM4 # end
node.inputs[3] = wiliConstant1 # axes
node.inputs[4] = wiliConstant4 # step
slice84Node = node.o()
tensor613 = slice84Node.outputs[0]
tensor613.dtype = np.dtype(np.int32)
unsqueezeTo3DN = gs.Node("Unsqueeze", "wiliUnsqueezeTo3DN-" + str(nNotV3), inputs=[node.outputs[0], wiliConstant1], outputs=[tensor613])
graph.nodes.append(unsqueezeTo3DN)
nNotV3 += 1
slice84Node.outputs = []
continue
if node.op == 'Not' and node.name != 'Not_30':
castV = gs.Variable("castV-" + str(nNotV3), np.dtype(bool), None)
castN = gs.Node("Cast", "CastN-" + str(nNotV3), inputs=[node.inputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.BOOL)]))
graph.nodes.append(castN)
nNotV3 += 1
node.inputs = [castV]
continue
# Round 2: Layer Normalization
if bLayerNormPlugin:
for node in graph.nodes:
if node.op == 'ReduceMean' and \
node.o().op == 'Sub' and node.o().inputs[0] == node.inputs[0] and \
node.o().o(0).op =='Pow' and node.o().o(1).op =='Div' and \
node.o().o(0).o().op == 'ReduceMean' and \
node.o().o(0).o().o().op == 'Add' and \
node.o().o(0).o().o().o().op == 'Sqrt' and \
node.o().o(0).o().o().o().o().op == 'Div' and node.o().o(0).o().o().o().o() == node.o().o(1) and \
node.o().o(0).o().o().o().o().o().op == 'Mul' and \
node.o().o(0).o().o().o().o().o().o().op == 'Add':
inputTensor = node.inputs[0]
lastMultipyNode = node.o().o(0).o().o().o().o().o()
index = ['weight' in i.name for i in lastMultipyNode.inputs].index(True)
b = np.array(deepcopy(lastMultipyNode.inputs[index].values.tolist()), dtype=np.float32)
constantB = gs.Constant("LayerNormB-" + str(nLayerNormPlugin), np.ascontiguousarray(b.reshape(-1))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
lastAddNode = node.o().o(0).o().o().o().o().o().o()
index = ['bias' in i.name for i in lastAddNode.inputs].index(True)
a = np.array(deepcopy(lastAddNode.inputs[index].values.tolist()), dtype=np.float32)
constantA = gs.Constant("LayerNormA-" + str(nLayerNormPlugin), np.ascontiguousarray(a.reshape(-1)))
inputList = [inputTensor, constantB, constantA]
layerNormV = gs.Variable("LayerNormV-" + str(nLayerNormPlugin), np.dtype(np.float32), None)
layerNormN = gs.Node("LayerNorm", "LayerNormN-" + str(nLayerNormPlugin), inputs=inputList, outputs=[layerNormV])
graph.nodes.append(layerNormN)
if lastAddNode.outputs[0] in graph.outputs: # the last LayerNorm provide one of the graph's output, and do not unsqueeze to 4 dimension
# oldLastAdd -> graph.outputs[0] ===> LayerNorm -> Squeeze -> graph.outputs[0]
layerNormN.outputs[0].name = 'encoder_out'
index = graph.outputs.index(lastAddNode.outputs[0])
graph.outputs[index] = layerNormN.outputs[0]
else: # other LayerNorm contain the subsequent Squeeze operation
for n in graph.nodes:
if lastAddNode.outputs[0] in n.inputs:
index = n.inputs.index(lastAddNode.outputs[0])
n.inputs[index] = layerNormN.outputs[0]
lastAddNode.outputs = []
nLayerNormPlugin += 1
continue
# Round 3: constant fold, removed for adopting Attention plugin
if bConstantFold:
for node in graph.nodes:
if node.op == 'Slice' and node.name == 'Slice_74':
node.inputs[0].values = node.inputs[0].values[:, :256, :]
nConstantFold += 1
break
# Round 4: Reshape + Matmul -> Convolution, by Hongwei
if bReshapeMatmulToConv:
for node in graph.nodes:
if node.op == "Relu" and node.name == 'Relu_38':
matmulNode = node.o(2).o().o()
addNode = matmulNode.o()
mulNode = addNode.o()
convKernel = matmulNode.inputs[1].values.transpose(1, 0).reshape(256, 256, 1, 19).astype(np.float32)
convKernelV = gs.Constant("wiliConvKernelV-" + str(nReshapeMatmulToConv), np.ascontiguousarray(convKernel))
nReshapeMatmulToConv += 1
convBias = addNode.inputs[0].values
convBiasV = gs.Constant("wiliConvBiasV-" + str(nReshapeMatmulToConv), np.ascontiguousarray(convBias))
nReshapeMatmulToConv += 1
convV = gs.Variable("wiliConvV-" + str(nReshapeMatmulToConv), np.dtype(np.float32), ['B', 256, 't4', 1])
convN = gs.Node("Conv", "wiliConvN-" + str(nReshapeMatmulToConv), inputs=[node.outputs[0], convKernelV, convBiasV], outputs=[convV])
convN.attrs = OrderedDict([
('dilations', [1, 1]),
('kernel_shape', [1, 19]),
('pads', [0, 0, 0, 0]),
('strides', [1, 1]),
])
graph.nodes.append(convN)
nReshapeMatmulToConv += 1
squeezeV = gs.Variable("wiliSqueezeV-" + str(nReshapeMatmulToConv), np.dtype(np.float32), ['B', 256, 't4'])
squeezeN = gs.Node("Squeeze", "wiliSqueezeN-" + str(nReshapeMatmulToConv), inputs=[convV, wiliConstant3], outputs=[squeezeV])
graph.nodes.append(squeezeN)
nReshapeMatmulToConv += 1
transposeV = gs.Variable("wiliTransposeV-" + str(nReshapeMatmulToConv), np.dtype(np.float32), ['B', 't4', 256])
transposeN = gs.Node("Transpose", "wiliTransposeN-" + str(nReshapeMatmulToConv), inputs=[squeezeV], outputs=[transposeV], attrs=OrderedDict([('perm', [0, 2, 1])]))
graph.nodes.append(transposeN)
nReshapeMatmulToConv += 1
mulNode.inputs[0] = transposeV
# Round 5: Expand_23
if bExpand:
for node in graph.nodes:
if node.op == 'Expand' and node.name == 'Expand_23':
node.i().i().inputs[1] = tTensorScalar
concatV = gs.Variable("wiliConcatV-" + str(nExpand), np.dtype(np.int64), [2])
concatN = gs.Node("Concat", "wiliConcatN-" + str(nExpand), inputs=[bTensor, tTensor], outputs=[concatV], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(concatN)
nExpand += 1
node.inputs[1] = concatV
# Round 6: 2D Matrix multiplication
if b2DMM:
for node in graph.nodes:
if node.op == 'MatMul' and node.name != 'MatMul_61' and \
node.o().op == 'Add' and \
node.o().o().op == 'Sigmoid' and \
node.o().o().o().op == 'Mul' and \
node.o().o().o().o().op == 'MatMul' and \
node.o().o().o().o().o().op == 'Add' and \
node.o().o().o().o().o().o().op == 'Mul':
reshape1V = gs.Variable("wiliReshape1V-" + str(n2DMM), np.dtype(np.float32), ['B*t4', 256])
reshape1N = gs.Node("Reshape", "wiliReshape1N-" + str(n2DMM), inputs=[node.inputs[0], bt4Comma256Tensor], outputs=[reshape1V])
graph.nodes.append(reshape1N)
n2DMM += 1
node.inputs[0] = reshape1V
lastNode = node.o().o().o().o().o().o() # Mul[0.5]
reshape2V = gs.Variable("wiliReshape2V-" + str(n2DMM), np.dtype(np.float32), ['B', 't4', 256])
reshape2N = gs.Node("Reshape", "wiliReshape2N-" + str(n2DMM), inputs=[lastNode.inputs[0], bCommat4Comma64Tensor], outputs=[reshape2V])
graph.nodes.append(reshape2N)
n2DMM += 1
lastNode.inputs[0] = reshape2V
if bAttentionMM:
for node in graph.nodes:
if node.op == 'LayerNorm' and node.name == int(node.name[11:]) % 5 == 1:
qM = node.o(1).inputs[1].values
qB = node.o(1).o().inputs[0].values
kM = node.o(2).inputs[1].values
kB = node.o(2).o().inputs[0].values
vM = node.o(3).inputs[1].values
vB = node.o(3).o().inputs[0].values
bigFactor = np.concatenate([qM, kM, vM], axis=1)
bigBias = np.concatenate([qB, kB, vB], axis=0)
bigFactorTensor = gs.Constant("bigFactorTensor" + str(nAttentionMM), np.ascontiguousarray(bigFactor))
bigBiasTensor = gs.Constant("bigBiasTensor" + str(nAttentionMM), np.ascontiguousarray(bigBias))
nAttentionMM += 1
qReshapeN = node.o(1).o().o()
kReshapeN = node.o(2).o().o()
vReshapeN = node.o(3).o().o()
matMulV = gs.Variable("wiliMatMul1V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256 * 3])
matMulN = gs.Node("MatMul", "wiliMatMulN-" + str(nAttentionMM), inputs=[node.outputs[0], bigFactorTensor], outputs=[matMulV])
graph.nodes.append(matMulN)
nAttentionMM += 1
addV = gs.Variable("wiliAddV-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256 * 3])
addN = gs.Node("Add", "wiliAddN-" + str(nAttentionMM), inputs=[matMulV, bigBiasTensor], outputs=[addV])
graph.nodes.append(addN)
nAttentionMM += 1
split0V = gs.Variable("wiliSplit0V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256])
split1V = gs.Variable("wiliSplit1V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256])
split2V = gs.Variable("wiliSplit2V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256])
splitN = gs.Node("Split", "wiliSplitN-" + str(nAttentionMM), inputs=[addV], outputs=[split0V, split1V, split2V], attrs=OrderedDict([('axis', 1)]))
graph.nodes.append(splitN)
nAttentionMM += 1
qReshapeN.inputs[0] = split0V
qReshapeN.inputs[1] = bCommat4Comma4Comma64Tensor
kReshapeN.inputs[0] = split1V
kReshapeN.inputs[1] = bCommat4Comma4Comma64Tensor
vReshapeN.inputs[0] = split2V
vReshapeN.inputs[1] = bCommat4Comma4Comma64Tensor
# Round 7: Attention Plugin, by Xuewei Li
if bAttentionPlugin:
tensorTable = graph.tensors()
para = {}
inputTable = {}
outputTable = {}
for name in tensorTable:
if "self_attn.pos_bias_u" in name:
para[name] = np.array(deepcopy(tensorTable[name].values.tolist()), dtype=np.float32)
if "self_attn.pos_bias_v" in name:
para[name] = np.array(deepcopy(tensorTable[name].values.tolist()), dtype=np.float32)
tensor = tensorTable[name]
test = tensor.outputs[0].o().o().i(1, 0).i(0).i(0)
if test.op == "MatMul":
t = test.inputs[1]
para[name[:len(name) - 20] + "self_attn.linear_pos.weight"] = np.array(deepcopy(t.values.tolist()), dtype=np.float32)
else:
raise Exception("not correct!")
if "self_attn.linear_q.bias" in name or "self_attn.linear_k.bias" in name\
or "self_attn.linear_v.bias" in name or "self_attn.linear_out.bias" in name:
tensor = tensorTable[name]
para[name] = np.array(deepcopy(tensor.values.tolist()), dtype=np.float32)
weight_node = tensor.outputs[0].i(1, 0)
if weight_node.op == "MatMul":
para[name[:-4] + "weight"] = np.array(deepcopy(weight_node.inputs[1].values.tolist()), dtype=np.float32)
if "self_attn.linear_out.bias" in name:
ot = weight_node.inputs[0]
ot_node = ot.inputs[0]
outputTable[name[:-25]] = ot.name
outputTable[name[:-25] + "node"] = ot_node
if "self_attn.linear_q.bias" in name:
it = weight_node.inputs[0]
inputTable[name[:-23]] = it.name
else:
raise Exception("not correct!")
input1 = tensorTable["603"]
mask = tensorTable["613"]
test = tensorTable["551"]
input2 = gs.Variable("CastVariable-", np.dtype(np.int32), None)
castN = gs.Node("Cast", "CastnNode-", inputs=[mask], outputs=[input2], attrs=OrderedDict([('to', 1)]))
graph.nodes.append(castN)
index = 0
for name in inputTable:
input0 = tensorTable[inputTable[name]]
inputList = [input0, input1, input2]
temp = para[name + 'self_attn.pos_bias_u']
inputList.append(gs.Constant(name + "-pos_bias_u", np.ascontiguousarray(para[name + 'self_attn.pos_bias_u'].reshape(-1))))
inputList.append(gs.Constant(name + "-pos_bias_v", np.ascontiguousarray(para[name + 'self_attn.pos_bias_v'].reshape(-1))))
q_weight = para[name + 'self_attn.linear_q.weight']
k_weight = para[name + 'self_attn.linear_k.weight']
v_weight = para[name + 'self_attn.linear_v.weight']
qkv_weight = np.stack((q_weight, k_weight, v_weight))
inputList.append(gs.Constant(name + "-linear_qkv_weight", np.ascontiguousarray(qkv_weight.reshape(-1))))
inputList.append(gs.Constant(name + "-linear_q_bias", np.ascontiguousarray(para[name + 'self_attn.linear_q.bias'].reshape(-1))))
inputList.append(gs.Constant(name + "-linear_k_bias", np.ascontiguousarray(para[name + 'self_attn.linear_k.bias'].reshape(-1))))
inputList.append(gs.Constant(name + "-linear_v_bias", np.ascontiguousarray(para[name + 'self_attn.linear_v.bias'].reshape(-1))))
inputList.append(gs.Constant(name + "-linear_out_weight", np.ascontiguousarray(para[name + 'self_attn.linear_out.weight'].reshape(-1))))
inputList.append(gs.Constant(name + "-linear_out_bias", np.ascontiguousarray(para[name + 'self_attn.linear_out.bias'].reshape(-1))))
inputList.append(gs.Constant(name + "-linear_pos_weight", np.ascontiguousarray(para[name + 'self_attn.linear_pos.weight'].reshape(-1))))
ForwardAttentionN = gs.Node("Attention", "Attention" + name, inputs=inputList, outputs=[tensorTable[outputTable[name]]])
# ForwardAttentionN.inputs[0].dtype = np.dtype(np.float32)
# ForwardAttentionN.inputs[1].dtype = np.dtype(np.float32)
# ForwardAttentionN.inputs[2].dtype = np.dtype(np.int32)
graph.nodes.append(ForwardAttentionN)
outputTable[name + "node"].outputs = []
index = index + 1
nAttentionPlugin += 1
# for debug
if len(debugNodeList) > 0:
for node in graph.nodes:
if node.name in debugNodeList:
#graph.outputs.append( node.inputs[0] )
graph.outputs.append(node.outputs[0])
#graph.outputs = [node.outputs[0]]
graph.cleanup()
onnx.save(gs.export_onnx(graph), destinationOnnx)
print("finish encoder onnx-graphsurgeon!")
print("%4d NotV3" % nNotV3)
print("%4d LayerNormPlugin" % nLayerNormPlugin)
print("%4d ConstantFold" % nConstantFold)
print("%4d ReshapeMatmulToConv" % nReshapeMatmulToConv)
print("%4d Expand" % nExpand)
print("%4d 2DMM" % n2DMM)
print("%4d Wili" % nWili)
print("%4d AttentionMM" % nAttentionMM)
print("%4d AttentionPlugin" % nAttentionPlugin) | trt-samples-for-hackathon-cn-master | Hackathon2022/code/encoder-surgeonV6.py |
#!/usr/bin/python
import ctypes
from cuda import cudart
from datetime import datetime as dt
from glob import glob
import numpy as np
import os
import sys
import tensorrt as trt
from calibrator import EncoderCalibrator
#basePath = "/target/"
basePath = "./"
onnxFile = sorted(glob(basePath + "encoderV*.onnx"))[-1]
trtFile = basePath + "encoder.plan"
isForSubmit = True
isConvertToStaticNetwork = False
isPrintNetwork = False
additionOutput = []
useInt8 = False
calibrationDataFile = "/workspace/data/calibration.npz"
int8CacheFile = basePath + "encoder-int8.cache"
strictTypeLayer = []
useTimeCache = True
timeCacheFile = "./encoder.cache"
nTestBS = 4
nTestSL = 64
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
for soFile in glob(basePath + "*.so"):
ctypes.cdll.LoadLibrary(soFile)
timeCache = b""
if useTimeCache and os.path.isfile(timeCacheFile):
with open(timeCacheFile, 'rb') as f:
timeCache = f.read()
if timeCache == None:
print("Failed getting serialized timing cache!")
exit()
print("Succeeded getting serialized timing cache!")
if os.path.isfile(trtFile):
print("Engine existed!")
with open(trtFile, 'rb') as f:
engineString = f.read()
else:
builder = trt.Builder(logger)
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
profile = builder.create_optimization_profile()
config = builder.create_builder_config()
if useTimeCache:
cache = config.create_timing_cache(timeCache)
config.set_timing_cache(cache, False)
if isForSubmit:
config.max_workspace_size = 22 << 30
config.flags = 1 << int(trt.BuilderFlag.FP16)
config.flags = config.flags & ~(1 << int(trt.BuilderFlag.TF32))
if useInt8:
config.flags = config.flags | (1 << int(trt.BuilderFlag.INT8))
config.int8_calibrator = EncoderCalibrator(calibrationDataFile, int8CacheFile, 16, 256)
else:
config.max_workspace_size = 6 << 30
config.flags = config.flags & ~(1 << int(trt.BuilderFlag.TF32))
config.flags = config.flags | (1 << int(trt.BuilderFlag.DEBUG))
config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
if useInt8:
config.flags = config.flags | (1 << int(trt.BuilderFlag.INT8))
config.int8_calibrator = EncoderCalibrator(calibrationDataFile, int8CacheFile, 16, 64)
parser = trt.OnnxParser(network, logger)
if not os.path.exists(onnxFile):
print("Failed finding ONNX file!")
exit()
print("Succeeded finding ONNX file!")
with open(onnxFile, 'rb') as model:
if not parser.parse(model.read()):
print("Failed parsing ONNX file!")
for error in range(parser.num_errors):
print(parser.get_error(error))
exit()
print("Succeeded parsing ONNX file!")
if isForSubmit:
inputT0 = network.get_input(0)
inputT0.shape = [-1, -1, 80]
profile.set_shape(inputT0.name, (1, 16, 80), (64, 1024, 80), (64, 1024, 80))
inputT1 = network.get_input(1)
inputT1.shape = [-1]
profile.set_shape(inputT1.name, (1, ), (64, ), (64, ))
config.add_optimization_profile(profile)
else:
if isConvertToStaticNetwork:
inputT0 = network.get_input(0)
inputT0.shape = [3, 17, 80]
inputT1 = network.get_input(1)
inputT1.shape = [3]
else:
inputT0 = network.get_input(0)
inputT0.shape = [-1, -1, 80]
profile.set_shape(inputT0.name, (1, 4, 80), (4, 16, 80), (4, 16, 80))
inputT1 = network.get_input(1)
inputT1.shape = [-1]
profile.set_shape(inputT1.name, (1, ), (4, ), (4, ))
config.add_optimization_profile(profile)
if isPrintNetwork:
for i in range(network.num_layers):
layer = network.get_layer(i)
print(i, "%s,in=%d,out=%d,%s" % (str(layer.type)[10:], layer.num_inputs, layer.num_outputs, layer.name))
for j in range(layer.num_inputs):
tensor = layer.get_input(j)
if tensor == None:
print("\tInput %2d:" % j, "None")
else:
print("\tInput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name))
for j in range(layer.num_outputs):
tensor = layer.get_output(j)
if tensor == None:
print("\tOutput %2d:" % j, "None")
else:
print("\tOutput %2d:%s,%s,%s" % (j, tensor.shape, str(tensor.dtype)[9:], tensor.name))
exit()
if len(strictTypeLayer) > 0:
for index in strictTypeLayer:
layer = network.get_layer(i)
layer.precision = trt.float32
layer.get_output(0).dtype = trt.float32
if len(additionOutput) > 0:
for index in additionOutput:
network.mark_output(network.get_layer(index).get_output(0))
#network.mark_output(network.get_layer(index).get_input(0))
engineString = builder.build_serialized_network(network, config)
if engineString == None:
print("Failed building engine!")
exit()
if useTimeCache and not os.path.isfile(timeCacheFile):
timeCache = config.get_timing_cache()
timeCacheString = timeCache.serialize()
with open(timeCacheFile, 'wb') as f:
f.write(timeCacheString)
print("Succeeded saving .cache file!")
print("Succeeded building engine!")
with open(trtFile, 'wb') as f:
f.write(engineString)
'''
engine = trt.Runtime(logger).deserialize_cuda_engine(engineString)
context = engine.create_execution_context()
context.set_binding_shape(0, [nTestBS,nTestSL,80])
context.set_binding_shape(1, [nTestBS])
nInput = np.sum([engine.binding_is_input(i) for i in range(engine.num_bindings)])
nOutput = engine.num_bindings - nInput
for i in range(nInput):
print("Bind[%2d]:i[%2d]->" % (i, i), engine.get_binding_dtype(i), engine.get_binding_shape(i), context.get_binding_shape(i), engine.get_binding_name(i))
for i in range(nInput,nInput+nOutput):
print("Bind[%2d]:o[%2d]->" % (i, i - nInput), engine.get_binding_dtype(i), engine.get_binding_shape(i), context.get_binding_shape(i), engine.get_binding_name(i))
dd = np.load("/workspace/data/encoder-%d-%d.npz"%(nTestBS,nTestSL))
bufferH = []
bufferH.append(np.ascontiguousarray(dd['speech'].reshape(-1)))
bufferH.append(np.ascontiguousarray(dd['speech_lengths'].reshape(-1)))
for i in range(nInput, nInput + nOutput):
bufferH.append(np.empty(context.get_binding_shape(i), dtype=trt.nptype(engine.get_binding_dtype(i))))
bufferD = []
for i in range(nInput + nOutput):
bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1])
for i in range(nInput):
cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
context.execute_v2(bufferD)
for i in range(nInput, nInput + nOutput):
cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost)
out={}
for i in range(nInput + nOutput):
print(engine.get_binding_name(i))
print(bufferH[i].reshape(context.get_binding_shape(i)))
out[str(i)] = bufferH[i]
np.savez('encoderOut.npz',**out)
for b in bufferD:
cudart.cudaFree(b)
print("Finished building Encoder engine!")
'''
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/encoder.py |
import os
import numpy as np
from cuda import cudart
import tensorrt as trt
class EncoderCalibrator(trt.IInt8EntropyCalibrator2):
def __init__(self, npzFile, cacheFile, nBS, nSL): # BatchSize,SequenceLength,Calibration
trt.IInt8EntropyCalibrator2.__init__(self)
self.data = np.load(npzFile)
self.cacheFile = cacheFile
self.nBS = nBS
self.nSL = nSL
self.iB = 0
self.keyName0 = "speech-" + str(nSL)
self.keyName1 = "speech_lengths-" + str(nSL)
self.bufferSize0 = np.zeros([nBS, nSL, 80], dtype=np.float32).nbytes
self.bufferSize1 = np.zeros([nBS], dtype=np.int32).nbytes
self.bufferD = []
self.bufferD.append(cudart.cudaMalloc(self.bufferSize0)[1])
self.bufferD.append(cudart.cudaMalloc(self.bufferSize1)[1])
print("> Encoder calibrator constructor")
def __del__(self):
cudart.cudaFree(self.bufferD[0])
cudart.cudaFree(self.bufferD[1])
def get_batch_size(self): # do NOT change name
return self.nBS
def get_batch(self, nameList=None, inputNodeName=None): # do NOT change name
print("> Calibration: %d/%d" % (self.iB, 100 // self.nBS))
if (self.iB + 1) * self.nBS > 100:
return None
batchData0 = self.data[self.keyName0][self.iB * self.nBS:(self.iB + 1) * self.nBS]
batchData1 = self.data[self.keyName1][self.iB * self.nBS:(self.iB + 1) * self.nBS]
cudart.cudaMemcpy(self.bufferD[0], batchData0.ctypes.data, self.bufferSize0, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
cudart.cudaMemcpy(self.bufferD[1], batchData1.ctypes.data, self.bufferSize1, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
self.iB += 1
return self.bufferD
def read_calibration_cache(self): # do NOT change name
if os.path.exists(self.cacheFile):
print("Succeed finding int8 cahce: %s" % (self.cacheFile))
with open(self.cacheFile, "rb") as f:
cache = f.read()
return cache
else:
print("Failed finding int8 cache!")
return None
def write_calibration_cache(self, cache): # do NOT change name
with open(self.cacheFile, "wb") as f:
f.write(cache)
print("Succeed saving int8 cache: %s" % (self.cacheFile))
class DecoderCalibrator(trt.IInt8EntropyCalibrator2):
def __init__(self, npzFile, cacheFile, nBS, nSL): # BatchSize,SequenceLength,Calibration
trt.IInt8EntropyCalibrator2.__init__(self)
self.data = np.load(npzFile)
self.cacheFile = cacheFile
self.nBS = nBS
self.nSL = nSL
self.iB = 0
self.keyName0 = "encoder_out-" + str(nSL)
self.keyName1 = "encoder_out_lens-" + str(nSL)
self.keyName2 = "hyps_pad_sos_eos-" + str(nSL)
self.keyName3 = "hyps_lens_sos-" + str(nSL)
self.keyName4 = "ctc_score-" + str(nSL)
self.bufferSize0 = np.zeros([nBS, nSL, 256], dtype=np.float32).nbytes
self.bufferSize1 = np.zeros([nBS], dtype=np.int32).nbytes
self.bufferSize2 = np.zeros([nBS, 10, 64], dtype=np.int32).nbytes
self.bufferSize3 = np.zeros([nBS, 10], dtype=np.int32).nbytes
self.bufferSize4 = np.zeros([nBS, 10], dtype=np.float32).nbytes
self.bufferD = []
self.bufferD.append(cudart.cudaMalloc(self.bufferSize0)[1])
self.bufferD.append(cudart.cudaMalloc(self.bufferSize1)[1])
self.bufferD.append(cudart.cudaMalloc(self.bufferSize2)[1])
self.bufferD.append(cudart.cudaMalloc(self.bufferSize3)[1])
self.bufferD.append(cudart.cudaMalloc(self.bufferSize4)[1])
print("> Decoder calibrator constructor")
def __del__(self):
for i in range(5):
cudart.cudaFree(self.bufferD[i])
def get_batch_size(self): # do NOT change name
return self.nBS
def get_batch(self, nameList=None, inputNodeName=None): # do NOT change name
print("> Calibration: %d/%d" % (self.iB, 100 // self.nBS))
if (self.iB + 1) * self.nBS > 100:
return None
batchData0 = self.data[self.keyName0][self.iB * self.nBS:(self.iB + 1) * self.nBS]
batchData1 = self.data[self.keyName1][self.iB * self.nBS:(self.iB + 1) * self.nBS]
batchData2 = self.data[self.keyName2][self.iB * self.nBS:(self.iB + 1) * self.nBS]
batchData3 = self.data[self.keyName3][self.iB * self.nBS:(self.iB + 1) * self.nBS]
batchData4 = self.data[self.keyName4][self.iB * self.nBS:(self.iB + 1) * self.nBS]
cudart.cudaMemcpy(self.bufferD[0], batchData0.ctypes.data, self.bufferSize0, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
cudart.cudaMemcpy(self.bufferD[1], batchData1.ctypes.data, self.bufferSize1, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
cudart.cudaMemcpy(self.bufferD[2], batchData2.ctypes.data, self.bufferSize2, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
cudart.cudaMemcpy(self.bufferD[3], batchData3.ctypes.data, self.bufferSize3, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
cudart.cudaMemcpy(self.bufferD[4], batchData4.ctypes.data, self.bufferSize4, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
self.iB += 1
return self.bufferD
def read_calibration_cache(self): # do NOT change name
if os.path.exists(self.cacheFile):
print("Succeed finding int8 cahce: %s" % (self.cacheFile))
with open(self.cacheFile, "rb") as f:
cache = f.read()
return cache
else:
print("Failed finding int8 cache!")
return None
def write_calibration_cache(self, cache): # do NOT change name
with open(self.cacheFile, "wb") as f:
f.write(cache)
print("Succeed saving int8 cache: %s" % (self.cacheFile))
if __name__ == "__main__":
cudart.cudaDeviceSynchronize()
nBS = 4
nSL = 64
m = EncoderCalibrator("/workspace/data/calibration.npz", "./testCalibrator.cache", nBS, nSL)
for i in range((100 + nBS - 1) // nBS + 1):
print("%2d->" % i, m.get_batch("FakeNameList"))
m = DecoderCalibrator("/workspace/data/calibration.npz", "./testCalibrator.cache", nBS, nSL)
for i in range((100 + nBS - 1) // nBS + 1):
print("%2d->" % i, m.get_batch("FakeNameList"))
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/calibrator.py |
from collections import OrderedDict
from copy import deepcopy
import numpy as np
import onnx
import onnx_graphsurgeon as gs
sourceOnnx = "./encoderV2.onnx"
destinationOnnx = "./encoderV3.onnx"
bConvertToStaticNetwork = False
debugNodeList = []
nWili = 0
bSimplifyOutput = True
bNot = False
nNot = 0
bNotV2 = True
nNotV2 = 0
bMaskPlugin = False
nMaskPlugin = 0
bLayerNormPlugin = True
nLayerNormPlugin = 0
bConstantFold = True
nConstantFold = 0
bReshapeMatmulToConv = True
nReshapeMatmulToConv = 0
bExpand = True
nExpand = 0
b2DMM = True
n2DMM = 0
bAttentionMM = False
nAttentionMM = 0
#graph = gs.import_onnx(onnx.load(sourceOnnx))
graph = gs.import_onnx(onnx.shape_inference.infer_shapes(onnx.load(sourceOnnx)))
if bConvertToStaticNetwork:
graph.inputs[0].shape = [3, 17, 256]
graph.inputs[1].shape = [3]
else:
graph.inputs[0].shape = ['B', 'T', 80]
graph.inputs[1].shape = ['B']
# Round 0: ceate useful constant tensor or collect useful shape tensor
wiliConstant0 = gs.Constant("wiliConstant0", np.ascontiguousarray(np.array([0], dtype=np.int64))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
wiliConstant1 = gs.Constant("wiliConstant1", np.ascontiguousarray(np.array([1], dtype=np.int64)))
wiliConstant3 = gs.Constant("wiliConstant3", np.ascontiguousarray(np.array([3], dtype=np.int64)))
wiliConstant4 = gs.Constant("wiliConstant4", np.ascontiguousarray(np.array([4], dtype=np.int64)))
wiliConstantM4 = gs.Constant("wiliConstantM4", np.ascontiguousarray(np.array([-4], dtype=np.int64))) # minus four
wiliConstant64 = gs.Constant("wiliConstant64", np.ascontiguousarray(np.array([64], dtype=np.int64)))
wiliConstant256 = gs.Constant("wiliConstant256", np.ascontiguousarray(np.array([256], dtype=np.int64)))
wiliConstantS0 = gs.Constant("wiliConstantS0", np.array(0, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(0, dtype=np.dtype(np.int64)))
wiliConstantS1 = gs.Constant("wiliConstantS1", np.array(1, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(1, dtype=np.dtype(np.int64)))
wiliConstantS2 = gs.Constant("wiliConstantS2", np.array(2, dtype=np.int64)).to_variable(np.dtype(np.int64), []).to_constant(np.array(2, dtype=np.dtype(np.int64)))
wiliShapeV = gs.Variable("wiliShapeV-" + str(nWili), np.dtype(np.int64), [3])
wiliShapeN = gs.Node("Shape", "wiliShapeN-" + str(nWili), inputs=[graph.inputs[0]], outputs=[wiliShapeV])
graph.nodes.append(wiliShapeN)
nWili += 1
# shape = [], value = ['B']
bTensorScalar = gs.Variable("bTensorScalar", np.dtype(np.int64), [])
wiliGatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[wiliShapeV, wiliConstantS0], outputs=[bTensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliGatherN)
nWili += 1
# shape = [1,], value = ['B']
bTensor = gs.Variable("bTensor", np.dtype(np.int64), [1])
wiliUnsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[bTensorScalar, wiliConstant0], outputs=[bTensor])
graph.nodes.append(wiliUnsqueezeN)
nWili += 1
# shape = [], value = ['T']
tTensorScalar = gs.Variable("tTensorScalar", np.dtype(np.int64), [])
wiliGatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[wiliShapeV, wiliConstantS1], outputs=[tTensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliGatherN)
nWili += 1
# shape = [1,], value = ['T']
tTensor = gs.Variable("tTensor", np.dtype(np.int64), [1])
wiliUnsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[tTensorScalar, wiliConstant0], outputs=[tTensor])
graph.nodes.append(wiliUnsqueezeN)
nWili += 1
# shape = [1,], value = ['t4'], t4 = floor('T'/4) - 1
for node in graph.nodes:
if node.op == 'Relu' and node.name == 'Relu_38':
shapeV = gs.Variable("wiliShapeV-" + str(nWili), np.dtype(np.int64), [4])
shapeN = gs.Node("Shape", "wiliShapeN-" + str(nWili), inputs=[node.outputs[0]], outputs=[shapeV])
graph.nodes.append(shapeN)
nWili += 1
t4TensorScalar = gs.Variable("t4TensorScalar", np.dtype(np.int64), [])
gatherN = gs.Node("Gather", "wiliGatherN-" + str(nWili), inputs=[shapeV, wiliConstantS2], outputs=[t4TensorScalar], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(gatherN)
nWili += 1
t4Tensor = gs.Variable("t4Tensor", np.dtype(np.int64), [1])
unsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nWili), inputs=[t4TensorScalar, wiliConstant0], outputs=[t4Tensor])
graph.nodes.append(unsqueezeN)
nWili += 1
'''
# Old method to get t4Tensor
for node in graph.nodes:
if node.op == 'Unsqueeze' and node.name == 'Unsqueeze_56':
t4Tensor = node.outputs[0] # shape = [1,], value = ['t4'], t4 = floor('T'/4) - 1
# Error method to get t4Tensor
t4_Tensor = gs.Variable("t4_Tensor", np.dtype(np.int64), [1])
wiliT4_N = gs.Node("Div","wiliDivN-"+str(nWili), inputs = [tTensor, wiliConstant4],outputs=[t4_Tensor])
graph.nodes.append(wiliT4_N)
nWili += 1
t4Tensor = gs.Variable("t4Tensor", np.dtype(np.int64), [1]) # shape = [1,], value = ['t4'], t4 = floor('T'/4) - 1
wiliT4N = gs.Node("Sub","wiliSubN-"+str(nWili), inputs = [t4_Tensor, wiliConstant1],outputs=[t4Tensor])
graph.nodes.append(wiliT4N)
nWili += 1
'''
# shape = [1,], value = ['B'*'t4']
bt4Tensor = gs.Variable("bt4Tensor-" + str(nWili), np.dtype(np.int64), [1])
wiliMulN = gs.Node("Mul", "wiliMulN-" + str(nWili), inputs=[bTensor, t4Tensor], outputs=[bt4Tensor])
graph.nodes.append(wiliMulN)
nWili += 1
# shape = [2,], value = ['B'*'t4',256]
bt4Comma256Tensor = gs.Variable("bt4Comma256Tensor-" + str(nWili), np.dtype(np.int64), [2])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bt4Tensor, wiliConstant256], outputs=[bt4Comma256Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [3,], value = ['B','t4',256]
bCommat4Comma64Tensor = gs.Variable("bCommat4Comma64Tensor-" + str(nWili), np.dtype(np.int64), [3])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, t4Tensor, wiliConstant256], outputs=[bCommat4Comma64Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# shape = [4,], value = ['B','t4',4,64]
bCommat4Comma4Comma64Tensor = gs.Variable("bCommat4Comma4Comma64Tensor-" + str(nWili), np.dtype(np.int64), [4])
wiliConcatN = gs.Node("Concat", "wiliConcatN-" + str(nWili), inputs=[bTensor, t4Tensor, wiliConstant4, wiliConstant64], outputs=[bCommat4Comma4Comma64Tensor], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(wiliConcatN)
nWili += 1
# Round 0.5: output tensor
if bSimplifyOutput:
for node in graph.nodes:
graph.outputs[0].name = 'deprecated[encoder_out]'
graph.outputs[1].name = 'deprecated[encoder_out_lens]'
graph.outputs = graph.outputs[:2]
'''
wiliDivV0 = gs.Variable("wiliDevV-0", np.dtype(np.int32), ['B'])
wiliDivN0 = gs.Node("Div", "wiliDivN-0", inputs=[graph.inputs[1], wiliConstant4], outputs=[wiliDivV0])
graph.nodes.append(wiliDivN0)
wiliAddV0 = gs.Variable("wiliAddV-0", np.dtype(np.int32), ['B'])
wiliAddN0 = gs.Node("Add", "wiliAddN-0", inputs=[wiliDivV0, wiliConstant1], outputs=[wiliAddV0])
graph.nodes.append(wiliAddN0)
'''
wiliAddV0 = gs.Variable("wiliAddV-0", np.dtype(np.int32), ['B'])
wiliAddN0 = gs.Node("Add", "wiliAddN-0", inputs=[graph.inputs[1], wiliConstant3], outputs=[wiliAddV0])
graph.nodes.append(wiliAddN0)
wiliDivV0 = gs.Variable("wiliDevV-0", np.dtype(np.int32), ['B'])
wiliDivN0 = gs.Node("Div", "wiliDivN-0", inputs=[wiliAddV0, wiliConstant4], outputs=[wiliDivV0])
graph.nodes.append(wiliDivN0)
wiliMinV0 = gs.Variable("encoder_out_lens", np.dtype(np.int32), ['B'])
wiliMinN0 = gs.Node("Min", "wiliMinN-0", inputs=[wiliDivV0, t4Tensor], outputs=[wiliMinV0])
graph.nodes.append(wiliMinN0)
graph.outputs[1] = wiliMinV0
# Round 1: Not, deprecated since V4
if bNot:
for node in graph.nodes:
if node.name == 'Not_30':
castV = gs.Variable("wiliCastV-" + str(nNot), np.dtype(bool), None)
castN = gs.Node("Cast", "wiliCastN-" + str(nNot), inputs=[node.i().outputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.BOOL)]))
graph.nodes.append(castN)
nNot += 1
node.inputs = [castV]
castV = gs.Variable("wiliCastV-" + str(nNot), np.dtype(np.int32), None)
castN = gs.Node("Cast", "wiliCastN-" + str(nNot), inputs=node.outputs, outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.INT32)]))
graph.nodes.append(castN)
nNot += 1
node.o().inputs[0] = castV
node.o().o().outputs[0].dtype = np.dtype(np.int32)
node.o().o().o().outputs[0].dtype = np.dtype(np.int32)
continue
if node.op == 'Not' and node.name != 'Not_30':
castV = gs.Variable("wiliCastV-" + str(nNot), np.dtype(bool), None)
castN = gs.Node("Cast", "wiliCastN-" + str(nNot), inputs=[node.inputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.BOOL)]))
graph.nodes.append(castN)
nNot += 1
node.inputs = [castV]
continue
# Round 1.1: Not version 2
if bNotV2:
for node in graph.nodes:
if node.op == 'Slice' and node.name == 'Slice_79':
# adjust node before Slice_79
greaterOrEqualNode = node.i().i().i()
greaterOrEqualNode.op = 'Less'
greaterOrEqualNode.name = 'LessN-' + str(nNotV2)
nNotV2 += 1
castV = gs.Variable("wiliCastV-" + str(nNotV2), np.dtype(np.int32), None)
castN = gs.Node("Cast", "wiliCastN-" + str(nNotV2), inputs=[greaterOrEqualNode.outputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.INT32)]))
graph.nodes.append(castN)
nNotV2 += 1
# adjust Slice_79
node.inputs[0] = castV
node.inputs[2] = wiliConstantM4 # end
node.inputs[3] = wiliConstant1 # axes
node.inputs[4] = wiliConstant4 # step
slice84Node = node.o()
tensor613 = slice84Node.outputs[0]
tensor613.dtype = np.dtype(np.int32)
unsqueezeTo3DN = gs.Node("Unsqueeze", "wiliUnsqueezeTo3DN-" + str(nNotV2), inputs=[node.outputs[0], wiliConstant1], outputs=[tensor613])
graph.nodes.append(unsqueezeTo3DN)
nNotV2 += 1
slice84Node.outputs = []
continue
if node.op == 'Not' and node.name != 'Not_30':
castV = gs.Variable("castV-" + str(nNotV2), np.dtype(bool), None)
castN = gs.Node("Cast", "CastN-" + str(nNotV2), inputs=[node.inputs[0]], outputs=[castV], attrs=OrderedDict([('to', onnx.TensorProto.BOOL)]))
graph.nodes.append(castN)
nNotV2 += 1
node.inputs = [castV]
continue
# Round 1.2: Not version 2, adjust node after Slice_79
if bNotV2:
for node in graph.nodes:
if node.op == 'Unsqueeze' and node.name == 'wiliUnsqueezeTo3DN-2':
castV0 = node.o(0).o().o().o().outputs[0]
castV1 = node.o(12 + 1).o().o().outputs[0]
for node in graph.nodes:
if node.op == "Where" and node.o().op == 'Softmax':
# unknown reason to make the output be correct only
#node.inputs[0] = castV0
#nNotV2 += 1
continue
if node.op == "Where" and node.i(2).op == 'Softmax':
node.inputs[0] = castV0
nNotV2 += 1
continue
if node.op == "Where" and node.o().op == 'Conv':
node.inputs[0] = castV1
nNotV2 += 1
continue
if node.op == "Where" and node.i(2).op == 'Conv':
node.inputs[0] = castV1
nNotV2 += 1
continue
# Round 1.9: Mask Plugin - Bad Performance
if bMaskPlugin:
if (True): # one output
maskV0 = gs.Variable("wiliMaskV0-" + str(nMaskPlugin), np.dtype(np.int32), ['B', 1, 't4']) # 0 / 1
maskN = gs.Node("Mask", "wiliMaskN-" + str(nMaskPlugin), inputs=[graph.inputs[0], graph.inputs[1]], outputs=[maskV0])
graph.nodes.append(maskN)
nMaskPlugin += 1
maskV1 = gs.Variable("wiliMaskV1-" + str(nMaskPlugin), np.dtype(bool), ['B', 1, 't4']) # 0 / 1
castN = gs.Node("Equal", "wiliEqualN-" + str(nMaskPlugin), inputs=[maskV0, wiliConstant1], outputs=[maskV1])
graph.nodes.append(castN)
nMaskPlugin += 1
maskV2 = gs.Variable("wiliMaskV2-" + str(nMaskPlugin), np.dtype(bool), ['B', 1, 1, 't4']) # 1 / 0
unsqueezeN = gs.Node("Unsqueeze", "wiliUnsqueezeN-" + str(nMaskPlugin), inputs=[maskV1, wiliConstant1], outputs=[maskV2])
graph.nodes.append(unsqueezeN)
nMaskPlugin += 1
for node in graph.nodes:
if node.op == "Where" and node.o().op == 'Softmax':
node.inputs[0] = maskV2
nMaskPlugin += 1
continue
if node.op == "Where" and node.i(2).op == 'Softmax':
node.inputs[0] = maskV2
nMaskPlugin += 1
continue
if node.op == "Where" and node.o().op == 'Conv':
node.inputs[0] = maskV1
nMaskPlugin += 1
continue
if node.op == "Where" and node.i(2).op == 'Conv':
node.inputs[0] = maskV1
nMaskPlugin += 1
continue
else:
# two output
maskV0 = gs.Variable("wiliMaskV0", np.dtype(np.float32), ['B', 1, 1, 't4']) # 0 / -6e6
maskV1 = gs.Variable("wiliMaskV1", np.dtype(np.float32), ['B', 1, 1, 't4']) # 1 / 0
maskN = gs.Node("Mask", "wiliMaskN-" + str(nMaskPlugin), inputs=[graph.inputs[0], graph.inputs[1]], outputs=[maskV0, maskV1])
graph.nodes.append(maskN)
squeezeAfterMaskV = gs.Variable("wiliSqueezeAfterMaskV", np.dtype(np.float32), ['B', 1, 't4'])
SqueezeAfterMaskN = gs.Node("Squeeze", "wiliSqueezeAfterMaskN", inputs=[maskV1, wiliConstant1], outputs=[squeezeAfterMaskV])
graph.nodes.append(SqueezeAfterMaskN)
for node in graph.nodes:
if node.op == "Where" and node.o().op == 'Softmax':
node.i().outputs = []
node.op = "Add"
node.inputs = [maskV0, node.inputs[2]]
nMaskPlugin += 1
if node.op == "Where" and node.i(2).op == 'Softmax':
node.i().outputs = []
node.op = "Mul"
node.inputs = [maskV1, node.inputs[2]]
nMaskPlugin += 1
if node.op == "Where" and node.o().op == 'Conv':
node.i().outputs = []
node.op = "Mul"
node.inputs = [squeezeAfterMaskV, node.inputs[2]]
nMaskPlugin += 1
if node.op == "Where" and node.i(2).op == 'Conv':
node.i().outputs = []
node.op = "Mul"
node.inputs = [squeezeAfterMaskV, node.inputs[2]]
nMaskPlugin += 1
# Round 2: Layer Normalization
if bLayerNormPlugin:
for node in graph.nodes:
if node.op == 'ReduceMean' and \
node.o().op == 'Sub' and node.o().inputs[0] == node.inputs[0] and \
node.o().o(0).op =='Pow' and node.o().o(1).op =='Div' and \
node.o().o(0).o().op == 'ReduceMean' and \
node.o().o(0).o().o().op == 'Add' and \
node.o().o(0).o().o().o().op == 'Sqrt' and \
node.o().o(0).o().o().o().o().op == 'Div' and node.o().o(0).o().o().o().o() == node.o().o(1) and \
node.o().o(0).o().o().o().o().o().op == 'Mul' and \
node.o().o(0).o().o().o().o().o().o().op == 'Add':
inputTensor = node.inputs[0]
lastMultipyNode = node.o().o(0).o().o().o().o().o()
index = ['weight' in i.name for i in lastMultipyNode.inputs].index(True)
b = np.array(deepcopy(lastMultipyNode.inputs[index].values.tolist()), dtype=np.float32)
constantB = gs.Constant("LayerNormB-" + str(nLayerNormPlugin), np.ascontiguousarray(b.reshape(-1))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
lastAddNode = node.o().o(0).o().o().o().o().o().o()
index = ['bias' in i.name for i in lastAddNode.inputs].index(True)
a = np.array(deepcopy(lastAddNode.inputs[index].values.tolist()), dtype=np.float32)
constantA = gs.Constant("LayerNormA-" + str(nLayerNormPlugin), np.ascontiguousarray(a.reshape(-1)))
inputList = [inputTensor, constantB, constantA]
layerNormV = gs.Variable("LayerNormV-" + str(nLayerNormPlugin), np.dtype(np.float32), None)
layerNormN = gs.Node("LayerNorm", "LayerNormN-" + str(nLayerNormPlugin), inputs=inputList, outputs=[layerNormV])
graph.nodes.append(layerNormN)
if lastAddNode.outputs[0] in graph.outputs: # the last LayerNorm provide one of the graph's output, and do not unsqueeze to 4 dimension
# oldLastAdd -> graph.outputs[0] ===> LayerNorm -> Squeeze -> graph.outputs[0]
layerNormN.outputs[0].name = 'encoder_out'
index = graph.outputs.index(lastAddNode.outputs[0])
graph.outputs[index] = layerNormN.outputs[0]
else: # other LayerNorm contain the subsequent Squeeze operation
for n in graph.nodes:
if lastAddNode.outputs[0] in n.inputs:
index = n.inputs.index(lastAddNode.outputs[0])
n.inputs[index] = layerNormN.outputs[0]
lastAddNode.outputs = []
nLayerNormPlugin += 1
continue
# Round 3: constant fold
if bConstantFold:
for node in graph.nodes:
if node.op == 'Slice' and node.name == 'Slice_74':
node.inputs[2] = t4Tensor
nConstantFold += 1
table5000x256 = node.inputs[0].values[0]
for i in range(1, 24, 2):
trashNode = node.o(i).o().o() # Transpose
factor256x256 = node.o(i).inputs[1].values
newTable = np.matmul(table5000x256, factor256x256).transpose().reshape(1, 4, 64, 5000)[:, :, :, :256]
constantData = gs.Constant("wiliConstant-" + str(nConstantFold), np.ascontiguousarray(newTable))
sliceV = gs.Variable("wiliSliceV-" + str(nConstantFold), np.dtype(np.float32), [1, 4, 64, 't4'])
sliceN = gs.Node(
"Slice",
"wiliSliceN-" + str(nConstantFold),
inputs=[
constantData, # data
wiliConstant0, # start=0
t4Tensor, # end
wiliConstant3, # axes=3
wiliConstant1, # step=1
],
outputs=[sliceV]
)
graph.nodes.append(sliceN)
node.o(i).o().o().o().inputs[1] = sliceV
trashNode.outputs = []
nConstantFold += 1
continue
# Round 4: Reshape + Matmul -> Convolution, by Hongwei
if bReshapeMatmulToConv:
for node in graph.nodes:
if node.op == "Relu" and node.name == 'Relu_38':
matmulNode = node.o(2).o().o()
addNode = matmulNode.o()
mulNode = addNode.o()
convKernel = matmulNode.inputs[1].values.transpose(1, 0).reshape(256, 256, 1, 19).astype(np.float32)
convKernelV = gs.Constant("wiliConvKernelV-" + str(nReshapeMatmulToConv), np.ascontiguousarray(convKernel))
nReshapeMatmulToConv += 1
convBias = addNode.inputs[0].values
convBiasV = gs.Constant("wiliConvBiasV-" + str(nReshapeMatmulToConv), np.ascontiguousarray(convBias))
nReshapeMatmulToConv += 1
convV = gs.Variable("wiliConvV-" + str(nReshapeMatmulToConv), np.dtype(np.float32), ['B', 256, 't4', 1])
convN = gs.Node("Conv", "wiliConvN-" + str(nReshapeMatmulToConv), inputs=[node.outputs[0], convKernelV, convBiasV], outputs=[convV])
convN.attrs = OrderedDict([
('dilations', [1, 1]),
('kernel_shape', [1, 19]),
('pads', [0, 0, 0, 0]),
('strides', [1, 1]),
])
graph.nodes.append(convN)
nReshapeMatmulToConv += 1
squeezeV = gs.Variable("wiliSqueezeV-" + str(nReshapeMatmulToConv), np.dtype(np.float32), ['B', 256, 't4'])
squeezeN = gs.Node("Squeeze", "wiliSqueezeN-" + str(nReshapeMatmulToConv), inputs=[convV, wiliConstant3], outputs=[squeezeV])
graph.nodes.append(squeezeN)
nReshapeMatmulToConv += 1
transposeV = gs.Variable("wiliTransposeV-" + str(nReshapeMatmulToConv), np.dtype(np.float32), ['B', 't4', 256])
transposeN = gs.Node("Transpose", "wiliTransposeN-" + str(nReshapeMatmulToConv), inputs=[squeezeV], outputs=[transposeV], attrs=OrderedDict([('perm', [0, 2, 1])]))
graph.nodes.append(transposeN)
nReshapeMatmulToConv += 1
mulNode.inputs[0] = transposeV
# Round 5: Expand_23
if bExpand:
for node in graph.nodes:
if node.op == 'Expand' and node.name == 'Expand_23':
node.i().i().inputs[1] = tTensorScalar
concatV = gs.Variable("wiliConcatV-" + str(nExpand), np.dtype(np.int64), [2])
concatN = gs.Node("Concat", "wiliConcatN-" + str(nExpand), inputs=[bTensor, tTensor], outputs=[concatV], attrs=OrderedDict([('axis', 0)]))
graph.nodes.append(concatN)
nExpand += 1
node.inputs[1] = concatV
# Round 6: 2D Matrix multiplication
if b2DMM:
for node in graph.nodes:
if node.op == 'MatMul' and node.name != 'MatMul_61' and \
node.o().op == 'Add' and \
node.o().o().op == 'Sigmoid' and \
node.o().o().o().op == 'Mul' and \
node.o().o().o().o().op == 'MatMul' and \
node.o().o().o().o().o().op == 'Add' and \
node.o().o().o().o().o().o().op == 'Mul':
reshape1V = gs.Variable("wiliReshape1V-" + str(n2DMM), np.dtype(np.float32), ['B*t4', 256])
reshape1N = gs.Node("Reshape", "wiliReshape1N-" + str(n2DMM), inputs=[node.inputs[0], bt4Comma256Tensor], outputs=[reshape1V])
graph.nodes.append(reshape1N)
n2DMM += 1
node.inputs[0] = reshape1V
lastNode = node.o().o().o().o().o().o() # Mul[0.5]
reshape2V = gs.Variable("wiliReshape2V-" + str(n2DMM), np.dtype(np.float32), ['B', 't4', 256])
reshape2N = gs.Node("Reshape", "wiliReshape2N-" + str(n2DMM), inputs=[lastNode.inputs[0], bCommat4Comma64Tensor], outputs=[reshape2V])
graph.nodes.append(reshape2N)
n2DMM += 1
lastNode.inputs[0] = reshape2V
'''
# reshape within Attention, worse performance
for node in graph.nodes:
if node.op == 'Reshape' and node.i(0).op == 'Add' and node.i(1).op == 'Concat' and node.o().op != "Mul":
node.inputs[1] = shape3V
if node.o().op == 'Add':
LayerNormN = node.i().i(1).i()
layerNormTensor = node.i().i(1).i().outputs[0]
reshapeV = gs.Variable("reshapeV-"+str(n2DMM), np.dtype(np.float32), ['B','t4',256])
reshapeN = gs.Node("Reshape","wiliReshapeN-"+str(n2DMM), inputs = [reshapeV, bt4Comma256Tensor],outputs=[layerNormTensor])
graph.nodes.append(reshapeN)
n2DMM += 1
LayerNormN.outputs[0] = reshapeV
'''
if bAttentionMM:
for node in graph.nodes:
if node.op == 'LayerNorm' and node.name == int(node.name[11:]) % 5 == 1:
qM = node.o(1).inputs[1].values
qB = node.o(1).o().inputs[0].values
kM = node.o(2).inputs[1].values
kB = node.o(2).o().inputs[0].values
vM = node.o(3).inputs[1].values
vB = node.o(3).o().inputs[0].values
bigFactor = np.concatenate([qM, kM, vM], axis=1)
bigBias = np.concatenate([qB, kB, vB], axis=0)
bigFactorTensor = gs.Constant("bigFactorTensor" + str(nAttentionMM), np.ascontiguousarray(bigFactor))
bigBiasTensor = gs.Constant("bigBiasTensor" + str(nAttentionMM), np.ascontiguousarray(bigBias))
nAttentionMM += 1
qReshapeN = node.o(1).o().o()
kReshapeN = node.o(2).o().o()
vReshapeN = node.o(3).o().o()
matMulV = gs.Variable("wiliMatMul1V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256 * 3])
matMulN = gs.Node("MatMul", "wiliMatMulN-" + str(nAttentionMM), inputs=[node.outputs[0], bigFactorTensor], outputs=[matMulV])
graph.nodes.append(matMulN)
nAttentionMM += 1
addV = gs.Variable("wiliAddV-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256 * 3])
addN = gs.Node("Add", "wiliAddN-" + str(nAttentionMM), inputs=[matMulV, bigBiasTensor], outputs=[addV])
graph.nodes.append(addN)
nAttentionMM += 1
split0V = gs.Variable("wiliSplit0V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256])
split1V = gs.Variable("wiliSplit1V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256])
split2V = gs.Variable("wiliSplit2V-" + str(nAttentionMM), np.dtype(np.float32), ['B*t4', 256])
splitN = gs.Node("Split", "wiliSplitN-" + str(nAttentionMM), inputs=[addV], outputs=[split0V, split1V, split2V], attrs=OrderedDict([('axis', 1)]))
graph.nodes.append(splitN)
nAttentionMM += 1
qReshapeN.inputs[0] = split0V
qReshapeN.inputs[1] = bCommat4Comma4Comma64Tensor
kReshapeN.inputs[0] = split1V
kReshapeN.inputs[1] = bCommat4Comma4Comma64Tensor
vReshapeN.inputs[0] = split2V
vReshapeN.inputs[1] = bCommat4Comma4Comma64Tensor
# for debug
if len(debugNodeList) > 0:
for node in graph.nodes:
if node.name in debugNodeList:
#graph.outputs.append( node.inputs[0] )
graph.outputs.append(node.outputs[0])
#graph.outputs = [node.outputs[0]]
graph.cleanup()
onnx.save(gs.export_onnx(graph), destinationOnnx)
print("finish encoder onnx-graphsurgeon!")
print("%4d Not" % nNot)
print("%4d NotV2" % nNotV2)
print("%4d mask" % nMaskPlugin)
print("%4d LayerNormPlugin" % nLayerNormPlugin)
print("%4d ConstantFold" % nConstantFold)
print("%4d ReshapeMatmulToConv" % nReshapeMatmulToConv)
print("%4d Expand" % nExpand)
print("%4d 2DMM" % n2DMM)
print("%4d Wili" % nWili)
print("%4d AttentionMM" % nAttentionMM)
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/encoder-surgeonV5.py |
#!/usr/bin/python
import numpy as np
np.random.seed(97)
for bs in [1, 4, 16, 64]:
for sl in [16, 64, 256, 1024]:
fileName = "./data/encoder-%d-%d.npz" % (bs, sl)
data = {}
data['speech'] = np.random.rand(bs * sl * 80).astype(np.float32).reshape(bs, sl, 80) * 2 - 1
data['speech_lengths'] = np.random.randint(1, sl, [bs]).astype(np.int32)
data['encoder_out'] = np.random.rand(bs * (sl // 4 - 1) * 256).astype(np.float32).reshape(bs, (sl // 4 - 1), 256) * 2 - 1
data['encoder_out_lens'] = np.random.randint(1, sl, [bs, 1, (sl // 4 - 1)]).astype(bool).reshape(bs, 1, (sl // 4 - 1))
np.savez(fileName, **data)
for bs in [1, 4, 16, 64]:
for sl in [16, 64, 256, 1024]:
fileName = "./data/decoder-%d-%d.npz" % (bs, sl)
data = {}
data['encoder_out'] = np.random.rand(bs * sl * 256).astype(np.float32).reshape(bs, sl, 256) * 2 - 1
data['encoder_out_lens'] = np.random.randint(1, sl, [bs]).astype(np.int32)
#data['hyps_pad_sos_eos'] = np.random.randint(0,10,[bs,10,sl]).astype(np.int32)
data['hyps_pad_sos_eos'] = np.random.randint(0, 10, [bs, 10, 64]).astype(np.int32)
data['hyps_lens_sos'] = np.random.randint(0, 10, [bs, 10]).astype(np.int32)
data['ctc_score'] = np.random.rand(bs * 10).astype(np.float32).reshape(bs, 10) * 2 - 1
#data['decoder_out'] = np.random.rand(bs*10*(sl-1)*4233).astype(np.float32).reshape(bs,10,sl-1,4233) * 2 - 1
data['decoder_out'] = np.random.rand(bs * 10 * (64 - 1) * 4233).astype(np.float32).reshape(bs, 10, (64 - 1), 4233) * 2 - 1
data['best_index'] = np.random.randint(0, 10, [bs]).astype(np.int32)
np.savez(fileName, **data)
print("Finish!")
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/createFakeIOData.py |
#!/usr/bin/python
import os
import sys
import ctypes
import numpy as np
from glob import glob
from time import time_ns
from datetime import datetime as dt
from cuda import cudart
import tensorrt as trt
dataFilePath = "./data/"
planFilePath = ""
encoderPlanFile = planFilePath + "encoder.plan"
encoderScoreFile = planFilePath + "encoderScore.txt"
decoderPlanFile = planFilePath + "decoder.plan"
decoderScoreFile = planFilePath + "decoderScore.txt"
soFileList = glob("./*.so")
tableHead = \
"""
bs: Batch Size
sl: Sequence Length
lt: Latency (ms)
tp: throughput (word/s)
a0: maximum of absolute difference of output 0
r0: median of relative difference of output 0
a1: maximum of absolute difference of output 1
r1: median of relative difference of output 1
----+----+--------+---------+---------+---------+---------+---------+-------------
bs| sl| lt| tp| a0| r0| a1| r1| output check
----+----+--------+---------+---------+---------+---------+---------+-------------
"""
def printArrayInfo(x, description=""):
print( '%s: %s\n Mean=%.5e,SumAbs=%.5e,Var=%.5e,Max=%.5f,Min=%.5f,SAD=%.5e'%( \
description,str(x.shape),np.mean(x),np.sum(abs(x)),np.var(x),np.max(x),np.min(x),np.sum(np.abs(np.diff(x.reshape(-1)))) ))
print("\t", x.reshape(-1)[:10])
def check(a, b, weak=False, epsilon=1e-5):
if weak:
res = np.all(np.abs(a - b) < epsilon)
else:
res = np.all(a == b)
diff0 = np.max(np.abs(a - b))
diff1 = np.median(np.abs(a - b) / (np.abs(b) + epsilon))
#print("check:",res,diff0,diff1)
return res, diff0, diff1
#-------------------------------------------------------------------------------
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
if len(soFileList) > 0:
print("Find Plugin %s!" % soFileList)
else:
print("No Plugin!")
for soFile in soFileList:
ctypes.cdll.LoadLibrary(soFile)
#-------------------------------------------------------------------------------
def testEncoder():
print("Test Encoder Part!")
with open(encoderScoreFile, 'w') as f:
if os.path.isfile(encoderPlanFile):
with open(encoderPlanFile, 'rb') as encoderF:
engine = trt.Runtime(logger).deserialize_cuda_engine(encoderF.read())
if engine is None:
print("Failed loading %s" % encoderPlanFile)
return
print("Succeeded loading %s" % encoderPlanFile)
else:
print("Failed finding %s" % encoderPlanFile)
return
nInput = np.sum([engine.binding_is_input(i) for i in range(engine.num_bindings)])
nOutput = engine.num_bindings - nInput
context = engine.create_execution_context()
print(tableHead) # for standard output
#test = sorted(glob("/data/attention_from_hackthon/test_data" + "/encoder-*.npz"))
test = sorted(glob("/data/attention_from_hackthon/test_data" + "/encoder-*.npz"))
#for ioFile in sorted(glob("/data/attention_from_hackthon/test_data" + "/encoder-*.npz")):
for ioFile in sorted(glob("./data/encoder-*.npz")):
ioData = np.load(ioFile)
speech = ioData['speech']
speech_lengths = ioData['speech_lengths']
batchSize, sequenceLength, _ = speech.shape
# if batchSize != 1 or sequenceLength != 64:
# continue
context.set_binding_shape(0, speech.shape)
context.set_binding_shape(1, speech_lengths.shape)
#for i in range(nInput + nOutput):
# print("Input ->" if engine.binding_is_input(i) else "Output->", engine.get_binding_dtype(i), engine.get_binding_shape(i), context.get_binding_shape(i), engine.get_binding_dtype(i), engine.get_binding_name(i))
#print("Finish all input binding: %s"%context.all_binding_shapes_specified)
bufferH = []
bufferH.append(speech.astype(np.float32).reshape(-1))
bufferH.append(speech_lengths.astype(np.int32).reshape(-1))
for i in range(nInput, nInput + nOutput):
bufferH.append(np.empty(context.get_binding_shape(i), dtype=trt.nptype(engine.get_binding_dtype(i))))
bufferD = []
for i in range(nInput + nOutput):
bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1])
for i in range(nInput):
cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
context.execute_v2(bufferD)
for i in range(nInput, nInput + nOutput):
cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost)
# warm up
for i in range(2):
context.execute_v2(bufferD)
# test infernece time
t0 = time_ns()
for i in range(2):
context.execute_v2(bufferD)
t1 = time_ns()
timePerInference = (t1 - t0) / 1000 / 1000 / 2
indexEncoderOut = engine.get_binding_index('encoder_out')
indexEncoderOutLens = engine.get_binding_index('encoder_out_lens')
check0 = check(bufferH[indexEncoderOut], ioData['encoder_out'], True, 5e-5)
check1 = check(bufferH[indexEncoderOutLens], np.sum(ioData['encoder_out_lens'].astype(np.int32), axis=2)[:, 0], True)
string = "%4d,%4d,%8.3f,%9.3e,%9.3e,%9.3e,%9.3e,%9.3e, %s" % (batchSize, sequenceLength, timePerInference, batchSize * sequenceLength / timePerInference * 1000, check0[1], check0[2], check1[1], check1[2], "Good" if check0[1] < 3.5e-2 and check0[2] < 2e-3 and check1[2] < 1e-1 else "Bad")
print(string)
f.write(string + "\n")
for i in range(nInput + nOutput):
cudart.cudaFree(bufferD[i])
#-------------------------------------------------------------------------------
def testDecoder():
print("Test Decoder Part!")
with open(decoderScoreFile, 'w') as f:
if os.path.isfile(decoderPlanFile):
with open(decoderPlanFile, 'rb') as decoderF:
engine = trt.Runtime(logger).deserialize_cuda_engine(decoderF.read())
if engine is None:
print("Failed loading %s" % decoderPlanFile)
return
print("Succeeded loading %s" % decoderPlanFile)
else:
print("Failed finding %s" % decoderPlanFile)
return
nInput = np.sum([engine.binding_is_input(i) for i in range(engine.num_bindings)])
nOutput = engine.num_bindings - nInput
context = engine.create_execution_context()
print(tableHead) # for standard output
for ioFile in sorted(glob(dataFilePath + "./decoder-*.npz")):
ioData = np.load(ioFile)
encoder_out = ioData['encoder_out']
encoder_out_lens = ioData['encoder_out_lens']
hyps_pad_sos_eos = ioData['hyps_pad_sos_eos']
hyps_lens_sos = ioData['hyps_lens_sos']
ctc_score = ioData['ctc_score']
batchSize, sequenceLength, _ = encoder_out.shape
#if batchSize > 16 or sequenceLength > 256:
# continue
context.set_binding_shape(0, encoder_out.shape)
context.set_binding_shape(1, encoder_out_lens.shape)
context.set_binding_shape(2, hyps_pad_sos_eos.shape)
context.set_binding_shape(3, hyps_lens_sos.shape)
context.set_binding_shape(4, ctc_score.shape)
#for i in range(nInput + nOutput):
# print("Input ->" if engine.binding_is_input(i) else "Output->", engine.get_binding_dtype(i), engine.get_binding_shape(i), context.get_binding_shape(i), engine.get_binding_dtype(i), engine.get_binding_name(i))
#print("Finish all input binding: %s"%context.all_binding_shapes_specified)
bufferH = []
bufferH.append(encoder_out.astype(np.float32).reshape(-1))
bufferH.append(encoder_out_lens.astype(np.int32).reshape(-1))
bufferH.append(hyps_pad_sos_eos.astype(np.int32).reshape(-1))
bufferH.append(hyps_lens_sos.astype(np.int32).reshape(-1))
bufferH.append(ctc_score.astype(np.float32).reshape(-1))
for i in range(nInput, nInput + nOutput):
bufferH.append(np.empty(context.get_binding_shape(i), dtype=trt.nptype(engine.get_binding_dtype(i))))
bufferD = []
for i in range(nInput + nOutput):
bufferD.append(cudart.cudaMalloc(bufferH[i].nbytes)[1])
for i in range(nInput):
cudart.cudaMemcpy(bufferD[i], bufferH[i].ctypes.data, bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyHostToDevice)
context.execute_v2(bufferD)
for i in range(nInput, nInput + nOutput):
cudart.cudaMemcpy(bufferH[i].ctypes.data, bufferD[i], bufferH[i].nbytes, cudart.cudaMemcpyKind.cudaMemcpyDeviceToHost)
# warm up
for i in range(10):
context.execute_v2(bufferD)
# test infernece time
t0 = time_ns()
for i in range(30):
context.execute_v2(bufferD)
t1 = time_ns()
timePerInference = (t1 - t0) / 1000 / 1000 / 30
indexDecoderOut = engine.get_binding_index('decoder_out')
indexBestIndex = engine.get_binding_index('best_index')
check0 = check(
bufferH[indexDecoderOut],
ioData['decoder_out'],
True,
)
check1 = check(bufferH[indexBestIndex], ioData['best_index'], True)
string = "%4d,%4d,%8.3f,%9.3e,%9.3e,%9.3e,%9.3e,%9.3e, %s" % (batchSize, sequenceLength, timePerInference, batchSize * sequenceLength / timePerInference * 1000, check0[1], check0[2], check1[1], check1[2], "Good" if check0[1] < 4e-1 and check0[2] < 2e-4 and check1[2] < 1e-1 else "Bad")
print(string)
f.write(string + "\n")
for i in range(nInput + nOutput):
cudart.cudaFree(bufferD[i])
if __name__ == "__main__":
testEncoder()
testDecoder()
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/testEncoderAndDecoder.py |
import os
import ctypes
import numpy as np
#from time import time_ns
import tensorrt as trt
import pycuda.autoinit
import pycuda.driver as cuda
useFile = False
ipnutDataFile = '/workspace/data/encoder-16-64.npz'
soFilePath = './Mask.so'
epsilon = 1e-6
negInf = -6e6
np.random.seed(97)
npToTRT = {np.int8:trt.int8,np.float16:trt.float16,np.int32:trt.int32,np.float32:trt.float32}
npToPFT = {np.int8:trt.PluginFieldType.INT8,np.float16:trt.PluginFieldType.FLOAT16,
np.int32:trt.PluginFieldType.INT32,np.float32:trt.PluginFieldType.FLOAT32}
def check(a, b, weak = False):
if weak:
return np.all( np.abs(a - b) < epsilon)
else:
return np.all( a == b )
def maskCPU(bufferHList):
input0 = bufferHList[0]
input1 = bufferHList[1]
b = input0.shape[-0]
t4 = input0.shape[1] // 4 - 1
output0 = np.zeros([b,1,1,t4],dtype=np.float32) + negInf
output1 = np.zeros([b,1,1,t4],dtype=np.float32)
for i in range(b):
output0[i,0,0,:input1[i]] = 0
output1[i,0,0,:input1[i]] = 1
return output0, output1
def getMaskPlugin():
for c in trt.get_plugin_registry().plugin_creator_list:
#print(c.name)
if c.name == 'Mask':
return c.create_plugin(c.name, trt.PluginFieldCollection([]))
return None
def run(nBS,nSL):
testCase = "test<bs=%d,sl=%d>"%(nBS,nSL)
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
ctypes.cdll.LoadLibrary(soFilePath)
builder = trt.Builder(logger)
network = builder.create_network(1<<0)
config = builder.create_builder_config()
config.max_workspace_size = 6 << 30
config.flags = 0 #1<<int(trt.BuilderFlag.FP16)
inputTensorList = []
inputTensorList.append( network.add_input('inputT0', trt.float32, [-1,-1,80]) )
inputTensorList.append( network.add_input('inputT1', trt.int32, [-1]) )
profile = builder.create_optimization_profile()
profile.set_shape('inputT0',[1,16,80],[4,64,80],[16,256,80])
profile.set_shape('inputT1',[1],[4],[16])
config.add_optimization_profile(profile)
pluginLayer = network.add_plugin_v2(inputTensorList, getMaskPlugin())
pluginLayer.get_output(0).dtype = trt.float32 #trt.float16
network.mark_output(pluginLayer.get_output(0))
network.mark_output(pluginLayer.get_output(1))
engineString = builder.build_serialized_network(network, config)
engine = trt.Runtime(logger).deserialize_cuda_engine(engineString)
context = engine.create_execution_context()
context.set_binding_shape(0,[nBS,nSL,80])
context.set_binding_shape(1,[nBS])
print("Binding all? %s"%(["No","Yes"][int(context.all_binding_shapes_specified)]))
stream = cuda.Stream()
nInput = np.sum([ engine.binding_is_input(i) for i in range(engine.num_bindings) ])
nOutput = engine.num_bindings - nInput
for i in range(engine.num_bindings):
print("input ->" if engine.binding_is_input(i) else "output->",engine.get_binding_dtype(i),engine.get_binding_shape(i),context.get_binding_shape(i))
bufferH = []
bufferH.append( np.random.rand(nBS,nSL,80).astype(np.float32).reshape(nBS,nSL,80) )
bufferH.append( np.arange(1,1+nBS).astype(np.int32) )
bufferH.append(np.empty(context.get_binding_shape(2),dtype=trt.nptype(engine.get_binding_dtype(2))))
bufferH.append(np.empty(context.get_binding_shape(3),dtype=trt.nptype(engine.get_binding_dtype(3))))
bufferD = []
for i in range(engine.num_bindings):
bufferD.append( cuda.mem_alloc(bufferH[i].nbytes) )
for i in range(nInput):
cuda.memcpy_htod_async(bufferD[i], np.ascontiguousarray(bufferH[i].reshape(-1)), stream)
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
for i in range(nOutput):
cuda.memcpy_dtoh_async(bufferH[nInput+i], bufferD[nInput+i], stream)
stream.synchronize()
for i in range(nInput):
temp = bufferH[i]
print("inputH%d"%i, temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
print(temp)
for i in range(nOutput):
temp = bufferH[nInput+i]
print("outputH%d"%i, temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
print(temp)
print("check result:")
temp1 = bufferH[-1]
temp2 = maskCPU(bufferH[:2])
print(check(temp1,temp2,True), "max diff=%f"%(np.max(np.abs(temp1 - temp2))) )
if __name__ == '__main__':
os.system("rm -f ./*.trt")
np.set_printoptions(precision = 4, linewidth = 200, suppress = True)
#cuda.Device(0).make_context()
run(16,16)
#cuda.Context.pop()
#print("test all finish!")
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/MaskPlugin-1output/testMaskPlugin.py |
import os
import ctypes
import numpy as np
#from time import time_ns
import tensorrt as trt
import pycuda.autoinit
import pycuda.driver as cuda
useFile = False
ipnutDataFile = '/workspace/data/encoder-16-64.npz'
soFilePath = './Mask.so'
epsilon = 1e-6
negInf = -6e6
np.random.seed(97)
npToTRT = {np.int8:trt.int8,np.float16:trt.float16,np.int32:trt.int32,np.float32:trt.float32}
npToPFT = {np.int8:trt.PluginFieldType.INT8,np.float16:trt.PluginFieldType.FLOAT16,
np.int32:trt.PluginFieldType.INT32,np.float32:trt.PluginFieldType.FLOAT32}
def check(a, b, weak = False):
if weak:
return np.all( np.abs(a - b) < epsilon)
else:
return np.all( a == b )
def maskCPU(bufferHList):
input0 = bufferHList[0]
input1 = bufferHList[1]
b = input0.shape[-0]
t4 = input0.shape[1] // 4 - 1
output0 = np.zeros([b,1,1,t4],dtype=np.float32) + negInf
output1 = np.zeros([b,1,1,t4],dtype=np.float32)
for i in range(b):
output0[i,0,0,:input1[i]] = 0
output1[i,0,0,:input1[i]] = 1
return output0, output1
def getMaskPlugin():
for c in trt.get_plugin_registry().plugin_creator_list:
#print(c.name)
if c.name == 'Mask':
return c.create_plugin(c.name, trt.PluginFieldCollection([]))
return None
def run(nBS,nSL):
testCase = "test<bs=%d,sl=%d>"%(nBS,nSL)
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
ctypes.cdll.LoadLibrary(soFilePath)
builder = trt.Builder(logger)
network = builder.create_network(1<<0)
config = builder.create_builder_config()
config.max_workspace_size = 6 << 30
config.flags = 0 #1<<int(trt.BuilderFlag.FP16)
inputTensorList = []
inputTensorList.append( network.add_input('inputT0', trt.float32, [-1,-1,80]) )
inputTensorList.append( network.add_input('inputT1', trt.int32, [-1]) )
profile = builder.create_optimization_profile()
profile.set_shape('inputT0',[1,16,80],[4,64,80],[16,256,80])
profile.set_shape('inputT1',[1],[4],[16])
config.add_optimization_profile(profile)
pluginLayer = network.add_plugin_v2(inputTensorList, getMaskPlugin())
pluginLayer.get_output(0).dtype = trt.float32 #trt.float16
network.mark_output(pluginLayer.get_output(0))
network.mark_output(pluginLayer.get_output(1))
engineString = builder.build_serialized_network(network, config)
engine = trt.Runtime(logger).deserialize_cuda_engine(engineString)
context = engine.create_execution_context()
context.set_binding_shape(0,[nBS,nSL,80])
context.set_binding_shape(1,[nBS])
print("Binding all? %s"%(["No","Yes"][int(context.all_binding_shapes_specified)]))
stream = cuda.Stream()
nInput = np.sum([ engine.binding_is_input(i) for i in range(engine.num_bindings) ])
nOutput = engine.num_bindings - nInput
for i in range(engine.num_bindings):
print("input ->" if engine.binding_is_input(i) else "output->",engine.get_binding_dtype(i),engine.get_binding_shape(i),context.get_binding_shape(i))
bufferH = []
bufferH.append( np.random.rand(nBS,nSL,80).astype(np.float32).reshape(nBS,nSL,80) )
bufferH.append( np.arange(1,1+nBS).astype(np.int32) )
bufferH.append(np.empty(context.get_binding_shape(2),dtype=trt.nptype(engine.get_binding_dtype(2))))
bufferH.append(np.empty(context.get_binding_shape(3),dtype=trt.nptype(engine.get_binding_dtype(3))))
bufferD = []
for i in range(engine.num_bindings):
bufferD.append( cuda.mem_alloc(bufferH[i].nbytes) )
for i in range(nInput):
cuda.memcpy_htod_async(bufferD[i], np.ascontiguousarray(bufferH[i].reshape(-1)), stream)
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
for i in range(nOutput):
cuda.memcpy_dtoh_async(bufferH[nInput+i], bufferD[nInput+i], stream)
stream.synchronize()
for i in range(nInput):
temp = bufferH[i]
print("inputH%d"%i, temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
print(temp)
for i in range(nOutput):
temp = bufferH[nInput+i]
print("outputH%d"%i, temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
print(temp)
print("check result:")
temp1 = bufferH[-1]
temp2 = maskCPU(bufferH[:2])
print(check(temp1,temp2,True), "max diff=%f"%(np.max(np.abs(temp1 - temp2))) )
if __name__ == '__main__':
os.system("rm -f ./*.trt")
np.set_printoptions(precision = 4, linewidth = 200, suppress = True)
#cuda.Device(0).make_context()
run(16,16)
#cuda.Context.pop()
#print("test all finish!")
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/MaskPlugin-2output/testMaskPlugin.py |
import os
import ctypes
import numpy as np
from time import time_ns
import tensorrt as trt
import pycuda.autoinit
import pycuda.driver as cuda
useFile = False
ipnutDataFile = './layerNormIO-bs64.npz'
soFilePath = './LayerNorm.so'
nBS = 1024
nSL = 256
nEmbedding = 256
nTime = 100
epsilon = 1e-6
np.random.seed(97)
npToTRT = {np.int8:trt.int8,np.float16:trt.float16,np.int32:trt.int32,np.float32:trt.float32}
npToPFT = {np.int8:trt.PluginFieldType.INT8,np.float16:trt.PluginFieldType.FLOAT16,
np.int32:trt.PluginFieldType.INT32,np.float32:trt.PluginFieldType.FLOAT32}
def check(a, b, weak = False):
if weak:
return np.all( np.abs(a - b) < epsilon)
else:
return np.all( a == b )
def layerNormCPU(bufferH):
_x,b,a = bufferH
nEmbed = bufferH[0].shape[2]
_0 = np.mean(_x,2)[:,:,np.newaxis]
_1 = _x - _0
_2 = _1 * _1
_3 = np.mean(_2,2)[:,:,np.newaxis]
_4 = np.array(1e-12,dtype=np.float32)
_5 = _4.reshape(1,1,1)
_6 = _3 + _5
_7 = np.sqrt(_6)
_8 = 1 / _7 # 1/sqrt(...)
_9 = b
_10 = _9.reshape(1,1,nEmbed)
_11 = _8 * _10 # b/sqrt(...)
_12 = _0 * _11 # bμ/sqrt(...)
_13 = a
_14 = _13.reshape(1,1,nEmbed)
_15 = _14 - _12 # a-bμ/sqrt(...)
_16 = _x * _11 # bx/sqrt(...)
_17 = _15 + _16 # b(x-μ)/sqrt(...)+a
_18 = _17.reshape(bufferH[0].shape[0],bufferH[0].shape[1],bufferH[0].shape[2])
return _18
def testLayerNormCPU():
print("test LayerNormCPU!")
bufferH = []
io = np.load(ipnutDataFile)
bufferH.append( io['encoder1_inputs:0'] )
bufferH.append( io['(Unnamed Layer* 9) [Constant]_output'] )
bufferH.append( io['(Unnamed Layer* 13) [Constant]_output'] )
temp1 = layerNormCPU(bufferH)
print( 'outputCPU: %s,SumAbs=%.5e,Var=%.5f,Max=%.5f,Min=%.5f,SAD=%.5f'%( \
str(temp1.shape),np.sum(abs(temp1)),np.var(temp1),np.max(temp1),np.min(temp1),np.sum(np.abs(np.diff(temp1.reshape(-1)))) ))
#print(temp1)
temp2 = io['seq2seq/encoder_1/layer_0/multi_head/conv1d/conv1d/ExpandDims:0']
print( 'outputRef: %s,SumAbs=%.5e,Var=%.5f,Max=%.5f,Min=%.5f,SAD=%.5f'%( \
str(temp2.shape),np.sum(abs(temp2)),np.var(temp2),np.max(temp2),np.min(temp2),np.sum(np.abs(np.diff(temp2.reshape(-1)))) ))
#print(temp2)
print("check result:")
print(check( temp1, temp2, True ))
#temp = temp1 - temp2
#print("diff", temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
#print(temp)
print("test layerNormCPU finish!")
def getLayerNormPlugin():
for c in trt.get_plugin_registry().plugin_creator_list:
#print(c.name)
if c.name == 'LayerNorm':
return c.create_plugin(c.name, trt.PluginFieldCollection([]))
return None
def run():
testCase = "test<fp%s,bs=%d,sl=%d,nEmbed=%d>"%(['32','16'][0],nBS,nSL,nEmbedding)
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
ctypes.cdll.LoadLibrary(soFilePath)
builder = trt.Builder(logger)
network = builder.create_network(1<<0)
config = builder.create_builder_config()
config.max_workspace_size = 6 << 30
config.flags = [0,1<<int(trt.BuilderFlag.FP16)][0]
inputTensorList = []
inputTensorList.append( network.add_input('inputT', trt.float32, [-1,-1,256]) )
inputTensorList.append( network.add_input('inputB', trt.float32, [256]) )
inputTensorList.append( network.add_input('inputA', trt.float32, [256]) )
profile = builder.create_optimization_profile()
profile.set_shape('inputT',[1,4,256],[1024,256,256],[1024,256,256])
config.add_optimization_profile(profile)
pluginLayer = network.add_plugin_v2(inputTensorList, getLayerNormPlugin())
pluginLayer.get_output(0).dtype = [trt.float32,trt.float16][0]
network.mark_output(pluginLayer.get_output(0))
engine = builder.build_engine(network, config)
context = engine.create_execution_context()
context.set_binding_shape(0,[nBS,nSL,nEmbedding])
context.set_binding_shape(1,[nEmbedding])
context.set_binding_shape(2,[nEmbedding])
print("Binding all? %s"%(["No","Yes"][int(context.all_binding_shapes_specified)]))
stream = cuda.Stream()
nInput = np.sum([ engine.binding_is_input(i) for i in range(engine.num_bindings) ])
nOutput = engine.num_bindings - nInput
for i in range(engine.num_bindings):
print("input ->" if engine.binding_is_input(i) else "output->",engine.get_binding_dtype(i),engine.get_binding_shape(i),context.get_binding_shape(i))
bufferH = []
bufferH.append( np.random.rand(nBS,nSL,nEmbedding).astype(np.float32).reshape(nBS,nSL,nEmbedding) * 2 - 1)
bufferH.append( np.ones(nEmbedding).astype(np.float32) )
bufferH.append( np.zeros(nEmbedding).astype(np.float32) )
bufferH.append(np.empty(context.get_binding_shape(3),dtype=trt.nptype(engine.get_binding_dtype(3))))
bufferD = []
for i in range(engine.num_bindings):
bufferD.append( cuda.mem_alloc(bufferH[i].nbytes) )
for i in range(nInput):
cuda.memcpy_htod_async(bufferD[i], np.ascontiguousarray(bufferH[i].reshape(-1)), stream)
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
for i in range(nOutput):
cuda.memcpy_dtoh_async(bufferH[nInput+i], bufferD[nInput+i], stream)
stream.synchronize()
for i in range(nInput):
temp = bufferH[i]
print("inputH%d"%i, temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
print(temp.reshape(-1)[:10])
#print(temp)
for i in range(nOutput):
temp = bufferH[nInput+i]
print("outputH%d"%i, temp.shape,np.sum(abs(temp)),np.var(temp),np.max(temp),np.min(temp),np.sum(np.abs(np.diff(temp.reshape(-1)))))
#print(temp)
for i in range(10):
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
time0 = time_ns()
for i in range(nTime):
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
time1 = time_ns()
print(testCase+"average %fms per inference\n"%((time1-time0)/nTime/1000000))
print("check result:")
temp1 = bufferH[-1]
temp2 = layerNormCPU(bufferH[:3])
print(check(temp1,temp2,True), "max diff=%f"%(np.max(np.abs(temp1 - temp2))) )
if __name__ == '__main__':
os.system("rm -f ./*.trt")
np.set_printoptions(precision = 4, linewidth = 200, suppress = True)
run()
#print("test all finish!")
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/LayerNormPlugin/testLayerNormPlugin.py |
import os
import ctypes
from glob import glob
from time import time
import numpy as np
import tensorrt as trt
import pycuda.autoinit
import pycuda.driver as cuda
useDataFromFile = True
ipnutDataFile = './output.npz'
parameterFile = './para.npz'
soFilePath = './Attention.so'
nTime = 30
nHead = 4#8or4
nDimPerHead = 64#64or32
nHDim = nHead * nDimPerHead
seq = 15
np.random.seed(97)
npToTRT = {np.int8:trt.int8,np.float16:trt.float16,np.int32:trt.int32,np.float32:trt.float32}
npToPFT = {np.int8:trt.PluginFieldType.INT8,np.float16:trt.PluginFieldType.FLOAT16,
np.int32:trt.PluginFieldType.INT32,np.float32:trt.PluginFieldType.FLOAT32}
def getAttentionPlugin(useFP16):
for c in trt.get_plugin_registry().plugin_creator_list:
#print(c.name)
if c.name == 'Attention':
# p0 = trt.PluginField("useFP16", np.array([int(useFP16)],dtype=np.int32), trt.PluginFieldType.INT32)
return c.create_plugin(c.name, trt.PluginFieldCollection([]))
return None
def buildEngine(logger,datatype):
builder = trt.Builder(logger)
network = builder.create_network(1<<0)
config = builder.create_builder_config()
config.max_workspace_size = 6 << 30
config.flags = [0,1<<int(trt.BuilderFlag.FP16)][int(datatype == np.float16)]
inputTensorList = []
inputTensorList.append( network.add_input('q_x', npToTRT[datatype], [-1,-1,nHDim]) )
inputTensorList.append( network.add_input('pos_emb', npToTRT[datatype], [-1,-1,nHDim]) )
inputTensorList.append( network.add_input('mask', npToTRT[datatype], [-1, 1, -1]) )
inputTensorList.append( network.add_input('pos_bias_u', npToTRT[datatype], [nHead,nDimPerHead]) )
inputTensorList.append( network.add_input('pos_bias_v', npToTRT[datatype], [nHead,nDimPerHead]) )
inputTensorList.append( network.add_input('linear_qkv_weight', npToTRT[datatype], [3, nHDim,nHDim]) )
inputTensorList.append( network.add_input('linear_q_bias', npToTRT[datatype], [nHDim]) )
inputTensorList.append( network.add_input('linear_k_bias', npToTRT[datatype], [nHDim]) )
inputTensorList.append( network.add_input('linear_v_bias', npToTRT[datatype], [nHDim]) )
inputTensorList.append( network.add_input('linear_out_weight', npToTRT[datatype], [nHDim,nHDim]) )
inputTensorList.append( network.add_input('linear_out_bias', npToTRT[datatype], [nHDim]) )
inputTensorList.append( network.add_input('linear_pos_weight', npToTRT[datatype], [nHDim,nHDim]) )
profile = builder.create_optimization_profile()
profile.set_shape('q_x', [1,seq,nHDim],[16,seq,nHDim],[32,seq,nHDim])
profile.set_shape('pos_emb',[1,seq,nHDim],[1,seq,nHDim],[1,seq,nHDim])
profile.set_shape('mask', [1,1,seq], [16,1,seq], [32,1,seq])
config.add_optimization_profile(profile)
pluginLayer = network.add_plugin_v2(inputTensorList, getAttentionPlugin(int(datatype == np.float16)))
pluginLayer.get_output(0).dtype = [trt.float32,trt.float16][int(datatype == np.float16)]
network.mark_output(pluginLayer.get_output(0))
return builder.build_engine(network, config)
def run(datatype,batchSize,sequenceLength):
testCase = "test<bs=%d,sl=%d,fp%s>"%(batchSize,sequenceLength,['32','16'][int(datatype == np.float16)])
#print(testCase+"start!")
logger = trt.Logger(trt.Logger.ERROR)
trt.init_libnvinfer_plugins(logger, '')
ctypes.cdll.LoadLibrary(soFilePath)
trtFile = 'engine-fp' + ['32','16'][int(datatype == np.float16)] +'.trt'
# if os.path.isfile(trtFile):
# with open(trtFile, 'rb') as f:
# engineStr = f.read()
# engine = trt.Runtime(logger).deserialize_cuda_engine(engineStr)
# if engine == None:
# print("Failed loading engine!")
# return
# print("Succeeded loading engine!")
# else:
engine = buildEngine(logger,datatype)
if engine == None:
print("Failed building engine!")
return
print("succeeded building engine!")
with open(trtFile, 'wb') as f:
f.write( engine.serialize() )
context = engine.create_execution_context()
context.set_binding_shape( 0,[batchSize,sequenceLength,nHDim])
context.set_binding_shape( 1,[1,sequenceLength,nHDim])
context.set_binding_shape( 2,[batchSize,1,sequenceLength])
print("Binding all? %s"%(["No","Yes"][int(context.all_binding_shapes_specified)]))
stream = cuda.Stream()
nInput = np.sum([ engine.binding_is_input(i) for i in range(engine.num_bindings) ])
nOutput = engine.num_bindings - nInput
for i in range(engine.num_bindings):
print("input ->" if engine.binding_is_input(i) else "output->",engine.get_binding_dtype(i),engine.get_binding_shape(i),context.get_binding_shape(i))
bufferH = []
data = np.load(ipnutDataFile)
para = np.load(parameterFile)
if useDataFromFile:
bufferH.append(np.ascontiguousarray( data['856'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( data['603'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( data['613'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.pos_bias_u'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.pos_bias_v'].astype(datatype).reshape(-1) ))
q_weight = para['encoder.encoders.1.self_attn.linear_q.weight']
k_weight = para['encoder.encoders.1.self_attn.linear_k.weight']
v_weight = para['encoder.encoders.1.self_attn.linear_v.weight']
qkv_weight = np.stack([q_weight, k_weight, v_weight])
bufferH.append(np.ascontiguousarray( qkv_weight.astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_q.bias'].astype(datatype).reshape(-1) ))
# bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_k.weight'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_k.bias'].astype(datatype).reshape(-1) ))
# bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_v.weight'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_v.bias'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_out.weight'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_out.bias'].astype(datatype).reshape(-1) ))
bufferH.append(np.ascontiguousarray( para['encoder.encoders.1.self_attn.linear_pos.weight'].astype(datatype).reshape(-1) ))
print("test")
else:
bufferH.append(np.ascontiguousarray( np.random.rand(batchSize,sequenceLength,nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(batchSize,sequenceLength,nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(batchSize,sequenceLength,nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(batchSize,sequenceLength,nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.ones([batchSize,1,sequenceLength])))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim*nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim*nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim*nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim*nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.ascontiguousarray( np.random.rand(nHDim*nHDim).astype(datatype).reshape(-1)*2-1 ))
bufferH.append(np.empty(context.get_binding_shape(12),dtype=trt.nptype(engine.get_binding_dtype(12))))
bufferD = []
for i in range(engine.num_bindings):
bufferD.append( cuda.mem_alloc(bufferH[i].nbytes) )
for i in range(nInput):
cuda.memcpy_htod_async(bufferD[i], bufferH[i], stream)
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
time0 = time()
for i in range(nTime):
context.execute_async_v2(bufferD, stream.handle)
stream.synchronize()
time1 = time()
print(testCase+"average %fms per inference\n"%((time1-time0)/nTime*1000))
for i in range(nOutput):
cuda.memcpy_dtoh_async(bufferH[nInput+i], bufferD[nInput+i], stream)
stream.synchronize()
print("res=")
#print(bufferH[-1])
temp1 = bufferH[-1]
data = np.load(ipnutDataFile)
temp4 = data["964"]
tt = np.max(np.abs(temp1-temp4))
print("test", tt)
'''
print("ref=")
print(data['att'])
'''
#print(testCase+"finish!")
if __name__ == '__main__':
#os.system("rm -f ./*.trt")
np.set_printoptions(precision = 4, linewidth = 200, suppress = True)
#cuda.Device(0).make_context()
run(np.float32,16,seq)
'''
run(np.float32,16,256)
run(np.float32,16,512)
run(np.float32,32,128)
run(np.float32,32,256)
run(np.float32,32,512)
'''
'''
run(np.float16,16,128)
run(np.float16,16,256)
run(np.float16,16,512)
run(np.float16,32,128)
run(np.float16,32,256)
run(np.float16,32,512)
'''
#cuda.Context.pop()
#print("test all finish!")
| trt-samples-for-hackathon-cn-master | Hackathon2022/code/AttentionPlugin/testAttentionPlugin.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.mlsd import MLSDdetector
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
apply_mlsd = MLSDdetector()
model = create_model('./models/cldm_v15.yaml').cpu()
model.load_state_dict(load_state_dict('./models/control_sd15_mlsd.pth', location='cuda'))
model = model.cuda()
ddim_sampler = DDIMSampler(model)
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, value_threshold, distance_threshold):
with torch.no_grad():
input_image = HWC3(input_image)
detected_map = apply_mlsd(resize_image(input_image, detect_resolution), value_threshold, distance_threshold)
detected_map = HWC3(detected_map)
img = resize_image(input_image, image_resolution)
H, W, C = img.shape
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
control = torch.stack([control for _ in range(num_samples)], dim=0)
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
if seed == -1:
seed = random.randint(0, 65535)
seed_everything(seed)
if config.save_memory:
model.low_vram_shift(is_diffusing=False)
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
shape = (4, H // 8, W // 8)
if config.save_memory:
model.low_vram_shift(is_diffusing=True)
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
shape, cond, verbose=False, eta=eta,
unconditional_guidance_scale=scale,
unconditional_conditioning=un_cond)
if config.save_memory:
model.low_vram_shift(is_diffusing=False)
x_samples = model.decode_first_stage(samples)
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
results = [x_samples[i] for i in range(num_samples)]
return [255 - cv2.dilate(detected_map, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)] + results
block = gr.Blocks().queue()
with block:
with gr.Row():
gr.Markdown("## Control Stable Diffusion with Hough Line Maps")
with gr.Row():
with gr.Column():
input_image = gr.Image(source='upload', type="numpy")
prompt = gr.Textbox(label="Prompt")
run_button = gr.Button(label="Run")
with gr.Accordion("Advanced options", open=False):
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
detect_resolution = gr.Slider(label="Hough Resolution", minimum=128, maximum=1024, value=512, step=1)
value_threshold = gr.Slider(label="Hough value threshold (MLSD)", minimum=0.01, maximum=2.0, value=0.1, step=0.01)
distance_threshold = gr.Slider(label="Hough distance threshold (MLSD)", minimum=0.01, maximum=20.0, value=0.1, step=0.01)
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
eta = gr.Number(label="eta (DDIM)", value=0.0)
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
n_prompt = gr.Textbox(label="Negative Prompt",
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
with gr.Column():
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, value_threshold, distance_threshold]
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
block.launch(server_name='0.0.0.0')
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_hough2image.py |
path_sd15 = './models/v1-5-pruned.ckpt'
path_sd15_with_control = './models/control_sd15_openpose.pth'
path_input = './models/anything-v3-full.safetensors'
path_output = './models/control_any3_openpose.pth'
import os
assert os.path.exists(path_sd15), 'Input path_sd15 does not exists!'
assert os.path.exists(path_sd15_with_control), 'Input path_sd15_with_control does not exists!'
assert os.path.exists(path_input), 'Input path_input does not exists!'
assert os.path.exists(os.path.dirname(path_output)), 'Output folder not exists!'
import torch
from share import *
from cldm.model import load_state_dict
sd15_state_dict = load_state_dict(path_sd15)
sd15_with_control_state_dict = load_state_dict(path_sd15_with_control)
input_state_dict = load_state_dict(path_input)
def get_node_name(name, parent_name):
if len(name) <= len(parent_name):
return False, ''
p = name[:len(parent_name)]
if p != parent_name:
return False, ''
return True, name[len(parent_name):]
keys = sd15_with_control_state_dict.keys()
final_state_dict = {}
for key in keys:
is_first_stage, _ = get_node_name(key, 'first_stage_model')
is_cond_stage, _ = get_node_name(key, 'cond_stage_model')
if is_first_stage or is_cond_stage:
final_state_dict[key] = input_state_dict[key]
continue
p = sd15_with_control_state_dict[key]
is_control, node_name = get_node_name(key, 'control_')
if is_control:
sd15_key_name = 'model.diffusion_' + node_name
else:
sd15_key_name = key
if sd15_key_name in input_state_dict:
p_new = p + input_state_dict[sd15_key_name] - sd15_state_dict[sd15_key_name]
# print(f'Offset clone from [{sd15_key_name}] to [{key}]')
else:
p_new = p
# print(f'Direct clone to [{key}]')
final_state_dict[key] = p_new
torch.save(final_state_dict, path_output)
print('Transferred model saved at ' + path_output)
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tool_transfer_control.py |
save_memory = False
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/config.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.midas import MidasDetector
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
apply_midas = MidasDetector()
model = create_model('./models/cldm_v15.yaml').cpu()
model.load_state_dict(load_state_dict('./models/control_sd15_depth.pth', location='cuda'))
model = model.cuda()
ddim_sampler = DDIMSampler(model)
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
with torch.no_grad():
input_image = HWC3(input_image)
detected_map, _ = apply_midas(resize_image(input_image, detect_resolution))
detected_map = HWC3(detected_map)
img = resize_image(input_image, image_resolution)
H, W, C = img.shape
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
control = torch.stack([control for _ in range(num_samples)], dim=0)
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
if seed == -1:
seed = random.randint(0, 65535)
seed_everything(seed)
if config.save_memory:
model.low_vram_shift(is_diffusing=False)
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
shape = (4, H // 8, W // 8)
if config.save_memory:
model.low_vram_shift(is_diffusing=True)
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
shape, cond, verbose=False, eta=eta,
unconditional_guidance_scale=scale,
unconditional_conditioning=un_cond)
if config.save_memory:
model.low_vram_shift(is_diffusing=False)
x_samples = model.decode_first_stage(samples)
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
results = [x_samples[i] for i in range(num_samples)]
return [detected_map] + results
block = gr.Blocks().queue()
with block:
with gr.Row():
gr.Markdown("## Control Stable Diffusion with Depth Maps")
with gr.Row():
with gr.Column():
input_image = gr.Image(source='upload', type="numpy")
prompt = gr.Textbox(label="Prompt")
run_button = gr.Button(label="Run")
with gr.Accordion("Advanced options", open=False):
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
detect_resolution = gr.Slider(label="Depth Resolution", minimum=128, maximum=1024, value=384, step=1)
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
eta = gr.Number(label="eta (DDIM)", value=0.0)
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
n_prompt = gr.Textbox(label="Negative Prompt",
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
with gr.Column():
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
block.launch(server_name='0.0.0.0')
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_depth2image.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
import os
import tensorrt as trt
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.canny import CannyDetector
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
from ldm.util import log_txt_as_img, exists, instantiate_from_config
class hackathon():
def initialize(self):
self.apply_canny = CannyDetector()
self.model = create_model('./models/cldm_v15.yaml').cpu()
self.model.load_state_dict(load_state_dict('/home/player/ControlNet/models/control_sd15_canny.pth', location='cuda'))
self.model = self.model.cuda()
self.ddim_sampler = DDIMSampler(self.model)
self.trt_logger = trt.Logger(trt.Logger.WARNING)
trt.init_libnvinfer_plugins(self.trt_logger, '')
H = 256
W = 384
control_model = self.model.control_model
if not os.path.isfile("sd_control_fp16.engine"):
x_in = torch.randn(1, 4, H//8, W //8, dtype=torch.float32).to("cuda")
h_in = torch.randn(1, 3, H, W, dtype=torch.float32).to("cuda")
t_in = torch.zeros(1, dtype=torch.int64).to("cuda")
c_in = torch.randn(1, 77, 768, dtype=torch.float32).to("cuda")
controls = control_model(x=x_in, hint=h_in, timesteps=t_in, context=c_in)
output_names = []
for i in range(13):
output_names.append("out_"+ str(i))
dynamic_table = {'x_in' : {0 : 'bs', 2 : 'H', 3 : 'W'},
'h_in' : {0 : 'bs', 2 : '8H', 3 : '8W'},
't_in' : {0 : 'bs'},
'c_in' : {0 : 'bs'}}
for i in range(13):
dynamic_table[output_names[i]] = {0 : "bs"}
torch.onnx.export(control_model,
(x_in, h_in, t_in, c_in),
"./sd_control_test.onnx",
export_params=True,
opset_version=16,
do_constant_folding=True,
keep_initializers_as_inputs=True,
input_names = ['x_in', "h_in", "t_in", "c_in"],
output_names = output_names,
dynamic_axes = dynamic_table)
os.system("trtexec --onnx=sd_control_test.onnx --saveEngine=sd_control_fp16.engine --fp16 --optShapes=x_in:1x4x32x48,h_in:1x3x256x384,t_in:1,c_in:1x77x768")
with open("./sd_control_fp16.engine", 'rb') as f:
engine_str = f.read()
control_engine = trt.Runtime(self.trt_logger).deserialize_cuda_engine(engine_str)
control_context = control_engine.create_execution_context()
control_context.set_binding_shape(0, (1, 4, H // 8, W // 8))
control_context.set_binding_shape(1, (1, 3, H, W))
control_context.set_binding_shape(2, (1,))
control_context.set_binding_shape(3, (1, 77, 768))
self.model.control_context = control_context
print("finished")
def process(self, input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, ddim_steps, guess_mode, strength, scale, seed, eta, low_threshold, high_threshold):
with torch.no_grad():
img = resize_image(HWC3(input_image), image_resolution)
H, W, C = img.shape
detected_map = self.apply_canny(img, low_threshold, high_threshold)
detected_map = HWC3(detected_map)
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
control = torch.stack([control for _ in range(num_samples)], dim=0)
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
if seed == -1:
seed = random.randint(0, 65535)
seed_everything(seed)
if config.save_memory:
self.model.low_vram_shift(is_diffusing=False)
cond = {"c_concat": [control], "c_crossattn": [self.model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [self.model.get_learned_conditioning([n_prompt] * num_samples)]}
shape = (4, H // 8, W // 8)
if config.save_memory:
self.model.low_vram_shift(is_diffusing=True)
self.model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
samples, intermediates = self.ddim_sampler.sample(ddim_steps, num_samples,
shape, cond, verbose=False, eta=eta,
unconditional_guidance_scale=scale,
unconditional_conditioning=un_cond)
if config.save_memory:
self.model.low_vram_shift(is_diffusing=False)
x_samples = self.model.decode_first_stage(samples)
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
results = [x_samples[i] for i in range(num_samples)]
return results
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/canny2image_TRT.py |
import sys
import os
assert len(sys.argv) == 3, 'Args are wrong.'
input_path = sys.argv[1]
output_path = sys.argv[2]
assert os.path.exists(input_path), 'Input model does not exist.'
assert not os.path.exists(output_path), 'Output filename already exists.'
assert os.path.exists(os.path.dirname(output_path)), 'Output path is not valid.'
import torch
from share import *
from cldm.model import create_model
def get_node_name(name, parent_name):
if len(name) <= len(parent_name):
return False, ''
p = name[:len(parent_name)]
if p != parent_name:
return False, ''
return True, name[len(parent_name):]
model = create_model(config_path='./models/cldm_v21.yaml')
pretrained_weights = torch.load(input_path)
if 'state_dict' in pretrained_weights:
pretrained_weights = pretrained_weights['state_dict']
scratch_dict = model.state_dict()
target_dict = {}
for k in scratch_dict.keys():
is_control, name = get_node_name(k, 'control_')
if is_control:
copy_k = 'model.diffusion_' + name
else:
copy_k = k
if copy_k in pretrained_weights:
target_dict[k] = pretrained_weights[copy_k].clone()
else:
target_dict[k] = scratch_dict[k].clone()
print(f'These weights are newly added: {k}')
model.load_state_dict(target_dict, strict=True)
torch.save(model.state_dict(), output_path)
print('Done.')
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/tool_add_control_sd21.py |
from share import *
import config
import cv2
import einops
import gradio as gr
import numpy as np
import torch
import random
from pytorch_lightning import seed_everything
from annotator.util import resize_image, HWC3
from annotator.uniformer import UniformerDetector
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
apply_uniformer = UniformerDetector()
model = create_model('./models/cldm_v15.yaml').cpu()
model.load_state_dict(load_state_dict('./models/control_sd15_seg.pth', location='cuda'))
model = model.cuda()
ddim_sampler = DDIMSampler(model)
def process(input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta):
with torch.no_grad():
input_image = HWC3(input_image)
detected_map = apply_uniformer(resize_image(input_image, detect_resolution))
img = resize_image(input_image, image_resolution)
H, W, C = img.shape
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
control = torch.stack([control for _ in range(num_samples)], dim=0)
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
if seed == -1:
seed = random.randint(0, 65535)
seed_everything(seed)
if config.save_memory:
model.low_vram_shift(is_diffusing=False)
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
shape = (4, H // 8, W // 8)
if config.save_memory:
model.low_vram_shift(is_diffusing=True)
model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
shape, cond, verbose=False, eta=eta,
unconditional_guidance_scale=scale,
unconditional_conditioning=un_cond)
if config.save_memory:
model.low_vram_shift(is_diffusing=False)
x_samples = model.decode_first_stage(samples)
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
results = [x_samples[i] for i in range(num_samples)]
return [detected_map] + results
block = gr.Blocks().queue()
with block:
with gr.Row():
gr.Markdown("## Control Stable Diffusion with Segmentation Maps")
with gr.Row():
with gr.Column():
input_image = gr.Image(source='upload', type="numpy")
prompt = gr.Textbox(label="Prompt")
run_button = gr.Button(label="Run")
with gr.Accordion("Advanced options", open=False):
num_samples = gr.Slider(label="Images", minimum=1, maximum=12, value=1, step=1)
image_resolution = gr.Slider(label="Image Resolution", minimum=256, maximum=768, value=512, step=64)
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
detect_resolution = gr.Slider(label="Segmentation Resolution", minimum=128, maximum=1024, value=512, step=1)
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=20, step=1)
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, randomize=True)
eta = gr.Number(label="eta (DDIM)", value=0.0)
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed')
n_prompt = gr.Textbox(label="Negative Prompt",
value='longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality')
with gr.Column():
result_gallery = gr.Gallery(label='Output', show_label=False, elem_id="gallery").style(grid=2, height='auto')
ips = [input_image, prompt, a_prompt, n_prompt, num_samples, image_resolution, detect_resolution, ddim_steps, guess_mode, strength, scale, seed, eta]
run_button.click(fn=process, inputs=ips, outputs=[result_gallery])
block.launch(server_name='0.0.0.0')
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/gradio_seg2image.py |
import numpy as np
from pytorch_fid import fid_score
from pytorch_fid.inception import InceptionV3
import cv2
import datetime
from canny2image_TRT import hackathon
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
model = InceptionV3([block_idx]).to("cuda")
def PD(base_img, new_img):
inception_feature_ref, _ = fid_score.calculate_activation_statistics([base_img], model, batch_size = 1, device="cuda")
inception_feature, _ = fid_score.calculate_activation_statistics([new_img], model, batch_size = 1, device="cuda")
pd_value = np.linalg.norm(inception_feature - inception_feature_ref)
pd_string = F"Perceptual distance to: {pd_value:.2f}"
print(pd_string)
return pd_value
scores = []
latencys = []
hk = hackathon()
hk.initialize()
for i in range(20):
path = "/home/player/pictures_croped/bird_"+ str(i) + ".jpg"
img = cv2.imread(path)
start = datetime.datetime.now().timestamp()
new_img = hk.process(img,
"a bird",
"best quality, extremely detailed",
"longbody, lowres, bad anatomy, bad hands, missing fingers",
1,
256,
20,
False,
1,
9,
2946901,
0.0,
100,
200)
end = datetime.datetime.now().timestamp()
print("time cost is: ", (end-start)*1000)
new_path = "./bird_"+ str(i) + ".jpg"
cv2.imwrite(new_path, new_img[0])
# generate the base_img by running the pytorch fp32 pipeline (origin code in canny2image_TRT.py)
# base_path = "base_img.jpg"
# score = PD(base_path, new_path)
# print("score is: ", score)
| trt-samples-for-hackathon-cn-master | Hackathon2023/controlnet/compute_score.py |
Subsets and Splits