file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/OgnBundleInspectChanges.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.
"""Node inspecting the changes made to an attribute."""
import traceback
from typing import Union
import numpy as np
import omni.graph.core as og
import omni.warp.nodes
from omni.warp.nodes.ogn.OgnBundleInspectChangesDatabase import OgnBundleInspectChangesDatabase
import warp as wp
_ATTR_NAMES_PER_PRIM_TYPE = {
"Mesh": (
"points",
"faceVertexCounts",
"faceVertexIndices",
"primvars:normals",
"primvars:st",
),
"Points": (
"points",
"widths",
),
}
# Helpers
# ------------------------------------------------------------------------------
def get_cpu_array(
attr: og.AttributeData,
read_only: bool = True,
) -> Union[np.ndarray, str]:
"""Retrieves the value of an array attribute living on the CPU."""
return attr.get_array(
on_gpu=False,
get_for_write=not read_only,
reserved_element_count=0 if read_only else attr.size(),
)
# Compute
# ------------------------------------------------------------------------------
def compute(db: OgnBundleInspectChangesDatabase) -> None:
"""Evaluates the node."""
if not db.inputs.bundle.valid or not db.outputs.bundle.valid:
return
db.outputs.bundle = db.inputs.bundle
attrs_changed = []
with db.inputs.bundle.changes() as bundle_changes:
for bundle in db.inputs.bundle.bundle.get_child_bundles():
attr = bundle.get_attribute_by_name("sourcePrimType")
prim_type = get_cpu_array(attr)
attr_names = _ATTR_NAMES_PER_PRIM_TYPE.get(prim_type)
for attr_name in attr_names:
if attr_name in attrs_changed:
continue
attr = bundle.get_attribute_by_name(attr_name)
changes = bundle_changes.get_change(attr)
if changes == og.BundleChangeType.NONE:
continue
attrs_changed.append(attr_name)
db.outputs.attrsChanged = " ".join(attrs_changed)
db.outputs.topologyChanged = db.outputs.attrsChanged != "points"
# Node Entry Point
# ------------------------------------------------------------------------------
class OgnBundleInspectChanges:
"""Node."""
@staticmethod
def compute(db: OgnBundleInspectChangesDatabase) -> None:
device = omni.warp.nodes.device_get_cuda_compute()
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.log_error(traceback.format_exc())
return
# Fire the execution for the downstream nodes.
db.outputs.execOut = og.ExecutionAttributeState.ENABLED
| 3,095 | Python | 29.058252 | 95 | 0.597738 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/props/codestr.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.
"""Property to edit the kernel's source code embedded to the node."""
from typing import (
Any,
Callable,
)
import omni.graph.core as og
import omni.ui as ui
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.widget.text_editor import TextEditor
from omni.kit.window.property.templates import HORIZONTAL_SPACING
_DIALOG_TITLE = "Kernel Editor"
_DIALOG_WIDTH = 800
_DIALOG_HEIGHT = 600
_BUTTON_WIDTH = 100
class _State:
"""State object shared across the various handlers."""
def __init__(self, layout: Any):
self.layout = layout
self.dialog = None
self.editor = None
self.code_str_attr = og.Controller.attribute(
"inputs:codeStr",
layout.node,
)
def is_read_only(self) -> bool:
return self.code_str_attr.get_upstream_connection_count() > 0
def _get_save_btn_clicked_handler(state: _State) -> Callable:
def fn():
# Trim the trailing new line character inserted by
# the text editor.
code = state.editor.text[:-1]
# Save the content into the corresponding string attribute.
assert not state.is_read_only()
og.Controller.set(state.code_str_attr, code, update_usd=True)
# Restore the title to its default state.
state.dialog.title = _DIALOG_TITLE
return fn
def _get_edit_btn_clicked_handler(state: _State) -> Callable:
def fn():
read_only = state.is_read_only()
dialog = ui.Window(
_DIALOG_TITLE,
width=_DIALOG_WIDTH,
height=_DIALOG_HEIGHT,
dockPreference=ui.DockPreference.MAIN,
)
with dialog.frame:
with ui.VStack():
state.editor = TextEditor(
syntax=TextEditor.Syntax.PYTHON,
text=og.Controller.get(state.code_str_attr),
read_only=read_only,
)
if not read_only:
with ui.HStack(height=0):
ui.Spacer()
ui.Button(
"Save",
width=_BUTTON_WIDTH,
clicked_fn=_get_save_btn_clicked_handler(state),
tooltip="Save the changes to the code",
)
# Store the dialog widget into the state to avoid having it
# not showing up due to being garbage collected.
state.dialog = dialog
return fn
def get_code_str_prop_builder(layout: Any) -> Callable:
"""Builds the function used to create the property."""
def fn(ui_prop: UsdPropertyUiEntry, *args):
state = _State(layout)
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label(
ui_prop.prop_name,
ui_prop.metadata,
{
"style": {
"alignment": ui.Alignment.RIGHT,
},
},
)
ui.Button(
"View" if state.is_read_only() else "Edit",
width=_BUTTON_WIDTH,
clicked_fn=_get_edit_btn_clicked_handler(state),
tooltip="View/edit the embedded kernel code",
)
return fn
| 3,851 | Python | 30.57377 | 88 | 0.586861 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/props/codefile.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.
"""Property to edit the file path pointing to the kernel's code."""
from typing import (
Any,
Callable,
)
import omni.ui as ui
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING
def get_code_file_prop_builder(layout: Any) -> Callable:
"""Builds the function used to create the property."""
def fn(ui_prop: UsdPropertyUiEntry, *args):
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._string_builder(
layout.compute_node_widget.stage,
ui_prop.prop_name,
ui_prop.property_type,
ui_prop.metadata,
prim_paths=(layout.node_prim_path,),
additional_label_kwargs={
"style": {
"alignment": ui.Alignment.RIGHT,
},
},
)
return fn
| 1,476 | Python | 35.924999 | 88 | 0.668022 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/props/__init__.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.
"""Properties used by the custom node UI templates.
These are built against the `omni.kit.property.usd` framework and are being
passed to the `build_fn` argument of `CustomLayoutProperty` objects.
"""
| 626 | Python | 47.230766 | 76 | 0.801917 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/props/sourcepicker.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.
"""Property to pick the source used to infer an attribute's value."""
from typing import (
Any,
Callable,
Sequence,
Tuple,
)
import omni.ui as ui
from omni.kit.property.usd.usd_attribute_model import TfTokenAttributeModel
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import HORIZONTAL_SPACING
def get_source_picker_prop_builder(
layout: Any,
sources: Sequence[str],
) -> Callable:
"""Builds the function used to create the property."""
def fn(ui_prop: UsdPropertyUiEntry, *args):
class _Model(TfTokenAttributeModel):
def _get_allowed_tokens(self, _) -> Tuple[str]:
return tuple(sources)
with ui.HStack(spacing=HORIZONTAL_SPACING):
# It is necessary to define a dummy allowed token otherwise
# the code in `UsdPropertiesWidgetBuilder._tftoken_builder()` exits
# before attempting to call our custom model.
metadata = ui_prop.metadata.copy()
metadata.update(
{
"allowedTokens": ("dummy",),
}
)
UsdPropertiesWidgetBuilder.build(
layout.compute_node_widget.stage,
ui_prop.prop_name,
metadata,
ui_prop.property_type,
prim_paths=(layout.node_prim_path,),
additional_label_kwargs={
"style": {
"alignment": ui.Alignment.RIGHT,
},
},
additional_widget_kwargs={
"model_cls": _Model,
},
)
return fn
| 2,233 | Python | 34.460317 | 88 | 0.62069 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/props/editattrs.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.
"""Property to edit the node attributes based on the kernel's parameters."""
from functools import partial
from typing import (
Any,
Callable,
Sequence,
)
import omni.graph.core as og
import omni.ui as ui
from omni.warp.nodes._impl.attributes import (
ATTR_BUNDLE_TYPE,
attr_get_name,
attr_join_name,
)
from omni.warp.nodes._impl.kernel import (
ArrayAttributeFormat,
UserAttributeDesc,
UserAttributesEvent,
deserialize_user_attribute_descs,
serialize_user_attribute_descs,
)
from omni.warp.nodes._impl.widgets.attributeeditor import AttributeEditor
_BUTTON_WIDTH = 100
class _State:
"""State object shared across the various handlers."""
def __init__(self, layout):
self.layout = layout
self.dialog = None
self.remove_attr_menu = None
def _add_user_attribute_desc(state: _State, desc: UserAttributeDesc) -> None:
data = og.Controller.get(state.layout.user_attr_descs_attr)
descs = deserialize_user_attribute_descs(data)
descs[desc.name] = desc
data = serialize_user_attribute_descs(descs)
og.Controller.set(state.layout.user_attr_descs_attr, data, update_usd=True)
def _remove_user_attribute_desc(
state: _State,
port_type: og.AttributePortType,
base_name: str,
) -> None:
data = og.Controller.get(state.layout.user_attr_descs_attr)
descs = deserialize_user_attribute_descs(data)
name = attr_join_name(port_type, base_name)
descs.pop(name, None)
data = serialize_user_attribute_descs(descs)
og.Controller.set(state.layout.user_attr_descs_attr, data, update_usd=True)
def _get_attribute_creation_handler(state: _State) -> Callable:
def fn(attr_desc: UserAttributeDesc):
if any(attr_get_name(x) == attr_desc.name for x in state.layout.node.get_attributes()):
raise RuntimeError("The attribute '{}' already exists on the node.".format(attr_desc.name))
if attr_desc.array_format == ArrayAttributeFormat.RAW:
attr_type = attr_desc.type
elif attr_desc.array_format == ArrayAttributeFormat.BUNDLE:
attr_type = ATTR_BUNDLE_TYPE
else:
raise AssertionError("Unexpected array attribute format '{}'.".format(attr_desc.array_format))
attr = og.Controller.create_attribute(
state.layout.node,
attr_desc.base_name,
attr_type,
attr_desc.port_type,
)
if attr is None:
raise RuntimeError("Failed to create the attribute '{}'.".format(attr_desc.name))
attr.is_optional_for_compute = attr_desc.optional
# Store the new attribute's description within the node's state.
_add_user_attribute_desc(state, attr_desc)
# Inform the node that a new attribute was created.
og.Controller.set(
state.layout.user_attrs_event_attr,
UserAttributesEvent.CREATED,
)
state.layout.refresh()
return fn
def _get_attribute_removal_handler(state: _State) -> Callable:
def fn(attr):
port_type = attr.get_port_type()
name = attr_get_name(attr)
if not og.Controller.remove_attribute(attr):
return
# Remove that attribute's description from the node's state.
_remove_user_attribute_desc(state, port_type, name)
# Inform the node that an existing attribute was removed.
og.Controller.set(
state.layout.user_attrs_event_attr,
UserAttributesEvent.REMOVED,
)
state.layout.refresh()
return fn
def _get_add_btn_clicked_handler(
state: _State,
supported_types: Sequence[str],
) -> Callable:
def fn():
dialog = AttributeEditor(
supported_types,
_get_attribute_creation_handler(state),
)
# Store the dialog widget into the state to avoid having it
# not showing up due to being garbage collected.
state.dialog = dialog
return fn
def _get_remove_btn_clicked_handler(state: _State) -> Callable:
def fn():
attrs = tuple(x for x in state.layout.node.get_attributes() if x.is_dynamic())
if not attrs:
return
menu = ui.Menu()
with menu:
for attr in attrs:
ui.MenuItem(
attr_get_name(attr),
triggered_fn=partial(
_get_attribute_removal_handler(state),
attr,
),
)
menu.show()
# Store the menu widget into the state to avoid having it
# not showing up due to being garbage collected.
state.remove_attr_menu = menu
return fn
def get_edit_attrs_prop_builder(
layout: Any,
supported_types: Sequence[str],
) -> Callable:
"""Builds the function used to create the property."""
def fn(*args):
state = _State(layout)
with ui.HStack():
ui.Button(
"Add +",
width=_BUTTON_WIDTH,
clicked_fn=_get_add_btn_clicked_handler(state, supported_types),
tooltip="Opens an UI to add a new attribute",
)
ui.Spacer(width=8)
ui.Button(
"Remove -",
width=_BUTTON_WIDTH,
clicked_fn=_get_remove_btn_clicked_handler(state),
tooltip="Opens a menu to remove an existing node attribute",
)
return fn
| 5,916 | Python | 28.733668 | 106 | 0.625592 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/widgets/attributeeditor.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.
"""Widget for a dialog window to author node attributes."""
from functools import partial
import omni.graph.core as og
import omni.ui as ui
from omni.kit.widget.searchfield import SearchField
from omni.warp.nodes._impl.kernel import (
ArrayAttributeFormat,
OutputArrayShapeSource,
UserAttributeDesc,
)
_DIALOG_TITLE = "Attribute Creator"
_DIALOG_PADDING = 15
_DATA_TYPE_FRAME_HEIGHT = 300
_LABEL_WIDTH = 100
_FIELD_WIDTH = 275
_DIALOG_BTNS_FRAME_HEIGHT = 20
def _add_label(title):
ui.Label(title, alignment=ui.Alignment.RIGHT, width=_LABEL_WIDTH)
ui.Spacer(width=_DIALOG_PADDING)
class AttributeEditor:
"""Editor to add/remove node attributes."""
def __init__(self, data_type_names, create_attr_callback):
self.supported_data_type_names = data_type_names
self.filtered_data_type_names = data_type_names
self.create_attr_callback = create_attr_callback
self.dialog = None
self.input_port_btn = None
self.output_port_btn = None
self.name_field = None
self.data_type_frame = None
self.selected_data_type_btn = None
self.is_array_frame = None
self.is_array_checkbox = None
self.array_format_frame = None
self.array_format_combobox = None
self.output_array_shape_source_frame = None
self.output_array_shape_source_combobox = None
self.optional_frame = None
self.optional_checkbox = None
self.error_msg_label = None
self._build()
@property
def port_type(self):
if self.input_port_btn.checked:
return og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
if self.output_port_btn.checked:
return og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT
return None
@property
def name(self):
return self.name_field.model.get_value_as_string()
@property
def data_type(self):
if self.selected_data_type_btn is None:
return None
return self.selected_data_type_btn.text
@property
def is_array(self):
return self.is_array_checkbox.model.get_value_as_bool()
@property
def array_format(self):
return ArrayAttributeFormat(self.array_format_combobox.model.get_item_value_model().get_value_as_int())
@property
def array_shape_source(self):
if self.port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT:
enum_type = OutputArrayShapeSource
widget = self.output_array_shape_source_combobox
else:
return None
value = widget.model.get_item_value_model().get_value_as_int()
return enum_type(value)
@property
def optional(self):
return self.optional_checkbox.model.get_value_as_bool()
def _update_array_shape_source_visibility(self):
self.output_array_shape_source_frame.visible = (
self.port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and self.is_array
)
def _handle_data_type_clicked(self, btn):
if self.selected_data_type_btn is not None:
self.selected_data_type_btn.checked = False
self.selected_data_type_btn = btn
self.selected_data_type_btn.checked = True
def _handle_input_port_btn_clicked(self):
self.is_array_frame.enabled = True
self.optional_frame.visible = True
self._update_array_shape_source_visibility()
def _handle_output_port_btn_clicked(self):
self.is_array_checkbox.model.set_value(True)
self.is_array_frame.enabled = False
self.optional_frame.visible = False
self._update_array_shape_source_visibility()
def _handle_data_type_search(self, text):
if text is None:
self.filtered_data_type_names = self.supported_data_type_names
else:
text = text[0]
self.filtered_data_type_names = tuple(x for x in self.supported_data_type_names if text in x)
self._build_data_type_frame()
self.selected_data_type_btn = None
def _handle_is_array_value_changed(self, model):
# TODO: uncomment when support for dynamic bundle attributes is added
# in OmniGraph.
# self.array_format_frame.visible = model.get_value_as_bool()
self._update_array_shape_source_visibility()
def _handle_array_format_item_changed(self, model, item):
self._update_array_shape_source_visibility()
def _handle_ok_btn_clicked(self):
port_type = self.port_type
if port_type is None:
self._set_error_msg("A port type must be selected.")
return
name = self.name
if not name:
self._set_error_msg("The attribute's name cannot be empty.")
return
if not name[0].isalpha():
self._set_error_msg("The first character of the attribute's name must be a letter.")
return
if self.data_type is None:
self._set_error_msg("A data type for the new attribute must be selected.")
return
attr_desc = UserAttributeDesc(
port_type=port_type,
base_name=name,
data_type_name=self.data_type,
is_array=self.is_array,
array_format=self.array_format,
array_shape_source=self.array_shape_source,
optional=(self.port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT and self.optional),
)
try:
self.create_attr_callback(attr_desc)
except Exception as e:
self._set_error_msg(str(e))
return
self.dialog.visible = False
def _handle_cancel_btn_clicked(self):
self.dialog.visible = False
def _set_error_msg(self, msg):
self.error_msg_label.text = msg
self.error_msg_label.visible = True
def _build_data_type_frame(self):
self.data_type_frame.clear()
with self.data_type_frame:
with ui.VStack():
for data_type_name in self.filtered_data_type_names:
btn = ui.Button(data_type_name)
btn.set_clicked_fn(
partial(
self._handle_data_type_clicked,
btn,
),
)
def _build(self):
self.dialog = ui.Window(
_DIALOG_TITLE,
padding_x=_DIALOG_PADDING,
padding_y=_DIALOG_PADDING,
auto_resize=True,
)
with self.dialog.frame:
with ui.VStack(spacing=10):
# Placeholder to display any error message.
self.error_msg_label = ui.Label(
"",
alignment=ui.Alignment.H_CENTER,
word_wrap=True,
visible=False,
style={
"color": 0xFF0000FF,
},
)
# Port type.
with ui.HStack(height=0):
_add_label("Port Type")
radio_collection = ui.RadioCollection()
with ui.HStack(width=_FIELD_WIDTH):
self.input_port_btn = ui.RadioButton(
text="input",
radio_collection=radio_collection,
clicked_fn=self._handle_input_port_btn_clicked,
)
self.output_port_btn = ui.RadioButton(
text="output",
radio_collection=radio_collection,
clicked_fn=self._handle_output_port_btn_clicked,
)
# Name.
with ui.HStack(height=0):
_add_label("Name")
self.name_field = ui.StringField(width=_FIELD_WIDTH)
# Data type.
with ui.HStack(height=0):
_add_label("Data Type")
with ui.VStack(width=_FIELD_WIDTH):
SearchField(
show_tokens=False,
on_search_fn=self._handle_data_type_search,
subscribe_edit_changed=True,
)
self.data_type_frame = ui.ScrollingFrame(
height=_DATA_TYPE_FRAME_HEIGHT,
horizontal_scrollbar_policy=(ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF),
style_type_name_override="TreeView",
)
self._build_data_type_frame()
# Is array flag.
self.is_array_frame = ui.HStack(height=0)
with self.is_array_frame:
_add_label("Is Array")
self.is_array_checkbox = ui.CheckBox(width=_FIELD_WIDTH)
self.is_array_checkbox.model.add_value_changed_fn(self._handle_is_array_value_changed)
# Array's format.
self.array_format_frame = ui.HStack(height=0, visible=False)
with self.array_format_frame:
_add_label("Array Format")
self.array_format_combobox = ui.ComboBox(
0,
*(x.label for x in ArrayAttributeFormat),
width=_FIELD_WIDTH,
)
self.array_format_combobox.model.add_item_changed_fn(self._handle_array_format_item_changed)
# Output array's shape.
self.output_array_shape_source_frame = ui.HStack(
height=0,
visible=False,
)
with self.output_array_shape_source_frame:
_add_label("Array Shape")
self.output_array_shape_source_combobox = ui.ComboBox(
0,
*(x.label for x in OutputArrayShapeSource),
width=_FIELD_WIDTH,
)
# Optional flag.
self.optional_frame = ui.HStack(height=0)
with self.optional_frame:
_add_label("Optional")
self.optional_checkbox = ui.CheckBox(width=_FIELD_WIDTH)
# Dialog buttons.
with ui.HStack(height=0):
ui.Spacer()
with ui.HStack(
width=_FIELD_WIDTH,
height=_DIALOG_BTNS_FRAME_HEIGHT,
):
ui.Button(
"OK",
clicked_fn=self._handle_ok_btn_clicked,
)
ui.Button(
"Cancel",
clicked_fn=self._handle_cancel_btn_clicked,
)
| 11,427 | Python | 35.628205 | 112 | 0.545375 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/widgets/__init__.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.
"""Widgets used by the custom node UI templates.
These are built solely against the `omni.ui` framework and could in theory be
reused outside of the context of node UIs, unlike the properties that are built
on top of `omni.kit.property.usd`.
"""
| 671 | Python | 46.999997 | 79 | 0.797317 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpWaveSolve.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:size",
"inputs:cellSize",
"inputs:gravity",
"inputs:amplitude",
"inputs:speed",
"inputs:damping",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 1,907 | Python | 29.774193 | 79 | 0.654955 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpKernel.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 functools import partial
from typing import (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
from omni.warp.nodes._impl.attributes import (
attr_get_base_name,
attr_get_name,
)
from omni.warp.nodes._impl.common import SUPPORTED_SDF_DATA_TYPE_NAMES
from omni.warp.nodes._impl.kernel import EXPLICIT_SOURCE
from omni.warp.nodes._impl.props.codefile import get_code_file_prop_builder
from omni.warp.nodes._impl.props.codestr import get_code_str_prop_builder
from omni.warp.nodes._impl.props.editattrs import get_edit_attrs_prop_builder
from omni.warp.nodes._impl.props.sourcepicker import get_source_picker_prop_builder
import warp as wp
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
"""Finds a prop by its name."""
try:
return next(p for p in props if p.prop_name == name)
except StopIteration:
return None
class CustomLayout:
"""Custom UI for the kernel node."""
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
self.dim_source_attr = og.Controller.attribute(
"inputs:dimSource",
self.node,
)
self.dim_count_attr = og.Controller.attribute(
"inputs:dimCount",
self.node,
)
self.code_provider_attr = og.Controller.attribute(
"inputs:codeProvider",
self.node,
)
self.user_attr_descs_attr = og.Controller.attribute(
"state:userAttrDescs",
self.node,
)
self.user_attrs_event_attr = og.Controller.attribute(
"state:userAttrsEvent",
self.node,
)
self.node.register_on_connected_callback(self._handle_node_attr_connected)
self.node.register_on_disconnected_callback(self._handle_node_attr_disconnected)
self.dim_source_attr.register_value_changed_callback(self._handle_dim_source_value_changed)
self.dim_count_attr.register_value_changed_callback(self._handle_dim_count_value_changed)
self.code_provider_attr.register_value_changed_callback(self._handle_code_provider_value_changed)
def _handle_node_attr_connected(
self,
attr_from: og.Attribute,
attr_to: og.Attribute,
) -> None:
"""Callback for a node attribute having been disconnected."""
if attr_get_name(attr_to) == "inputs:codeStr":
# Redraw the UI to update the view/edit code button label.
self.refresh()
def _handle_node_attr_disconnected(
self,
attr_from: og.Attribute,
attr_to: og.Attribute,
) -> None:
"""Callback for a node attribute having been disconnected."""
if attr_get_name(attr_to) == "inputs:codeStr":
# Redraw the UI to update the view/edit code button label.
self.refresh()
def _handle_dim_source_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the dimension source attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the dimension source value.
self.refresh()
def _handle_dim_count_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the dimension count attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the dimension count value.
self.refresh()
def _handle_code_provider_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the code provider attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the code provider value.
self.refresh()
def refresh(self) -> None:
"""Redraws the UI."""
self.compute_node_widget.rebuild_window()
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
"""Builds the UI."""
input_array_attrs = tuple(
x
for x in self.node.get_attributes()
if (
x.is_dynamic()
and x.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
and x.get_resolved_type().array_depth > 0
)
)
dim_sources = (EXPLICIT_SOURCE,) + tuple(attr_get_base_name(x) for x in input_array_attrs)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Add and Remove Attributes"):
CustomLayoutProperty(
None,
display_name=None,
build_fn=get_edit_attrs_prop_builder(
self,
SUPPORTED_SDF_DATA_TYPE_NAMES,
),
)
with CustomLayoutGroup("Inputs"):
prop = find_prop(props, "inputs:device")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
prop = find_prop(props, "inputs:dimSource")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
build_fn=partial(
get_source_picker_prop_builder(
self,
dim_sources,
),
prop,
),
)
dim_source = og.Controller.get(self.dim_source_attr)
if dim_source == EXPLICIT_SOURCE:
prop = find_prop(props, "inputs:dimCount")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
dim_count = min(
max(
og.Controller.get(self.dim_count_attr),
0,
),
wp.types.ARRAY_MAX_DIMS,
)
for i in range(dim_count):
prop = find_prop(props, "inputs:dim{}".format(i + 1))
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
prop = find_prop(props, "inputs:codeProvider")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
code_provider = og.Controller.get(self.code_provider_attr)
if code_provider == "embedded":
prop = find_prop(props, "inputs:codeStr")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
build_fn=partial(
get_code_str_prop_builder(self),
prop,
),
)
elif code_provider == "file":
prop = find_prop(props, "inputs:codeFile")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
build_fn=partial(
get_code_file_prop_builder(self),
prop,
),
)
else:
raise RuntimeError("Unexpected code provider '{}'".format(code_provider))
return frame.apply(props)
| 9,112 | Python | 38.621739 | 105 | 0.539947 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpSampleMeshDeform.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = ("inputs:time",)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 1,790 | Python | 31.563636 | 79 | 0.660894 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpMeshFromVolume.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:size",
"inputs:dim1",
"inputs:dim2",
"inputs:dim3",
"inputs:maxPoints",
"inputs:maxTriangles",
"inputs:threshold",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 1,928 | Python | 29.619047 | 79 | 0.654046 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpGridCreate.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:size",
"inputs:dims",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 1,815 | Python | 30.310344 | 79 | 0.6573 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpNoiseDeform.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PARTIAL_PROPS = (
"inputs:upAxis",
"inputs:base",
"inputs:falloff",
)
SHARED_PROPS = (
"inputs:func",
"inputs:cellSize",
"inputs:speed",
"inputs:amplitude",
"inputs:axisAmplitude",
"inputs:seed",
"inputs:time",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
self.mode_attr = og.Controller.attribute(
"inputs:mode",
self.node,
)
self.mode_attr.register_value_changed_callback(self._handle_mode_value_changed)
def _handle_mode_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the mode attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the mode value.
self.refresh()
def refresh(self) -> None:
"""Redraws the UI."""
self.compute_node_widget.rebuild_window()
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop = find_prop(props, "inputs:mode")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
mode = og.Controller.get(self.mode_attr)
if mode == "partial":
partial_props = tuple(find_prop(props, x) for x in PARTIAL_PROPS)
for prop in partial_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
shared_props = tuple(find_prop(props, x) for x in SHARED_PROPS)
for prop in shared_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 3,374 | Python | 32.088235 | 87 | 0.590101 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/__init__.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.
"""Templates defining custom node UIs.
These override the default behaviour from OmniGraph where widgets are
automatically generated based on the attributes defined in the node's
`.ogn` file.
"""
| 621 | Python | 43.428568 | 76 | 0.808374 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpParticlesSimulate.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:enabled",
"inputs:substepCount",
"inputs:gravity",
"inputs:globalScale",
"inputs:contactElasticStiffness",
"inputs:contactFrictionStiffness",
"inputs:contactFrictionCoeff",
"inputs:contactDampingStiffness",
"inputs:particlesQueryRange",
"inputs:particlesContactAdhesion",
"inputs:particlesContactCohesion",
"inputs:colliderContactDistance",
"inputs:colliderContactQueryRange",
"inputs:groundEnabled",
"inputs:groundAltitude",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 2,271 | Python | 31 | 79 | 0.674593 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpClothSimulate.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:enabled",
"inputs:substepCount",
"inputs:gravity",
"inputs:globalScale",
"inputs:contactElasticStiffness",
"inputs:contactFrictionStiffness",
"inputs:contactFrictionCoeff",
"inputs:contactDampingStiffness",
"inputs:clothDensity",
"inputs:clothTriElasticStiffness",
"inputs:clothTriAreaStiffness",
"inputs:clothTriDampingStiffness",
"inputs:clothTriDrag",
"inputs:clothTriLift",
"inputs:clothEdgeBendingStiffness",
"inputs:clothEdgeDampingStiffness",
"inputs:colliderContactDistance",
"inputs:colliderContactQueryRange",
"inputs:springElasticStiffness",
"inputs:springDampingStiffness",
"inputs:springVisualize",
"inputs:springVisualizeColor",
"inputs:springVisualizeWidth",
"inputs:groundEnabled",
"inputs:groundAltitude",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 2,608 | Python | 31.209876 | 79 | 0.682132 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpTextureWrite.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
import warp as wp
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
"""Finds a prop by its name."""
try:
return next(p for p in props if p.prop_name == name)
except StopIteration:
return None
class CustomLayout:
"""Custom UI for the kernel node."""
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
self.dim_count_attr = og.Controller.attribute(
"inputs:dimCount",
self.node,
)
self.dim_count_attr.register_value_changed_callback(self._handle_dim_count_value_changed)
def _handle_dim_count_value_changed(self, attr: og.Attribute) -> None:
"""Callback for the dimension count attribute value having changed."""
# Redraw the UI to display a different set of attributes depending on
# the dimension count value.
self.refresh()
def refresh(self) -> None:
"""Redraws the UI."""
self.compute_node_widget.rebuild_window()
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
"""Builds the UI."""
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
prop = find_prop(props, "inputs:uri")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
prop = find_prop(props, "inputs:dimCount")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
dim_count = min(
max(
og.Controller.get(self.dim_count_attr),
0,
),
wp.types.ARRAY_MAX_DIMS,
)
for i in range(dim_count):
prop = find_prop(
props,
"inputs:dim{}".format(i + 1),
)
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=(prop.metadata["customData"]["uiName"]),
)
prop = find_prop(props, "inputs:pixelFormat")
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 3,665 | Python | 33.261682 | 97 | 0.556344 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpSampleProceduralVolume.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:torusAltitude",
"inputs:torusMajorRadius",
"inputs:torusMinorRadius",
"inputs:smoothMinRadius",
"inputs:dim",
"inputs:time",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 1,934 | Python | 30.209677 | 79 | 0.659772 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/templates/template_omni.warp.WarpParticlesFromMesh.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 (
Optional,
Sequence,
)
import omni.graph.core as og
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.property.usd.usd_property_widget import UsdPropertyUiEntry
PROPS = (
"inputs:seed",
"inputs:minSdf",
"inputs:maxSdf",
"inputs:radius",
"inputs:spacing",
"inputs:spacingJitter",
"inputs:mass",
"inputs:velocityDir",
"inputs:velocityAmount",
"inputs:maxPoints",
)
def find_prop(
props: Sequence[UsdPropertyUiEntry],
name: str,
) -> Optional[UsdPropertyUiEntry]:
try:
return next(x for x in props if x.prop_name == name)
except StopIteration:
return None
class CustomLayout:
def __init__(self, compute_node_widget):
self.enable = True
self.compute_node_widget = compute_node_widget
self.node_prim_path = self.compute_node_widget._payload[-1]
self.node = og.Controller.node(self.node_prim_path)
def apply(self, props) -> Sequence[UsdPropertyUiEntry]:
user_props = tuple(find_prop(props, x) for x in PROPS)
frame = CustomLayoutFrame(hide_extra=True)
with frame:
with CustomLayoutGroup("Inputs"):
for prop in user_props:
if prop is not None:
CustomLayoutProperty(
prop.prop_name,
display_name=prop.metadata["customData"]["uiName"],
)
return frame.apply(props)
| 2,007 | Python | 29.424242 | 79 | 0.65421 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/kernels/grid_create.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.
"""Warp kernel creating a grid mesh geometry."""
from typing import Tuple
import warp as wp
# Helpers
# -----------------------------------------------------------------------------
@wp.func
def _define_face(
face: int,
vertex_1: int,
vertex_2: int,
vertex_3: int,
vertex_4: int,
out_face_vertex_indices: wp.array(dtype=int),
):
out_face_vertex_indices[face * 4 + 0] = vertex_1
out_face_vertex_indices[face * 4 + 1] = vertex_2
out_face_vertex_indices[face * 4 + 2] = vertex_3
out_face_vertex_indices[face * 4 + 3] = vertex_4
@wp.func
def _set_face_normals(
face: int,
normal: wp.vec3,
out_normals: wp.array(dtype=wp.vec3),
):
out_normals[face * 4 + 0] = normal
out_normals[face * 4 + 1] = normal
out_normals[face * 4 + 2] = normal
out_normals[face * 4 + 3] = normal
@wp.func
def _set_face_uvs(
face: int,
uv_1: wp.vec2,
uv_2: wp.vec2,
uv_3: wp.vec2,
uv_4: wp.vec2,
out_uvs: wp.array(dtype=wp.vec2),
):
out_uvs[face * 4 + 0] = uv_1
out_uvs[face * 4 + 1] = uv_2
out_uvs[face * 4 + 2] = uv_3
out_uvs[face * 4 + 3] = uv_4
# Kernel
# -----------------------------------------------------------------------------
@wp.kernel(enable_backward=False)
def _kernel(
half_size: wp.vec2,
res: wp.vec2i,
update_topology: int,
dt_pos: wp.vec2,
dt_uv: wp.vec2,
out_points: wp.array(dtype=wp.vec3),
out_face_vertex_indices: wp.array(dtype=int),
out_normals: wp.array(dtype=wp.vec3),
out_uvs: wp.array(dtype=wp.vec2),
):
"""Kernel to create a geometry mesh grid."""
tid = wp.tid()
i = int(tid % res[0])
j = int(tid / res[0])
if i == 0 and j == 0:
point = 0
out_points[point] = wp.vec3(
half_size[0],
0.0,
half_size[1],
)
if i == 0:
point = (j + 1) * (res[0] + 1)
out_points[point] = wp.vec3(
half_size[0],
0.0,
half_size[1] - dt_pos[1] * float(j + 1),
)
if j == 0:
point = i + 1
out_points[point] = wp.vec3(
half_size[0] - dt_pos[0] * float(i + 1),
0.0,
half_size[1],
)
point = (j + 1) * (res[0] + 1) + i + 1
out_points[point] = wp.vec3(
half_size[0] - dt_pos[0] * float(i + 1),
0.0,
half_size[1] - dt_pos[1] * float(j + 1),
)
if update_topology:
face = tid
# Face vertex indices.
vertex_4 = point
vertex_3 = vertex_4 - 1
vertex_1 = vertex_3 - res[0]
vertex_2 = vertex_1 - 1
_define_face(face, vertex_1, vertex_2, vertex_3, vertex_4, out_face_vertex_indices)
# Vertex normals.
_set_face_normals(face, wp.vec3(0.0, 1.0, 0.0), out_normals)
# Vertex UVs.
s_0 = 1.0 - dt_uv[0] * float(i)
s_1 = 1.0 - dt_uv[0] * float(i + 1)
t_0 = dt_uv[1] * float(j)
t_1 = dt_uv[1] * float(j + 1)
_set_face_uvs(
face,
wp.vec2(s_1, t_0),
wp.vec2(s_0, t_0),
wp.vec2(s_0, t_1),
wp.vec2(s_1, t_1),
out_uvs,
)
# Launcher
# -----------------------------------------------------------------------------
def grid_create_launch_kernel(
out_points: wp.array,
out_face_vertex_counts: wp.array,
out_face_vertex_indices: wp.array,
out_normals: wp.array,
out_uvs: wp.array,
size: Tuple[float, float],
dims: Tuple[int, int],
update_topology: bool = True,
):
"""Launches the kernel."""
face_count = dims[0] * dims[1]
half_size = (
size[0] * 0.5,
size[1] * 0.5,
)
dt_pos = wp.vec2(
size[0] / float(dims[0]),
size[1] / float(dims[1]),
)
dt_uv = (
1.0 / float(dims[0]),
1.0 / float(dims[1]),
)
wp.launch(
kernel=_kernel,
dim=face_count,
inputs=[
half_size,
dims,
update_topology,
dt_pos,
dt_uv,
],
outputs=[
out_points,
out_face_vertex_indices,
out_normals,
out_uvs,
],
)
out_face_vertex_counts.fill_(4)
| 4,676 | Python | 23.615789 | 91 | 0.494654 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/_impl/kernels/__init__.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.
"""Shared Warp kernels."""
| 451 | Python | 49.222217 | 76 | 0.804878 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/tests/test_api_type_conversions.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.
"""Tests for the API that does type conversions."""
from typing import Any
import omni.graph.core as og
import omni.kit
import omni.warp
import warp as wp
def are_array_annotations_equal(a: Any, b: Any) -> bool:
return isinstance(a, wp.array) and isinstance(b, wp.array) and a.dtype == b.dtype and a.ndim == b.ndim
class TestApiTypeConversions(omni.kit.test.AsyncTestCase):
async def test_og_to_warp_conversion(self):
og_type = og.Type(
og.BaseDataType.BOOL,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.int8
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=1)
expected = wp.array(dtype=wp.int8)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
og_type = og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.COLOR,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.array(dtype=wp.vec3)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=0)
expected = wp.vec3
self.assertEqual(wp_type, expected)
# ----------------------------------------------------------------------
og_type = og.Type(
og.BaseDataType.DOUBLE,
tuple_count=9,
array_depth=0,
role=og.AttributeRole.MATRIX,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.mat33d
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=1)
expected = wp.array(dtype=wp.mat33d)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
og_type = og.Type(
og.BaseDataType.FLOAT,
tuple_count=4,
array_depth=1,
role=og.AttributeRole.QUATERNION,
)
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type)
expected = wp.array(dtype=wp.quat)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_og_to_warp(og_type, dim_count=0)
expected = wp.quat
self.assertEqual(wp_type, expected)
async def test_sdf_name_to_warp_conversion(self):
sdf_name = "color4f"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.vec4
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=1)
expected = wp.array(dtype=wp.vec4)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
sdf_name = "point3f[]"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.array(dtype=wp.vec3)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=0)
expected = wp.vec3
self.assertEqual(wp_type, expected)
# ----------------------------------------------------------------------
sdf_name = "timecode"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.float64
self.assertEqual(wp_type, expected)
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=1)
expected = wp.array(dtype=wp.float64)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
# ----------------------------------------------------------------------
sdf_name = "token[]"
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name)
expected = wp.array(dtype=wp.uint64)
self.assertTrue(are_array_annotations_equal(wp_type, expected))
wp_type = omni.warp.nodes.type_convert_sdf_name_to_warp(sdf_name, dim_count=0)
expected = wp.uint64
self.assertEqual(wp_type, expected)
async def test_sdf_name_to_og_conversion(self):
sdf_name = "float2"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=0,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=True)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=1,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
# ----------------------------------------------------------------------
sdf_name = "matrix3d[]"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.DOUBLE,
tuple_count=9,
array_depth=1,
role=og.AttributeRole.MATRIX,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=False)
expected = og.Type(
og.BaseDataType.DOUBLE,
tuple_count=9,
array_depth=0,
role=og.AttributeRole.MATRIX,
)
self.assertEqual(og_type, expected)
# ----------------------------------------------------------------------
sdf_name = "texCoord2f"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=0,
role=og.AttributeRole.TEXCOORD,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=True)
expected = og.Type(
og.BaseDataType.FLOAT,
tuple_count=2,
array_depth=1,
role=og.AttributeRole.TEXCOORD,
)
self.assertEqual(og_type, expected)
# ----------------------------------------------------------------------
sdf_name = "uchar[]"
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name)
expected = og.Type(
og.BaseDataType.UCHAR,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
og_type = omni.warp.nodes.type_convert_sdf_name_to_og(sdf_name, is_array=False)
expected = og.Type(
og.BaseDataType.UCHAR,
tuple_count=1,
array_depth=0,
role=og.AttributeRole.NONE,
)
self.assertEqual(og_type, expected)
| 7,723 | Python | 33.482143 | 106 | 0.552894 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/tests/__init__.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.
"""Tests for the extension omni.warp.nodes."""
scan_for_test_modules = True
| 501 | Python | 44.63636 | 76 | 0.800399 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/tests/_common.py | """Shared helpers for the extension's tests."""
import importlib
import os
import tempfile
from typing import Optional
import numpy as np
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
from omni.warp.nodes._impl.attributes import from_omni_graph_ptr
import warp as wp
def register_node(
cls: type,
ogn_definition: str,
extension: str,
) -> None:
"""Registers a new node type based on its class object and OGN code."""
# Parse the OGN definition.
interface_wrapper = ogn.NodeInterfaceWrapper(ogn_definition, extension)
# Generate the node's `og.Database` class and load it as a module.
db_definition = ogn.generate_python(
ogn.GeneratorConfiguration(
node_file_path=None,
node_interface=interface_wrapper.node_interface,
extension=extension,
module=extension,
base_name=cls.__name__,
destination_directory=None,
),
)
module_name = "{}.{}".format(extension, cls.__name__)
file, file_path = tempfile.mkstemp(suffix=".py")
try:
with os.fdopen(file, "w") as f:
f.write(db_definition)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
finally:
os.remove(file_path)
# Register the node.
db_cls = getattr(module, "{}Database".format(cls.__name__))
db_cls.register(cls)
def bundle_create_attr(
bundle: og.BundleContents,
name: str,
og_type: og.Type,
size: int = 0,
) -> og.AttributeData:
"""Creates a bundle attribute if it doesn't already exist."""
if bundle.bundle.get_child_bundle_count() > 0:
prim_bundle = bundle.bundle.get_child_bundle(0)
else:
prim_bundle = bundle.bundle.create_child_bundle("prim0")
attr = prim_bundle.get_attribute_by_name(name)
if attr.is_valid() and attr.get_type() == og_type and attr.size() == size:
return attr
return prim_bundle.create_attribute(name, og_type, element_count=size)
def bundle_get_attr(
bundle: og.BundleContents,
name: str,
) -> Optional[og.AttributeData]:
"""Retrieves a bundle attribute from its name."""
if bundle.bundle.get_child_bundle_count():
attr = bundle.bundle.get_child_bundle(0).get_attribute_by_name(name)
else:
attr = bundle.bundle.get_attribute_by_name(name)
if not attr.is_valid():
return None
return attr
def attr_set_array(
attr: og.AttributeData,
value: wp.array,
on_gpu: bool = False,
) -> None:
"""Sets the given array data onto an attribute."""
if on_gpu:
attr.gpu_ptr_kind = og.PtrToPtrKind.CPU
(ptr, _) = attr.get_array(
on_gpu=True,
get_for_write=True,
reserved_element_count=attr.size(),
)
data = from_omni_graph_ptr(ptr, (attr.size(),), dtype=value.dtype)
wp.copy(data, value)
else:
attr.set(value.numpy(), on_gpu=False)
def array_are_equal(
a: wp.array,
b: wp.array,
) -> bool:
"""Checks whether two arrays are equal."""
return a.shape == b.shape and a.dtype == a.dtype and np.array_equal(a.numpy(), b.numpy())
| 3,258 | Python | 27.840708 | 93 | 0.631369 |
NVIDIA/warp/exts/omni.warp/omni/warp/nodes/tests/test_api_from_omni_graph.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.
"""Tests for the `from_omni_graph()` API."""
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.warp
from omni.warp.nodes.tests._common import (
array_are_equal,
attr_set_array,
bundle_create_attr,
bundle_get_attr,
register_node,
)
import warp as wp
# Test Node Definitions
# -----------------------------------------------------------------------------
MAKE_DATA_NODE_DEF = """{
"WarpTestsMakeData": {
"version": 1,
"description": "Make data.",
"language": "Python",
"uiName": "Make Data",
"cudaPointers": "cpu",
"outputs": {
"floatArrayAttr": {
"type": "float[]",
"uiName": "Float Array",
"description": "Float array."
},
"vec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array",
"description": "Vector3 array."
},
"mat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array",
"description": "Matrix4 array."
},
"bundleAttr": {
"type": "bundle",
"uiName": "Bundle",
"description": "Bundle."
}
}
}
}
"""
class MakeDataNode:
@staticmethod
def compute(db: og.Database) -> bool:
db.outputs.floatArrayAttr = (1.0, 2.0, 3.0)
db.outputs.vec3ArrayAttr = ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0))
db.outputs.mat4ArrayAttr = (
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
)
for variant in ("cpuBundle", "gpuBundle"):
device = omni.warp.nodes.device_get_cuda_compute() if variant == "gpuBundle" else wp.get_device("cpu")
with wp.ScopedDevice(device):
attr = bundle_create_attr(
db.outputs.bundleAttr,
"{}FloatArray".format(variant),
og.Type(
og.BaseDataType.FLOAT,
tuple_count=1,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=3,
)
attr_set_array(
attr,
wp.array(db.outputs.floatArrayAttr, dtype=wp.float32),
on_gpu=device.is_cuda,
)
attr = bundle_create_attr(
db.outputs.bundleAttr,
"{}Vec3Array".format(variant),
og.Type(
og.BaseDataType.FLOAT,
tuple_count=3,
array_depth=1,
role=og.AttributeRole.NONE,
),
size=2,
)
attr_set_array(
attr,
wp.array(db.outputs.vec3ArrayAttr, dtype=wp.vec3),
on_gpu=device.is_cuda,
)
attr = bundle_create_attr(
db.outputs.bundleAttr,
"{}Mat4Array".format(variant),
og.Type(
og.BaseDataType.DOUBLE,
tuple_count=16,
array_depth=1,
role=og.AttributeRole.MATRIX,
),
size=2,
)
attr_set_array(
attr,
wp.array(db.outputs.mat4ArrayAttr, dtype=wp.mat44d),
on_gpu=device.is_cuda,
)
return True
FROM_OMNI_GRAPH_NODE_DEF = """{
"WarpTestsFromOmniGraph": {
"version": 1,
"description": "From omni graph.",
"language": "Python",
"uiName": "From Omni Graph",
"cudaPointers": "cpu",
"inputs": {
"anyFloatArrayAttr": {
"type": "float[]",
"uiName": "Float Array (Any)",
"description": "Float array (any).",
"memoryType": "any"
},
"cpuFloatArrayAttr": {
"type": "float[]",
"uiName": "Float Array (CPU)",
"description": "Float array (cpu).",
"memoryType": "cpu"
},
"gpuFloatArrayAttr": {
"type": "float[]",
"uiName": "Float Array (GPU)",
"description": "Float array (gpu).",
"memoryType": "cuda"
},
"anyVec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array (Any)",
"description": "Vector3 array (any).",
"memoryType": "any"
},
"cpuVec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array (CPU)",
"description": "Vector3 array (cpu).",
"memoryType": "cpu"
},
"gpuVec3ArrayAttr": {
"type": "float[3][]",
"uiName": "Vector3 Array (GPU)",
"description": "Vector3 array (gpu).",
"memoryType": "cuda"
},
"anyMat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array (Any)",
"description": "Matrix4 array (any).",
"memoryType": "any"
},
"cpuMat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array (CPU)",
"description": "Matrix4 array (cpu).",
"memoryType": "cpu"
},
"gpuMat4ArrayAttr": {
"type": "matrixd[4][]",
"uiName": "Matrix4 Array (GPU)",
"description": "Matrix4 array (gpu).",
"memoryType": "cuda"
},
"bundleAttr": {
"type": "bundle",
"uiName": "Bundle",
"description": "Bundle."
},
"device": {
"type": "string",
"uiName": "Device",
"description": "Device."
}
},
"outputs": {
"success": {
"type": "bool",
"uiName": "Success",
"description": "Success."
}
}
}
}
"""
def compute(db: og.Database) -> None:
"""Evaluates the node."""
variants = ("any", "cpu", "gpu", "cpuBundle", "gpuBundle")
# Float Array
# --------------------------------------------------------------------------
attr = "floatArray"
for variant in variants:
if variant in ("cpuBundle", "gpuBundle"):
data = bundle_get_attr(db.inputs.bundleAttr, "{}FloatArray".format(variant))
else:
data = getattr(db.inputs, "{}FloatArrayAttr".format(variant))
result = omni.warp.from_omni_graph(data)
expected = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, shape=(3,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) not passing.".format(attr, variant))
# Cast the array to vec3.
result = omni.warp.from_omni_graph(data, dtype=wp.vec3)
expected = wp.array(((1.0, 2.0, 3.0),), dtype=wp.vec3, shape=(1,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with casting to wp.vec3 not passing.".format(attr, variant))
# Vector3 Array
# --------------------------------------------------------------------------
attr = "vec3Array"
for variant in variants:
if variant in ("cpuBundle", "gpuBundle"):
data = bundle_get_attr(db.inputs.bundleAttr, "{}Vec3Array".format(variant))
else:
data = getattr(db.inputs, "{}Vec3ArrayAttr".format(variant))
result = omni.warp.from_omni_graph(data)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.vec3, shape=(2,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) not passing.".format(attr, variant))
# Cast the array to floats while preserving the same shape.
result = omni.warp.from_omni_graph(data, dtype=wp.float32)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.float32, shape=(2, 3))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with casting to float not passing.".format(attr, variant))
# Cast the array to floats while flattening it to a single dimension.
result = omni.warp.from_omni_graph(data, dtype=wp.float32, shape=(6,))
expected = wp.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0), dtype=wp.float32, shape=(6,))
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with flattening not passing.".format(attr, variant))
# Matrix4 Array
# --------------------------------------------------------------------------
attr = "mat4Array"
for variant in variants:
if variant in ("cpuBundle", "gpuBundle"):
data = bundle_get_attr(db.inputs.bundleAttr, "{}Mat4Array".format(variant))
else:
data = getattr(db.inputs, "{}Mat4ArrayAttr".format(variant))
# Due to OmniGraph only supporting 1-D arrays with elements that might
# be represented as tuples, we can at best reconstruct 2-D arrays,
# however arrays made of elements such as matrices require 3 dimensions
# and hence are not something that we can infer from the data we're
# being given, so we need to explicitly pass the dtype here.
result = omni.warp.from_omni_graph(data, dtype=wp.mat44d)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.mat44d,
shape=(2,),
)
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) not passing.".format(attr, variant))
# Cast the array to vec4d.
result = omni.warp.from_omni_graph(data, dtype=wp.vec4d)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.vec4d,
shape=(2, 4),
)
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with casting to vec4 not passing.".format(attr, variant))
# Cast the array to floats while flattening it to a single dimension.
result = omni.warp.from_omni_graph(data, dtype=wp.float64, shape=(32,))
expected = wp.array(
(
1.0,
2.0,
3.0,
4.0,
2.0,
3.0,
4.0,
5.0,
3.0,
4.0,
5.0,
6.0,
4.0,
5.0,
6.0,
7.0,
2.0,
3.0,
4.0,
5.0,
3.0,
4.0,
5.0,
6.0,
4.0,
5.0,
6.0,
7.0,
5.0,
6.0,
7.0,
8.0,
),
dtype=wp.float64,
shape=(32,),
)
if not array_are_equal(result, expected):
raise RuntimeError("Test for {} ({}) with flattening not passing.".format(attr, variant))
class FromOmniGraphNode:
@staticmethod
def compute(db: og.Database) -> bool:
device = (
omni.warp.nodes.device_get_cuda_compute() if db.inputs.device == "cuda" else wp.get_device(db.inputs.device)
)
try:
with wp.ScopedDevice(device):
compute(db)
except Exception:
db.outputs.success = False
raise
db.outputs.success = True
return True
# Test Case
# -----------------------------------------------------------------------------
class TestApiFromOmniGraph(ogts.OmniGraphTestCase):
async def setUp(self) -> None:
await super().setUp()
register_node(MakeDataNode, MAKE_DATA_NODE_DEF, "omni.warp.nodes")
register_node(FromOmniGraphNode, FROM_OMNI_GRAPH_NODE_DEF, "omni.warp.nodes")
(graph, _, _, _) = og.Controller.edit(
"/Graph",
{
og.Controller.Keys.CREATE_NODES: [
("MakeData", "omni.warp.nodes.WarpTestsMakeData"),
("FromOmniGraph", "omni.warp.nodes.WarpTestsFromOmniGraph"),
],
og.Controller.Keys.CONNECT: [
("MakeData.outputs:floatArrayAttr", "FromOmniGraph.inputs:anyFloatArrayAttr"),
("MakeData.outputs:floatArrayAttr", "FromOmniGraph.inputs:cpuFloatArrayAttr"),
("MakeData.outputs:floatArrayAttr", "FromOmniGraph.inputs:gpuFloatArrayAttr"),
("MakeData.outputs:vec3ArrayAttr", "FromOmniGraph.inputs:anyVec3ArrayAttr"),
("MakeData.outputs:vec3ArrayAttr", "FromOmniGraph.inputs:cpuVec3ArrayAttr"),
("MakeData.outputs:vec3ArrayAttr", "FromOmniGraph.inputs:gpuVec3ArrayAttr"),
("MakeData.outputs:mat4ArrayAttr", "FromOmniGraph.inputs:anyMat4ArrayAttr"),
("MakeData.outputs:mat4ArrayAttr", "FromOmniGraph.inputs:cpuMat4ArrayAttr"),
("MakeData.outputs:mat4ArrayAttr", "FromOmniGraph.inputs:gpuMat4ArrayAttr"),
("MakeData.outputs_bundleAttr", "FromOmniGraph.inputs:bundleAttr"),
],
},
)
self.graph = graph
async def test_main(self):
node = og.Controller.node(("FromOmniGraph", self.graph))
device_attr = og.Controller.attribute("inputs:device", node)
success_attr = og.Controller.attribute("outputs:success", node)
device_attr.set("cpu")
await og.Controller.evaluate(self.graph)
self.assertTrue(success_attr.get())
device_attr.set("cuda")
await og.Controller.evaluate(self.graph)
self.assertTrue(success_attr.get())
| 15,869 | Python | 34.503356 | 120 | 0.453841 |
NVIDIA/warp/exts/omni.warp/omni/warp/_extension/__init__.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.
"""Entry point for the extension."""
import asyncio
import os
import subprocess
import sys
import webbrowser
from contextlib import suppress
from typing import Sequence
import carb
import carb.dictionary
import omni.ext
import omni.graph.core as og
import omni.kit.actions.core
import warp as wp
SCENES_PATH = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../data/scenes"))
NODES_INIT_PATH = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "../nodes/_impl/__init__.py")
)
WARP_GETTING_STARTED_URL = "https://docs.omniverse.nvidia.com/extensions/latest/ext_warp.html"
WARP_DOCUMENTATION_URL = "https://nvidia.github.io/warp/"
SETTING_ENABLE_BACKWARD = "/exts/omni.warp/enable_backward"
SETTING_ENABLE_MENU = "/exts/omni.warp/enable_menu"
SETTING_KERNEL_NODE_OPT_IN = "/app/omni.warp/kernel_opt_in"
SETTING_KERNEL_NODE_ENABLE_OPT_IN = "/app/omni.warp/kernel_enable_opt_in"
OMNIGRAPH_STAGEUPDATE_ORDER = 100 # We want our attach() to run after OG so that nodes have been instantiated
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
subprocess.call(["xdg-open", filename])
def set_all_graphs_enabled(enable: bool) -> None:
"""Set the enabled state of all OmniGraphs"""
graphs = og.get_all_graphs()
for graph in graphs:
graph.set_disabled(not enable)
def is_kernel_node_check_enabled() -> bool:
"""Check whether the kernel node opt-in is enabled"""
settings = carb.settings.get_settings()
if not settings.is_accessible_as(
carb.dictionary.ItemType.BOOL,
SETTING_KERNEL_NODE_ENABLE_OPT_IN,
):
# The enable-setting is not present, we enable the check
return True
if not settings.get(SETTING_KERNEL_NODE_ENABLE_OPT_IN):
# The enable-setting is present and False, disable the check
return False
# the enable-setting is present and True, enable the check
return True
VERIFY_KERNEL_NODE_LOAD_MSG = """This stage contains Warp kernel nodes.
There is currently no limitation on what code can be executed by this node. This means that graphs that contain these nodes should only be used when the author of the graph is trusted.
Do you want to enable the Warp kernel node functionality for this session?
"""
def verify_kernel_node_load(nodes: Sequence[og.Node]):
"""Confirm the user wants to run the nodes for the current session."""
from omni.kit.window.popup_dialog import MessageDialog
def on_cancel(dialog: MessageDialog):
settings = carb.settings.get_settings()
settings.set(SETTING_KERNEL_NODE_OPT_IN, False)
dialog.hide()
def on_ok(dialog: MessageDialog):
settings = carb.settings.get_settings()
settings.set(SETTING_KERNEL_NODE_OPT_IN, True)
dialog.hide()
dialog = MessageDialog(
title="Warning",
width=400,
message=VERIFY_KERNEL_NODE_LOAD_MSG,
ok_handler=on_ok,
ok_label="Yes",
cancel_handler=on_cancel,
cancel_label="No",
)
async def show_async():
import omni.kit.app
# wait a few frames to allow the app ui to finish loading
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
dialog.show()
asyncio.ensure_future(show_async())
def check_for_kernel_nodes() -> None:
"""Check for kernel node instances and confirm user wants to run them."""
# If the check is not enabled then we are good
if not is_kernel_node_check_enabled():
return
# Check is enabled - see if they already opted-in
settings = carb.settings.get_settings()
if settings.get(SETTING_KERNEL_NODE_OPT_IN):
# The check is enabled, and they opted-in
return
# The check is enabled but they opted out, or haven't been prompted yet
try:
import omni.kit.window.popup_dialog
except ImportError:
# Don't prompt in headless mode
return
graphs = og.get_all_graphs()
nodes = tuple(
n for g in graphs for n in g.get_nodes() if n.get_node_type().get_node_type() == "omni.warp.WarpKernel"
)
if not nodes:
# No nodes means we can leave them enabled
return
# Disable them until we get the opt-in via the async dialog
set_all_graphs_enabled(False)
verify_kernel_node_load(nodes)
def on_attach(*args, **kwargs) -> None:
"""Called when USD stage is attached"""
check_for_kernel_nodes()
def on_kernel_opt_in_setting_change(
item: carb.dictionary.Item,
change_type: carb.settings.ChangeEventType,
) -> None:
"""Update the local cache of the setting value"""
if change_type != carb.settings.ChangeEventType.CHANGED:
return
settings = carb.settings.get_settings()
if settings.get(SETTING_KERNEL_NODE_OPT_IN):
set_all_graphs_enabled(True)
class OmniWarpExtension(omni.ext.IExt):
def __init__(self, *args, **kwargs):
import omni.kit.app
super().__init__(*args, **kwargs)
self._menu = None
self._stage_subscription = None
self._opt_in_setting_sub = None
with suppress(ImportError):
app = omni.kit.app.get_app()
manager = app.get_extension_manager()
if manager.is_extension_enabled("omni.graph.ui"):
import omni.graph.ui
omni.graph.ui.ComputeNodeWidget.get_instance().add_template_path(NODES_INIT_PATH)
def on_startup(self, ext_id):
import omni.kit.app
settings = carb.settings.get_settings()
wp.config.enable_backward = settings.get(SETTING_ENABLE_BACKWARD)
self._is_live = True
self._ext_name = "omni.warp"
if settings.get(SETTING_ENABLE_MENU):
with suppress(ImportError):
import omni.kit.menu.utils
from omni.warp._extension.menu import WarpMenu
self._register_actions()
self._menu = WarpMenu()
with suppress(ImportError):
import omni.kit.browser.sample
omni.kit.browser.sample.register_sample_folder(SCENES_PATH, "Warp")
stage_update = omni.stageupdate.get_stage_update_interface()
self._stage_subscription = stage_update.create_stage_update_node(
"WarpKernelAttach",
on_attach_fn=on_attach,
)
assert self._stage_subscription
nodes = stage_update.get_stage_update_nodes()
stage_update.set_stage_update_node_order(
len(nodes) - 1,
OMNIGRAPH_STAGEUPDATE_ORDER + 1,
)
self._opt_in_setting_sub = omni.kit.app.SettingChangeSubscription(
SETTING_KERNEL_NODE_OPT_IN,
on_kernel_opt_in_setting_change,
)
assert self._opt_in_setting_sub
# Expose the `from_omni_graph` function onto the `omni.warp` module for
# backward compatibility. This cannot be done by using a `__init__.py`
# file directly under the `omni/warp` folder because it represents
# a Python namespace package.
import omni.warp
import omni.warp.nodes
omni.warp.from_omni_graph = omni.warp.nodes.from_omni_graph
def on_shutdown(self):
if self._menu is not None:
self._menu.shutdown()
self._menu = None
self._deregister_actions()
with suppress(ImportError):
import omni.kit.browser.sample
omni.kit.browser.sample.unregister_sample_folder(SCENES_PATH)
self._stage_subscription = None
self._opt_in_setting_sub = None
# Clean-up the extension's API.
import omni.warp
delattr(omni.warp, "from_omni_graph")
def _register_actions(self):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Warp menu actions"
# actions
action_registry.register_action(
self._ext_name,
"getting_started",
lambda: self._on_getting_started_click(),
display_name="Warp->Getting Started",
description="",
tag=actions_tag,
)
action_registry.register_action(
self._ext_name,
"documentation",
lambda: self._on_documentation_click(),
display_name="Warp->Documentation",
description="",
tag=actions_tag,
)
action_registry.register_action(
self._ext_name,
"browse_scenes",
lambda: self._on_browse_scenes_click(),
display_name="Warp->Browse Scenes",
description="",
tag=actions_tag,
)
def _deregister_actions(self):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(self._ext_name)
def _on_browse_scenes_click(self):
open_file(SCENES_PATH)
def _on_getting_started_click(self, *_):
webbrowser.open(WARP_GETTING_STARTED_URL)
def _on_documentation_click(self, *_):
webbrowser.open(WARP_DOCUMENTATION_URL)
| 9,622 | Python | 31.183946 | 184 | 0.644253 |
NVIDIA/warp/exts/omni.warp/omni/warp/_extension/menu.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 omni.kit.menu.utils
from omni.kit.menu.utils import MenuItemDescription
class WarpMenu:
def __init__(self):
omni.kit.menu.utils.set_default_menu_proirity("Warp", -8)
self._top_menu = None
self._build_warp_menu()
def _build_warp_menu(self):
# Warp menu
warp_menu = []
warp_menu.append(MenuItemDescription(name="Documentation", onclick_action=("omni.warp", "documentation")))
warp_menu.append(MenuItemDescription(name="Getting Started", onclick_action=("omni.warp", "getting_started")))
warp_menu.append(MenuItemDescription(name="Sample Scenes", onclick_action=("omni.warp", "browse_scenes")))
self._top_menu = [MenuItemDescription(name="Warp", appear_after="Simulation", sub_menu=warp_menu)]
omni.kit.menu.utils.add_menu_items(self._top_menu, "Window", -8)
def shutdown(self):
omni.kit.menu.utils.remove_menu_items(self._top_menu, "Window")
| 1,378 | Python | 42.093749 | 118 | 0.713353 |
NVIDIA/warp/exts/omni.warp/docs/CHANGELOG.md | # CHANGELOG
## [1.1.1] - 2024-05-24
- Implicitly initialize Warp when first required
- Speed up `omni.warp.core`'s startup time
## [1.1.0] - 2024-05-09
- Support returning a value from `@wp.func_native` CUDA functions using type hints
- Improved differentiability of the `wp.sim.FeatherstoneIntegrator`
- Fix gradient propagation for rigid body contacts in `wp.sim.collide()`
- Added support for event-based timing, see `wp.ScopedTimer()`
- Added Tape visualization and debugging functions, see `wp.Tape.visualize()`
- Support constructing Warp arrays from objects that define the `__cuda_array_interface__` attribute
- Support copying a struct to another device, use `struct.to(device)` to migrate struct arrays
- Allow rigid shapes to not have any collisions with other shapes in `wp.sim.Model`
- Change default test behavior to test redundant GPUs (up to 2x)
- Test each example in an individual subprocess
- Polish and optimize various examples and tests
- Allow non-contiguous point arrays to be passed to `wp.HashGrid.build()`
- Upgrade LLVM to 18.1.3 for from-source builds and Linux x86-64 builds
- Build DLL source code as C++17 and require GCC 9.4 as a minimum
- Array clone, assign, and copy are now differentiable
- Use `Ruff` for formatting and linting
- Various documentation improvements (infinity, math constants, etc.)
- Improve URDF importer, handle joint armature
- Allow builtins.bool to be used in Warp data structures
- Use external gradient arrays in backward passes when passed to `wp.launch()`
- Add Conjugate Residual linear solver, see `wp.optim.linear.cr()`
- Fix propagation of gradients on aliased copy of variables in kernels
- Facilitate debugging and speed up `import warp` by eliminating raising any exceptions
- Improve support for nested vec/mat assignments in structs
- Recommend Python 3.9 or higher, which is required for JAX and soon PyTorch.
- Support gradient propagation for indexing sliced multi-dimensional arrays, i.e. `a[i][j]` vs. `a[i, j]`
- Provide an informative message if setting DLL C-types failed, instructing to try rebuilding the library
## [1.0.3] - 2024-04-17
- Add a `support_level` entry to the configuration file of the extensions
## [1.0.2] - 2024-03-22
- Make examples runnable from any location
- Fix the examples not running directly from their Python file
- Add the example gallery to the documentation
- Update `README.md` examples USD location
- Update `example_graph_capture.py` description
## [1.0.1] - 2024-03-15
- Document Device `total_memory` and `free_memory`
- Documentation for allocators, streams, peer access, and generics
- Changed example output directory to current working directory
- Added `python -m warp.examples.browse` for browsing the examples folder
- Print where the USD stage file is being saved
- Added `examples/optim/example_walker.py` sample
- Make the drone example not specific to USD
- Reduce the time taken to run some examples
- Optimise rendering points with a single colour
- Clarify an error message around needing USD
- Raise exception when module is unloaded during graph capture
- Added `wp.synchronize_event()` for blocking the host thread until a recorded event completes
- Flush C print buffers when ending `stdout` capture
- Remove more unneeded CUTLASS files
- Allow setting mempool release threshold as a fractional value
## [1.0.0] - 2024-03-07
- Add `FeatherstoneIntegrator` which provides more stable simulation of articulated rigid body dynamics in generalized coordinates (`State.joint_q` and `State.joint_qd`)
- Introduce `warp.sim.Control` struct to store control inputs for simulations (optional, by default the `Model` control inputs are used as before); integrators now have a different simulation signature: `integrator.simulate(model: Model, state_in: State, state_out: State, dt: float, control: Control)`
- `joint_act` can now behave in 3 modes: with `joint_axis_mode` set to `JOINT_MODE_FORCE` it behaves as a force/torque, with `JOINT_MODE_VELOCITY` it behaves as a velocity target, and with `JOINT_MODE_POSITION` it behaves as a position target; `joint_target` has been removed
- Add adhesive contact to Euler integrators via `Model.shape_materials.ka` which controls the contact distance at which the adhesive force is applied
- Improve handling of visual/collision shapes in URDF importer so visual shapes are not involved in contact dynamics
- Experimental JAX kernel callback support
- Improve module load exception message
- Add `wp.ScopedCapture`
- Removing `enable_backward` warning for callables
- Copy docstrings and annotations from wrapped kernels, functions, structs
## [0.15.1] - 2024-03-05
- Add examples assets to the wheel packages
- Fix broken image link in documentation
- Fix codegen for custom grad functions calling their respective forward functions
- Fix custom grad function handling for functions that have no outputs
- Fix issues when `wp.config.quiet = True`
## [0.15.0] - 2024-03-04
- Add thumbnails to examples gallery
- Apply colored lighting to examples
- Moved `examples` directory under `warp/`
- Add example usage to `python -m warp.tests --help`
- Adding `torch.autograd.function` example + docs
- Add error-checking to array shapes during creation
- Adding `example_graph_capture`
- Add a Diffsim Example of a Drone
- Fix `verify_fp` causing compiler errors and support CPU kernels
- Fix to enable `matmul` to be called in CUDA graph capture
- Enable mempools by default
- Update `wp.launch` to support tuple args
- Fix BiCGSTAB and GMRES producing NaNs when converging early
- Fix warning about backward codegen being disabled in `test_fem`
- Fix `assert_np_equal` when NaN's and tolerance are involved
- Improve error message to discern between CUDA being disabled or not supported
- Support cross-module functions with user-defined gradients
- Suppress superfluous CUDA error when ending capture after errors
- Make output during initialization atomic
- Add `warp.config.max_unroll`, fix custom gradient unrolling
- Support native replay snippets using `@wp.func_native(snippet, replay_snippet=replay_snippet)`
- Look for the CUDA Toolkit in default locations if the `CUDA_PATH` environment variable or `--cuda_path` build option are not used
- Added `wp.ones()` to efficiently create one-initialized arrays
- Rename `wp.config.graph_capture_module_load_default` to `wp.config.enable_graph_capture_module_load_by_default`
## [0.14.0] - 2024-02-19
- Add support for CUDA pooled (stream-ordered) allocators
- Support memory allocation during graph capture
- Support copying non-contiguous CUDA arrays during graph capture
- Improved memory allocation/deallocation performance with pooled allocators
- Use `wp.config.enable_mempools_at_init` to enable pooled allocators during Warp initialization (if supported)
- `wp.is_mempool_supported()` - check if a device supports pooled allocators
- `wp.is_mempool_enabled()`, `wp.set_mempool_enabled()` - enable or disable pooled allocators per device
- `wp.set_mempool_release_threshold()`, `wp.get_mempool_release_threshold()` - configure memory pool release threshold
- Add support for direct memory access between devices
- Improved peer-to-peer memory transfer performance if access is enabled
- Caveat: enabling peer access may impact memory allocation/deallocation performance and increase memory consumption
- `wp.is_peer_access_supported()` - check if the memory of a device can be accessed by a peer device
- `wp.is_peer_access_enabled()`, `wp.set_peer_access_enabled()` - manage peer access for memory allocated using default CUDA allocators
- `wp.is_mempool_access_supported()` - check if the memory pool of a device can be accessed by a peer device
- `wp.is_mempool_access_enabled()`, `wp.set_mempool_access_enabled()` - manage access for memory allocated using pooled CUDA allocators
- Refined stream synchronization semantics
- `wp.ScopedStream` can synchronize with the previous stream on entry and/or exit (only sync on entry by default)
- Functions taking an optional stream argument do no implicit synchronization for max performance (e.g., `wp.copy()`, `wp.launch()`, `wp.capture_launch()`)
- Support for passing a custom `deleter` argument when constructing arrays
- Deprecation of `owner` argument - use `deleter` to transfer ownership
- Optimizations for various core API functions (e.g., `wp.zeros()`, `wp.full()`, and more)
- Fix `wp.matmul()` to always use the correct CUDA context
- Fix memory leak in BSR transpose
- Fix stream synchronization issues when copying non-contiguous arrays
- API change: `wp.matmul()` no longer accepts a device as a parameter; instead, it infers the correct device from the arrays being multiplied
- Updated DLPack utilities to the latest published standard
- External arrays can be imported into Warp directly, e.g., `wp.from_dlpack(external_array)`
- Warp arrays can be exported to consumer frameworks directly, e.g., `jax.dlpack.from_dlpack(warp_array)`
- Added CUDA stream synchronization for CUDA arrays
- The original DLPack protocol can still be used for better performance when stream synchronization is not required, see interoperability docs for details
- `warp.to_dlpack()` is about 3-4x faster in common cases
- `warp.from_dlpack()` is about 2x faster when called with a DLPack capsule
- Fixed a small CPU memory leak related to DLPack interop
- Improved performance of creating arrays
## [0.13.1] - 2024-02-22
- Ensure that the results from the `Noise Deform` are deterministic across different Kit sessions
## [0.13.0] - 2024-02-16
- Update the license to *NVIDIA Software License*, allowing commercial use (see `LICENSE.md`)
- Add `CONTRIBUTING.md` guidelines (for NVIDIA employees)
- Hash CUDA `snippet` and `adj_snippet` strings to fix caching
- Fix `build_docs.py` on Windows
- Add missing `.py` extension to `warp/tests/walkthrough_debug`
- Allow `wp.bool` usage in vector and matrix types
## [0.12.0] - 2024-02-05
- Add a warning when the `enable_backward` setting is set to `False` upon calling `wp.Tape.backward()`
- Fix kernels not being recompiled as expected when defined using a closure
- Change the kernel cache appauthor subdirectory to just "NVIDIA"
- Ensure that gradients attached to PyTorch tensors have compatible strides when calling `wp.from_torch()`
- Add a `Noise Deform` node for OmniGraph that deforms points using a perlin/curl noise
## [0.11.0] - 2024-01-23
- Re-release 1.0.0-beta.7 as a non-pre-release 0.11.0 version so it gets selected by `pip install warp-lang`.
- Introducing a new versioning and release process, detailed in `PACKAGING.md` and resembling that of [Python itself](https://devguide.python.org/developer-workflow/development-cycle/#devcycle):
- The 0.11 release(s) can be found on the `release-0.11` branch.
- Point releases (if any) go on the same minor release branch and only contain bug fixes, not new features.
- The `public` branch, previously used to merge releases into and corresponding with the GitHub `main` branch, is retired.
## [1.0.0-beta.7] - 2024-01-23
- Ensure captures are always enclosed in `try`/`finally`
- Only include .py files from the warp subdirectory into wheel packages
- Fix an extension's sample node failing at parsing some version numbers
- Allow examples to run without USD when possible
- Add a setting to disable the main Warp menu in Kit
- Add iterative linear solvers, see `wp.optim.linear.cg`, `wp.optim.linear.bicgstab`, `wp.optim.linear.gmres`, and `wp.optim.linear.LinearOperator`
- Improve error messages around global variables
- Improve error messages around mat/vec assignments
- Support conversion of scalars to native/ctypes, e.g.: `float(wp.float32(1.23))` or `ctypes.c_float(wp.float32(1.23))`
- Add a constant for infinity, see `wp.inf`
- Add a FAQ entry about array assignments
- Add a mass spring cage diff simulation example, see `examples/example_diffsim_mass_spring_cage.py`
- Add `-s`, `--suite` option for only running tests belonging to the given suites
- Fix common spelling mistakes
- Fix indentation of generated code
- Show deprecation warnings only once
- Improve `wp.render.OpenGLRenderer`
- Create the extension's symlink to the *core library* at runtime
- Fix some built-ins failing to compile the backward pass when nested inside if/else blocks
- Update examples with the new variants of the mesh query built-ins
- Fix type members that weren't zero-initialized
- Fix missing adjoint function for `wp.mesh_query_ray()`
## [1.0.0-beta.6] - 2024-01-10
- Do not create CPU copy of grad array when calling `array.numpy()`
- Fix `assert_np_equal()` bug
- Support Linux AArch64 platforms, including Jetson/Tegra devices
- Add parallel testing runner (invoke with `python -m warp.tests`, use `warp/tests/unittest_serial.py` for serial testing)
- Fix support for function calls in `range()`
- `wp.matmul()` adjoints now accumulate
- Expand available operators (e.g. vector @ matrix, scalar as dividend) and improve support for calling native built-ins
- Fix multi-gpu synchronization issue in `sparse.py`
- Add depth rendering to `wp.render.OpenGLRenderer`, document `wp.render`
- Make `wp.atomic_min()`, `wp.atomic_max()` differentiable
- Fix error reporting using the exact source segment
- Add user-friendly mesh query overloads, returning a struct instead of overwriting parameters
- Address multiple differentiability issues
- Fix backpropagation for returning array element references
- Support passing the return value to adjoints
- Add point basis space and explicit point-based quadrature for `wp.fem`
- Support overriding the LLVM project source directory path using `build_lib.py --build_llvm --llvm_source_path=`
- Fix the error message for accessing non-existing attributes
- Flatten faces array for Mesh constructor in URDF parser
## [1.0.0-beta.5] - 2023-11-22
- Fix for kernel caching when function argument types change
- Fix code-gen ordering of dependent structs
- Fix for `wp.Mesh` build on MGPU systems
- Fix for name clash bug with adjoint code: https://github.com/NVIDIA/warp/issues/154
- Add `wp.frac()` for returning the fractional part of a floating point value
- Add support for custom native CUDA snippets using `@wp.func_native` decorator
- Add support for batched matmul with batch size > 2^16-1
- Add support for transposed CUTLASS `wp.matmul()` and additional error checking
- Add support for quad and hex meshes in `wp.fem`
- Detect and warn when C++ runtime doesn't match compiler during build, e.g.: ``libstdc++.so.6: version `GLIBCXX_3.4.30' not found``
- Documentation update for `wp.BVH`
- Documentation and simplified API for runtime kernel specialization `wp.Kernel`
## [1.0.0-beta.4] - 2023-11-01
- Add `wp.cbrt()` for cube root calculation
- Add `wp.mesh_furthest_point_no_sign()` to compute furthest point on a surface from a query point
- Add support for GPU BVH builds, 10-100x faster than CPU builds for large meshes
- Add support for chained comparisons, i.e.: `0 < x < 2`
- Add support for running `wp.fem` examples headless
- Fix for unit test determinism
- Fix for possible GC collection of array during graph capture
- Fix for `wp.utils.array_sum()` output initialization when used with vector types
- Coverage and documentation updates
## [1.0.0-beta.3] - 2023-10-19
- Add support for code coverage scans (test_coverage.py), coverage at 85% in `omni.warp.core`
- Add support for named component access for vector types, e.g.: `a = v.x`
- Add support for lvalue expressions, e.g.: `array[i] += b`
- Add casting constructors for matrix and vector types
- Add support for `type()` operator that can be used to return type inside kernels
- Add support for grid-stride kernels to support kernels with > 2^31-1 thread blocks
- Fix for multi-process initialization warnings
- Fix alignment issues with empty `wp.struct`
- Fix for return statement warning with tuple-returning functions
- Fix for `wp.batched_matmul()` registering the wrong function in the Tape
- Fix and document for `wp.sim` forward + inverse kinematics
- Fix for `wp.func` to return a default value if function does not return on all control paths
- Refactor `wp.fem` support for new basis functions, decoupled function spaces
- Optimizations for `wp.noise` functions, up to 10x faster in most cases
- Optimizations for `type_size_in_bytes()` used in array construction'
### Breaking Changes
- To support grid-stride kernels, `wp.tid()` can no longer be called inside `wp.func` functions.
## [1.0.0-beta.2] - 2023-09-01
- Fix for passing bool into `wp.func` functions
- Fix for deprecation warnings appearing on `stderr`, now redirected to `stdout`
- Fix for using `for i in wp.hash_grid_query(..)` syntax
## [1.0.0-beta.1] - 2023-08-29
- Fix for `wp.float16` being passed as kernel arguments
- Fix for compile errors with kernels using structs in backward pass
- Fix for `wp.Mesh.refit()` not being CUDA graph capturable due to synchronous temp. allocs
- Fix for dynamic texture example flickering / MGPU crashes demo in Kit by reusing `ui.DynamicImageProvider` instances
- Fix for a regression that disabled bundle change tracking in samples
- Fix for incorrect surface velocities when meshes are deforming in `OgnClothSimulate`
- Fix for incorrect lower-case when setting USD stage "up_axis" in examples
- Fix for incompatible gradient types when wrapping PyTorch tensor as a vector or matrix type
- Fix for adding open edges when building cloth constraints from meshes in `wp.sim.ModelBuilder.add_cloth_mesh()`
- Add support for `wp.fabricarray` to directly access Fabric data from Warp kernels, see https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usdrt_prim_selection.html for examples
- Add support for user defined gradient functions, see `@wp.func_replay`, and `@wp.func_grad` decorators
- Add support for more OG attribute types in `omni.warp.from_omni_graph()`
- Add support for creating NanoVDB `wp.Volume` objects from dense NumPy arrays
- Add support for `wp.volume_sample_grad_f()` which returns the value + gradient efficiently from an NVDB volume
- Add support for LLVM fp16 intrinsics for half-precision arithmetic
- Add implementation of stochastic gradient descent, see `wp.optim.SGD`
- Add `wp.fem` framework for solving weak-form PDE problems (see https://nvidia.github.io/warp/modules/fem.html)
- Optimizations for `omni.warp` extension load time (2.2s to 625ms cold start)
- Make all `omni.ui` dependencies optional so that Warp unit tests can run headless
- Deprecation of `wp.tid()` outside of kernel functions, users should pass `tid()` values to `wp.func` functions explicitly
- Deprecation of `wp.sim.Model.flatten()` for returning all contained tensors from the model
- Add support for clamping particle max velocity in `wp.sim.Model.particle_max_velocity`
- Remove dependency on `urdfpy` package, improve MJCF parser handling of default values
## [0.10.1] - 2023-07-25
- Fix for large multidimensional kernel launches (> 2^32 threads)
- Fix for module hashing with generics
- Fix for unrolling loops with break or continue statements (will skip unrolling)
- Fix for passing boolean arguments to build_lib.py (previously ignored)
- Fix build warnings on Linux
- Fix for creating array of structs from NumPy structured array
- Fix for regression on kernel load times in Kit when using `wp.sim`
- Update `wp.array.reshape()` to handle `-1` dimensions
- Update margin used by for mesh queries when using `wp.sim.create_soft_body_contacts()`
- Improvements to gradient handling with `wp.from_torch()`, `wp.to_torch()` plus documentation
## [0.10.0] - 2023-07-05
- Add support for macOS universal binaries (x86 + aarch64) for M1+ support
- Add additional methods for SDF generation please see the following new methods:
- `wp.mesh_query_point_nosign()` - closest point query with no sign determination
- `wp.mesh_query_point_sign_normal()` - closest point query with sign from angle-weighted normal
- `wp.mesh_query_point_sign_winding_number()` - closest point query with fast winding number sign determination
- Add CSR/BSR sparse matrix support, see `wp.sparse` module:
- `wp.sparse.BsrMatrix`
- `wp.sparse.bsr_zeros()`, `wp.sparse.bsr_set_from_triplets()` for construction
- `wp.sparse.bsr_mm()`, `wp.sparse_bsr_mv()` for matrix-matrix and matrix-vector products respectively
- Add array-wide utilities:
- `wp.utils.array_scan()` - prefix sum (inclusive or exclusive)
- `wp.utils.array_sum()` - sum across array
- `wp.utils.radix_sort_pairs()` - in-place radix sort (key,value) pairs
- Add support for calling `@wp.func` functions from Python (outside of kernel scope)
- Add support for recording kernel launches using a `wp.Launch` object that can be replayed with low overhead, use `wp.launch(..., record_cmd=True)` to generate a command object
- Optimizations for `wp.struct` kernel arguments, up to 20x faster launches for kernels with large structs or number of params
- Refresh USD samples to use bundle based workflow + change tracking
- Add Python API for manipulating mesh and point bundle data in OmniGraph, see `omni.warp.nodes` module, see `omni.warp.nodes.mesh_create_bundle()`, `omni.warp.nodes.mesh_get_points()`, etc
- Improvements to `wp.array`:
- Fix a number of array methods misbehaving with empty arrays
- Fix a number of bugs and memory leaks related to gradient arrays
- Fix array construction when creating arrays in pinned memory from a data source in pageable memory
- `wp.empty()` no longer zeroes-out memory and returns an uninitialized array, as intended
- `array.zero_()` and `array.fill_()` work with non-contiguous arrays
- Support wrapping non-contiguous NumPy arrays without a copy
- Support preserving the outer dimensions of NumPy arrays when wrapping them as Warp arrays of vector or matrix types
- Improve PyTorch and DLPack interop with Warp arrays of arbitrary vectors and matrices
- `array.fill_()` can now take lists or other sequences when filling arrays of vectors or matrices, e.g. `arr.fill_([[1, 2], [3, 4]])`
- `array.fill_()` now works with arrays of structs (pass a struct instance)
- `wp.copy()` gracefully handles copying between non-contiguous arrays on different devices
- Add `wp.full()` and `wp.full_like()`, e.g., `a = wp.full(shape, value)`
- Add optional `device` argument to `wp.empty_like()`, `wp.zeros_like()`, `wp.full_like()`, and `wp.clone()`
- Add `indexedarray` methods `.zero_()`, `.fill_()`, and `.assign()`
- Fix `indexedarray` methods `.numpy()` and `.list()`
- Fix `array.list()` to work with arrays of any Warp data type
- Fix `array.list()` synchronization issue with CUDA arrays
- `array.numpy()` called on an array of structs returns a structured NumPy array with named fields
- Improve the performance of creating arrays
- Fix for `Error: No module named 'omni.warp.core'` when running some Kit configurations (e.g.: stubgen)
- Fix for `wp.struct` instance address being included in module content hash
- Fix codegen with overridden function names
- Fix for kernel hashing so it occurs after code generation and before loading to fix a bug with stale kernel cache
- Fix for `wp.BVH.refit()` when executed on the CPU
- Fix adjoint of `wp.struct` constructor
- Fix element accessors for `wp.float16` vectors and matrices in Python
- Fix `wp.float16` members in structs
- Remove deprecated `wp.ScopedCudaGuard()`, please use `wp.ScopedDevice()` instead
## [0.9.0] - 2023-06-01
- Add support for in-place modifications to vector, matrix, and struct types inside kernels (will warn during backward pass with `wp.verbose` if using gradients)
- Add support for step-through VSCode debugging of kernel code with standalone LLVM compiler, see `wp.breakpoint()`, and `walkthrough_debug.py`
- Add support for default values on built-in functions
- Add support for multi-valued `@wp.func` functions
- Add support for `pass`, `continue`, and `break` statements
- Add missing `__sincos_stret` symbol for macOS
- Add support for gradient propagation through `wp.Mesh.points`, and other cases where arrays are passed to native functions
- Add support for Python `@` operator as an alias for `wp.matmul()`
- Add XPBD support for particle-particle collision
- Add support for individual particle radii: `ModelBuilder.add_particle` has a new `radius` argument, `Model.particle_radius` is now a Warp array
- Add per-particle flags as a `Model.particle_flags` Warp array, introduce `PARTICLE_FLAG_ACTIVE` to define whether a particle is being simulated and participates in contact dynamics
- Add support for Python bitwise operators `&`, `|`, `~`, `<<`, `>>`
- Switch to using standalone LLVM compiler by default for `cpu` devices
- Split `omni.warp` into `omni.warp.core` for Omniverse applications that want to use the Warp Python module with minimal additional dependencies
- Disable kernel gradient generation by default inside Omniverse for improved compile times
- Fix for bounds checking on element access of vector/matrix types
- Fix for stream initialization when a custom (non-primary) external CUDA context has been set on the calling thread
- Fix for duplicate `@wp.struct` registration during hot reload
- Fix for array `unot()` operator so kernel writers can use `if not array:` syntax
- Fix for case where dynamic loops are nested within unrolled loops
- Change `wp.hash_grid_point_id()` now returns -1 if the `wp.HashGrid` has not been reserved before
- Deprecate `wp.Model.soft_contact_distance` which is now replaced by `wp.Model.particle_radius`
- Deprecate single scalar particle radius (should be a per-particle array)
## [0.8.2] - 2023-04-21
- Add `ModelBuilder.soft_contact_max` to control the maximum number of soft contacts that can be registered. Use `Model.allocate_soft_contacts(new_count)` to change count on existing `Model` objects.
- Add support for `bool` parameters
- Add support for logical boolean operators with `int` types
- Fix for `wp.quat()` default constructor
- Fix conditional reassignments
- Add sign determination using angle weighted normal version of `wp.mesh_query_point()` as `wp.mesh_query_sign_normal()`
- Add sign determination using winding number of `wp.mesh_query_point()` as `wp.mesh_query_sign_winding_number()`
- Add query point without sign determination `wp.mesh_query_no_sign()`
## [0.8.1] - 2023-04-13
- Fix for regression when passing flattened numeric lists as matrix arguments to kernels
- Fix for regressions when passing `wp.struct` types with uninitialized (`None`) member attributes
## [0.8.0] - 2023-04-05
- Add `Texture Write` node for updating dynamic RTX textures from Warp kernels / nodes
- Add multi-dimensional kernel support to Warp Kernel Node
- Add `wp.load_module()` to pre-load specific modules (pass `recursive=True` to load recursively)
- Add `wp.poisson()` for sampling Poisson distributions
- Add support for UsdPhysics schema see `wp.sim.parse_usd()`
- Add XPBD rigid body implementation plus diff. simulation examples
- Add support for standalone CPU compilation (no host-compiler) with LLVM backed, enable with `--standalone` build option
- Add support for per-timer color in `wp.ScopedTimer()`
- Add support for row-based construction of matrix types outside of kernels
- Add support for setting and getting row vectors for Python matrices, see `matrix.get_row()`, `matrix.set_row()`
- Add support for instantiating `wp.struct` types within kernels
- Add support for indexed arrays, `slice = array[indices]` will now generate a sparse slice of array data
- Add support for generic kernel params, use `def compute(param: Any):`
- Add support for `with wp.ScopedDevice("cuda") as device:` syntax (same for `wp.ScopedStream()`, `wp.Tape()`)
- Add support for creating custom length vector/matrices inside kernels, see `wp.vector()`, and `wp.matrix()`
- Add support for creating identity matrices in kernels with, e.g.: `I = wp.identity(n=3, dtype=float)`
- Add support for unary plus operator (`wp.pos()`)
- Add support for `wp.constant` variables to be used directly in Python without having to use `.val` member
- Add support for nested `wp.struct` types
- Add support for returning `wp.struct` from functions
- Add `--quick` build for faster local dev. iteration (uses a reduced set of SASS arches)
- Add optional `requires_grad` parameter to `wp.from_torch()` to override gradient allocation
- Add type hints for generic vector / matrix types in Python stubs
- Add support for custom user function recording in `wp.Tape()`
- Add support for registering CUTLASS `wp.matmul()` with tape backward pass
- Add support for grids with > 2^31 threads (each dimension may be up to INT_MAX in length)
- Add CPU fallback for `wp.matmul()`
- Optimizations for `wp.launch()`, up to 3x faster launches in common cases
- Fix `wp.randf()` conversion to float to reduce bias for uniform sampling
- Fix capture of `wp.func` and `wp.constant` types from inside Python closures
- Fix for CUDA on WSL
- Fix for matrices in structs
- Fix for transpose indexing for some non-square matrices
- Enable Python faulthandler by default
- Update to VS2019
### Breaking Changes
- `wp.constant` variables can now be treated as their true type, accessing the underlying value through `constant.val` is no longer supported
- `wp.sim.model.ground_plane` is now a `wp.array` to support gradient, users should call `builder.set_ground_plane()` to create the ground
- `wp.sim` capsule, cones, and cylinders are now aligned with the default USD up-axis
## [0.7.2] - 2023-02-15
- Reduce test time for vec/math types
- Clean-up CUDA disabled build pipeline
- Remove extension.gen.toml to make Kit packages Python version independent
- Handle additional cases for array indexing inside Python
## [0.7.1] - 2023-02-14
- Disabling some slow tests for Kit
- Make unit tests run on first GPU only by default
## [0.7.0] - 2023-02-13
- Add support for arbitrary length / type vector and matrices e.g.: `wp.vec(length=7, dtype=wp.float16)`, see `wp.vec()`, and `wp.mat()`
- Add support for `array.flatten()`, `array.reshape()`, and `array.view()` with NumPy semantics
- Add support for slicing `wp.array` types in Python
- Add `wp.from_ptr()` helper to construct arrays from an existing allocation
- Add support for `break` statements in ranged-for and while loops (backward pass support currently not implemented)
- Add built-in mathematic constants, see `wp.pi`, `wp.e`, `wp.log2e`, etc.
- Add built-in conversion between degrees and radians, see `wp.degrees()`, `wp.radians()`
- Add security pop-up for Kernel Node
- Improve error handling for kernel return values
## [0.6.3] - 2023-01-31
- Add DLPack utilities, see `wp.from_dlpack()`, `wp.to_dlpack()`
- Add Jax utilities, see `wp.from_jax()`, `wp.to_jax()`, `wp.device_from_jax()`, `wp.device_to_jax()`
- Fix for Linux Kit extensions OM-80132, OM-80133
## [0.6.2] - 2023-01-19
- Updated `wp.from_torch()` to support more data types
- Updated `wp.from_torch()` to automatically determine the target Warp data type if not specified
- Updated `wp.from_torch()` to support non-contiguous tensors with arbitrary strides
- Add CUTLASS integration for dense GEMMs, see `wp.matmul()` and `wp.matmul_batched()`
- Add QR and Eigen decompositions for `mat33` types, see `wp.qr3()`, and `wp.eig3()`
- Add default (zero) constructors for matrix types
- Add a flag to suppress all output except errors and warnings (set `wp.config.quiet = True`)
- Skip recompilation when Kernel Node attributes are edited
- Allow optional attributes for Kernel Node
- Allow disabling backward pass code-gen on a per-kernel basis, use `@wp.kernel(enable_backward=False)`
- Replace Python `imp` package with `importlib`
- Fix for quaternion slerp gradients (`wp.quat_slerp()`)
## [0.6.1] - 2022-12-05
- Fix for non-CUDA builds
- Fix strides computation in array_t constructor, fixes a bug with accessing mesh indices through mesh.indices[]
- Disable backward pass code generation for kernel node (4-6x faster compilation)
- Switch to linbuild for universal Linux binaries (affects TeamCity builds only)
## [0.6.0] - 2022-11-28
- Add support for CUDA streams, see `wp.Stream`, `wp.get_stream()`, `wp.set_stream()`, `wp.synchronize_stream()`, `wp.ScopedStream`
- Add support for CUDA events, see `wp.Event`, `wp.record_event()`, `wp.wait_event()`, `wp.wait_stream()`, `wp.Stream.record_event()`, `wp.Stream.wait_event()`, `wp.Stream.wait_stream()`
- Add support for PyTorch stream interop, see `wp.stream_from_torch()`, `wp.stream_to_torch()`
- Add support for allocating host arrays in pinned memory for asynchronous data transfers, use `wp.array(..., pinned=True)` (default is non-pinned)
- Add support for direct conversions between all scalar types, e.g.: `x = wp.uint8(wp.float64(3.0))`
- Add per-module option to enable fast math, use `wp.set_module_options({"fast_math": True})`, fast math is now *disabled* by default
- Add support for generating CUBIN kernels instead of PTX on systems with older drivers
- Add user preference options for CUDA kernel output ("ptx" or "cubin", e.g.: `wp.config.cuda_output = "ptx"` or per-module `wp.set_module_options({"cuda_output": "ptx"})`)
- Add kernel node for OmniGraph
- Add `wp.quat_slerp()`, `wp.quat_to_axis_angle()`, `wp.rotate_rodriquez()` and adjoints for all remaining quaternion operations
- Add support for unrolling for-loops when range is a `wp.constant`
- Add support for arithmetic operators on built-in vector / matrix types outside of `wp.kernel`
- Add support for multiple solution variables in `wp.optim` Adam optimization
- Add nested attribute support for `wp.struct` attributes
- Add missing adjoint implementations for spatial math types, and document all functions with missing adjoints
- Add support for retrieving NanoVDB tiles and voxel size, see `wp.Volume.get_tiles()`, and `wp.Volume.get_voxel_size()`
- Add support for store operations on integer NanoVDB volumes, see `wp.volume_store_i()`
- Expose `wp.Mesh` points, indices, as arrays inside kernels, see `wp.mesh_get()`
- Optimizations for `wp.array` construction, 2-3x faster on average
- Optimizations for URDF import
- Fix various deployment issues by statically linking with all CUDA libs
- Update warp.so/warp.dll to CUDA Toolkit 11.5
## [0.5.1] - 2022-11-01
- Fix for unit tests in Kit
## [0.5.0] - 2022-10-31
- Add smoothed particle hydrodynamics (SPH) example, see `example_sph.py`
- Add support for accessing `array.shape` inside kernels, e.g.: `width = arr.shape[0]`
- Add dependency tracking to hot-reload modules if dependencies were modified
- Add lazy acquisition of CUDA kernel contexts (save ~300Mb of GPU memory in MGPU environments)
- Add BVH object, see `wp.Bvh` and `bvh_query_ray()`, `bvh_query_aabb()` functions
- Add component index operations for `spatial_vector`, `spatial_matrix` types
- Add `wp.lerp()` and `wp.smoothstep()` builtins
- Add `wp.optim` module with implementation of the Adam optimizer for float and vector types
- Add support for transient Python modules (fix for Houdini integration)
- Add `wp.length_sq()`, `wp.trace()` for vector / matrix types respectively
- Add missing adjoints for `wp.quat_rpy()`, `wp.determinant()`
- Add `wp.atomic_min()`, `wp.atomic_max()` operators
- Add vectorized version of `wp.sim.model.add_cloth_mesh()`
- Add NVDB volume allocation API, see `wp.Volume.allocate()`, and `wp.Volume.allocate_by_tiles()`
- Add NVDB volume write methods, see `wp.volume_store_i()`, `wp.volume_store_f()`, `wp.volume_store_v()`
- Add MGPU documentation
- Add example showing how to compute Jacobian of multiple environments in parallel, see `example_jacobian_ik.py`
- Add `wp.Tape.zero()` support for `wp.struct` types
- Make SampleBrowser an optional dependency for Kit extension
- Make `wp.Mesh` object accept both 1d and 2d arrays of face vertex indices
- Fix for reloading of class member kernel / function definitions using `importlib.reload()`
- Fix for hashing of `wp.constants()` not invalidating kernels
- Fix for reload when multiple `.ptx` versions are present
- Improved error reporting during code-gen
## [0.4.3] - 2022-09-20
- Update all samples to use GPU interop path by default
- Fix for arrays > 2GB in length
- Add support for per-vertex USD mesh colors with `wp.render` class
## [0.4.2] - 2022-09-07
- Register Warp samples to the sample browser in Kit
- Add NDEBUG flag to release mode kernel builds
- Fix for particle solver node when using a large number of particles
- Fix for broken cameras in Warp sample scenes
## [0.4.1] - 2022-08-30
- Add geometry sampling methods, see `wp.sample_unit_cube()`, `wp.sample_unit_disk()`, etc
- Add `wp.lower_bound()` for searching sorted arrays
- Add an option for disabling code-gen of backward pass to improve compilation times, see `wp.set_module_options({"enable_backward": False})`, True by default
- Fix for using Warp from Script Editor or when module does not have a `__file__` attribute
- Fix for hot reload of modules containing `wp.func()` definitions
- Fix for debug flags not being set correctly on CUDA when `wp.config.mode == "debug"`, this enables bounds checking on CUDA kernels in debug mode
- Fix for code gen of functions that do not return a value
## [0.4.0] - 2022-08-09
- Fix for FP16 conversions on GPUs without hardware support
- Fix for `runtime = None` errors when reloading the Warp module
- Fix for PTX architecture version when running with older drivers, see `wp.config.ptx_target_arch`
- Fix for USD imports from `__init__.py`, defer them to individual functions that need them
- Fix for robustness issues with sign determination for `wp.mesh_query_point()`
- Fix for `wp.HashGrid` memory leak when creating/destroying grids
- Add CUDA version checks for toolkit and driver
- Add support for cross-module `@wp.struct` references
- Support running even if CUDA initialization failed, use `wp.is_cuda_available()` to check availability
- Statically linking with the CUDA runtime library to avoid deployment issues
### Breaking Changes
- Removed `wp.runtime` reference from the top-level module, as it should be considered private
## [0.3.2] - 2022-07-19
- Remove Torch import from `__init__.py`, defer import to `wp.from_torch()`, `wp.to_torch()`
## [0.3.1] - 2022-07-12
- Fix for marching cubes reallocation after initialization
- Add support for closest point between line segment tests, see `wp.closest_point_edge_edge()` builtin
- Add support for per-triangle elasticity coefficients in simulation, see `wp.sim.ModelBuilder.add_cloth_mesh()`
- Add support for specifying default device, see `wp.set_device()`, `wp.get_device()`, `wp.ScopedDevice`
- Add support for multiple GPUs (e.g., `"cuda:0"`, `"cuda:1"`), see `wp.get_cuda_devices()`, `wp.get_cuda_device_count()`, `wp.get_cuda_device()`
- Add support for explicitly targeting the current CUDA context using device alias `"cuda"`
- Add support for using arbitrary external CUDA contexts, see `wp.map_cuda_device()`, `wp.unmap_cuda_device()`
- Add PyTorch device aliasing functions, see `wp.device_from_torch()`, `wp.device_to_torch()`
### Breaking Changes
- A CUDA device is used by default, if available (aligned with `wp.get_preferred_device()`)
- `wp.ScopedCudaGuard` is deprecated, use `wp.ScopedDevice` instead
- `wp.synchronize()` now synchronizes all devices; for finer-grained control, use `wp.synchronize_device()`
- Device alias `"cuda"` now refers to the current CUDA context, rather than a specific device like `"cuda:0"` or `"cuda:1"`
## [0.3.0] - 2022-07-08
- Add support for FP16 storage type, see `wp.float16`
- Add support for per-dimension byte strides, see `wp.array.strides`
- Add support for passing Python classes as kernel arguments, see `@wp.struct` decorator
- Add additional bounds checks for builtin matrix types
- Add additional floating point checks, see `wp.config.verify_fp`
- Add interleaved user source with generated code to aid debugging
- Add generalized GPU marching cubes implementation, see `wp.MarchingCubes` class
- Add additional scalar*matrix vector operators
- Add support for retrieving a single row from builtin types, e.g.: `r = m33[i]`
- Add `wp.log2()` and `wp.log10()` builtins
- Add support for quickly instancing `wp.sim.ModelBuilder` objects to improve env. creation performance for RL
- Remove custom CUB version and improve compatibility with CUDA 11.7
- Fix to preserve external user-gradients when calling `wp.Tape.zero()`
- Fix to only allocate gradient of a Torch tensor if `requires_grad=True`
- Fix for missing `wp.mat22` constructor adjoint
- Fix for ray-cast precision in edge case on GPU (watertightness issue)
- Fix for kernel hot-reload when definition changes
- Fix for NVCC warnings on Linux
- Fix for generated function names when kernels are defined as class functions
- Fix for reload of generated CPU kernel code on Linux
- Fix for example scripts to output USD at 60 timecodes per-second (better Kit compatibility)
## [0.2.3] - 2022-06-13
- Fix for incorrect 4d array bounds checking
- Fix for `wp.constant` changes not updating module hash
- Fix for stale CUDA kernel cache when CPU kernels launched first
- Array gradients are now allocated along with the arrays and accessible as `wp.array.grad`, users should take care to always call `wp.Tape.zero()` to clear gradients between different invocations of `wp.Tape.backward()`
- Added `wp.array.fill_()` to set all entries to a scalar value (4-byte values only currently)
### Breaking Changes
- Tape `capture` option has been removed, users can now capture tapes inside existing CUDA graphs (e.g.: inside Torch)
- Scalar loss arrays should now explicitly set `requires_grad=True` at creation time
## [0.2.2] - 2022-05-30
- Fix for `from import *` inside Warp initialization
- Fix for body space velocity when using deforming Mesh objects with scale
- Fix for noise gradient discontinuities affecting `wp.curlnoise()`
- Fix for `wp.from_torch()` to correctly preserve shape
- Fix for URDF parser incorrectly passing density to scale parameter
- Optimizations for startup time from 3s -> 0.3s
- Add support for custom kernel cache location, Warp will now store generated binaries in the user's application directory
- Add support for cross-module function references, e.g.: call another modules @wp.func functions
- Add support for overloading `@wp.func` functions based on argument type
- Add support for calling built-in functions directly from Python interpreter outside kernels (experimental)
- Add support for auto-complete and docstring lookup for builtins in IDEs like VSCode, PyCharm, etc
- Add support for doing partial array copies, see `wp.copy()` for details
- Add support for accessing mesh data directly in kernels, see `wp.mesh_get_point()`, `wp.mesh_get_index()`, `wp.mesh_eval_face_normal()`
- Change to only compile for targets where kernel is launched (e.g.: will not compile CPU unless explicitly requested)
### Breaking Changes
- Builtin methods such as `wp.quat_identity()` now call the Warp native implementation directly and will return a `wp.quat` object instead of NumPy array
- NumPy implementations of many builtin methods have been moved to `wp.utils` and will be deprecated
- Local `@wp.func` functions should not be namespaced when called, e.g.: previously `wp.myfunc()` would work even if `myfunc()` was not a builtin
- Removed `wp.rpy2quat()`, please use `wp.quat_rpy()` instead
## [0.2.1] - 2022-05-11
- Fix for unit tests in Kit
## [0.2.0] - 2022-05-02
### Warp Core
- Fix for unrolling loops with negative bounds
- Fix for unresolved symbol `hash_grid_build_device()` not found when lib is compiled without CUDA support
- Fix for failure to load nvrtc-builtins64_113.dll when user has a newer CUDA toolkit installed on their machine
- Fix for conversion of Torch tensors to `wp.array` with a vector dtype (incorrect row count)
- Fix for `warp.dll` not found on some Windows installations
- Fix for macOS builds on Clang 13.x
- Fix for step-through debugging of kernels on Linux
- Add argument type checking for user defined `@wp.func` functions
- Add support for custom iterable types, supports ranges, hash grid, and mesh query objects
- Add support for multi-dimensional arrays, for example use `x = array[i,j,k]` syntax to address a 3-dimensional array
- Add support for multi-dimensional kernel launches, use `launch(kernel, dim=(i,j,k), ...` and `i,j,k = wp.tid()` to obtain thread indices
- Add support for bounds-checking array memory accesses in debug mode, use `wp.config.mode = "debug"` to enable
- Add support for differentiating through dynamic and nested for-loops
- Add support for evaluating MLP neural network layers inside kernels with custom activation functions, see `wp.mlp()`
- Add additional NVDB sampling methods and adjoints, see `wp.volume_sample_i()`, `wp.volume_sample_f()`, and `wp.volume_sample_vec()`
- Add support for loading zlib compressed NVDB volumes, see `wp.Volume.load_from_nvdb()`
- Add support for triangle intersection testing, see `wp.intersect_tri_tri()`
- Add support for NVTX profile zones in `wp.ScopedTimer()`
- Add support for additional transform and quaternion math operations, see `wp.inverse()`, `wp.quat_to_matrix()`, `wp.quat_from_matrix()`
- Add fast math (`--fast-math`) to kernel compilation by default
- Add `wp.torch` import by default (if PyTorch is installed)
### Warp Kit
- Add Kit menu for browsing Warp documentation and example scenes under 'Window->Warp'
- Fix for OgnParticleSolver.py example when collider is coming from Read Prim into Bundle node
### Warp Sim
- Fix for joint attachment forces
- Fix for URDF importer and floating base support
- Add examples showing how to use differentiable forward kinematics to solve inverse kinematics
- Add examples for URDF cartpole and quadruped simulation
### Breaking Changes
- `wp.volume_sample_world()` is now replaced by `wp.volume_sample_f/i/vec()` which operate in index (local) space. Users should use `wp.volume_world_to_index()` to transform points from world space to index space before sampling.
- `wp.mlp()` expects multi-dimensional arrays instead of one-dimensional arrays for inference, all other semantics remain the same as earlier versions of this API.
- `wp.array.length` member has been removed, please use `wp.array.shape` to access array dimensions, or use `wp.array.size` to get total element count
- Marking `dense_gemm()`, `dense_chol()`, etc methods as experimental until we revisit them
## [0.1.25] - 2022-03-20
- Add support for class methods to be Warp kernels
- Add HashGrid reserve() so it can be used with CUDA graphs
- Add support for CUDA graph capture of tape forward/backward passes
- Add support for Python 3.8.x and 3.9.x
- Add hyperbolic trigonometric functions, see `wp.tanh()`, `wp.sinh()`, `wp.cosh()`
- Add support for floored division on integer types
- Move tests into core library so they can be run in Kit environment
## [0.1.24] - 2022-03-03
### Warp Core
- Add NanoVDB support, see `wp.volume_sample*()` methods
- Add support for reading compile-time constants in kernels, see `wp.constant()`
- Add support for __cuda_array_interface__ protocol for zero-copy interop with PyTorch, see `wp.torch.to_torch()`
- Add support for additional numeric types, i8, u8, i16, u16, etc
- Add better checks for device strings during allocation / launch
- Add support for sampling random numbers with a normal distribution, see `wp.randn()`
- Upgrade to CUDA 11.3
- Update example scenes to Kit 103.1
- Deduce array dtype from np.array when one is not provided
- Fix for ranged for loops with negative step sizes
- Fix for 3d and 4d spherical gradient distributions
## [0.1.23] - 2022-02-17
### Warp Core
- Fix for generated code folder being removed during Showroom installation
- Fix for macOS support
- Fix for dynamic for-loop code gen edge case
- Add procedural noise primitives, see `wp.noise()`, `wp.pnoise()`, `wp.curlnoise()`
- Move simulation helpers our of test into `wp.sim` module
## [0.1.22] - 2022-02-14
### Warp Core
- Fix for .so reloading on Linux
- Fix for while loop code-gen in some edge cases
- Add rounding functions `wp.round()`, `wp.rint()`, `wp.trunc()`, `wp.floor()`, `wp.ceil()`
- Add support for printing strings and formatted strings from kernels
- Add MSVC compiler version detection and require minimum
### Warp Sim
- Add support for universal and compound joint types
## [0.1.21] - 2022-01-19
### Warp Core
- Fix for exception on shutdown in empty `wp.array` objects
- Fix for hot reload of CPU kernels in Kit
- Add hash grid primitive for point-based spatial queries, see `wp.hash_grid_query()`, `wp.hash_grid_query_next()`
- Add new PRNG methods using PCG-based generators, see `wp.rand_init()`, `wp.randf()`, `wp.randi()`
- Add support for AABB mesh queries, see `wp.mesh_query_aabb()`, `wp.mesh_query_aabb_next()`
- Add support for all Python `range()` loop variants
- Add builtin vec2 type and additional math operators, `wp.pow()`, `wp.tan()`, `wp.atan()`, `wp.atan2()`
- Remove dependency on CUDA driver library at build time
- Remove unused NVRTC binary dependencies (50mb smaller Linux distribution)
### Warp Sim
- Bundle import of multiple shapes for simulation nodes
- New OgnParticleVolume node for sampling shapes -> particles
- New OgnParticleSolver node for DEM style granular materials
## [0.1.20] - 2021-11-02
- Updates to the ripple solver for GTC (support for multiple colliders, buoyancy, etc)
## [0.1.19] - 2021-10-15
- Publish from 2021.3 to avoid omni.graph database incompatibilities
## [0.1.18] - 2021-10-08
- Enable Linux support (tested on 20.04)
## [0.1.17] - 2021-09-30
- Fix for 3x3 SVD adjoint
- Fix for A6000 GPU (bump compute model to sm_52 minimum)
- Fix for .dll unload on rebuild
- Fix for possible array destruction warnings on shutdown
- Rename spatial_transform -> transform
- Documentation update
## [0.1.16] - 2021-09-06
- Fix for case where simple assignments (a = b) incorrectly generated reference rather than value copy
- Handle passing zero-length (empty) arrays to kernels
## [0.1.15] - 2021-09-03
- Add additional math library functions (asin, etc)
- Add builtin 3x3 SVD support
- Add support for named constants (True, False, None)
- Add support for if/else statements (differentiable)
- Add custom memset kernel to avoid CPU overhead of cudaMemset()
- Add rigid body joint model to `wp.sim` (based on Brax)
- Add Linux, MacOS support in core library
- Fix for incorrectly treating pure assignment as reference instead of value copy
- Removes the need to transfer array to CPU before numpy conversion (will be done implicitly)
- Update the example OgnRipple wave equation solver to use bundles
## [0.1.14] - 2021-08-09
- Fix for out-of-bounds memory access in CUDA BVH
- Better error checking after kernel launches (use `wp.config.verify_cuda=True`)
- Fix for vec3 normalize adjoint code
## [0.1.13] - 2021-07-29
- Remove OgnShrinkWrap.py test node
## [0.1.12] - 2021-07-29
- Switch to Woop et al.'s watertight ray-tri intersection test
- Disable --fast-math in CUDA compilation step for improved precision
## [0.1.11] - 2021-07-28
- Fix for `wp.mesh_query_ray()` returning incorrect t-value
## [0.1.10] - 2021-07-28
- Fix for OV extension fwatcher filters to avoid hot-reload loop due to OGN regeneration
## [0.1.9] - 2021-07-21
- Fix for loading sibling DLL paths
- Better type checking for built-in function arguments
- Added runtime docs, can now list all builtins using `wp.print_builtins()`
## [0.1.8] - 2021-07-14
- Fix for hot-reload of CUDA kernels
- Add Tape object for replaying differentiable kernels
- Add helpers for Torch interop (convert `torch.Tensor` to `wp.Array`)
## [0.1.7] - 2021-07-05
- Switch to NVRTC for CUDA runtime
- Allow running without host compiler
- Disable asserts in kernel release mode (small perf. improvement)
## [0.1.6] - 2021-06-14
- Look for CUDA toolchain in target-deps
## [0.1.5] - 2021-06-14
- Rename OgLang -> Warp
- Improve CUDA environment error checking
- Clean-up some logging, add verbose mode (`wp.config.verbose`)
## [0.1.4] - 2021-06-10
- Add support for mesh raycast
## [0.1.3] - 2021-06-09
- Add support for unary negation operator
- Add support for mutating variables during dynamic loops (non-differentiable)
- Add support for in-place operators
- Improve kernel cache start up times (avoids adjointing before cache check)
- Update README.md with requirements / examples
## [0.1.2] - 2021-06-03
- Add support for querying mesh velocities
- Add CUDA graph support, see `wp.capture_begin()`, `wp.capture_end()`, `wp.capture_launch()`
- Add explicit initialization phase, `wp.init()`
- Add variational Euler solver (sim)
- Add contact caching, switch to nonlinear friction model (sim)
- Fix for Linux/macOS support
## [0.1.1] - 2021-05-18
- Fix bug with conflicting CUDA contexts
## [0.1.0] - 2021-05-17
- Initial publish for alpha testing
| 52,860 | Markdown | 55.962284 | 302 | 0.753462 |
NVIDIA/warp/exts/omni.warp/docs/README.md | # Warp [omni.warp]
This extension provides a collection of OmniGraph nodes and sample scenes demonstrating uses of Warp in OmniGraph.
This extension automatically enables the omni.warp.core extension, which allows Warp to be used by calling `import warp`
in Python code.
## About Warp
NVIDIA Warp is a Python framework for writing high-performance simulation and graphics code.
Compute kernels are defined in Python syntax and JIT converted to C++/CUDA and compiled at runtime.
## Sample Scenes
This extension adds several scenes that showcase the use of Warp in OmniGraph to the Sample Browser under the "Warp" category.
The Sample-Browser tab can be shown by selecting Window -> Browsers -> Examples.
The location of the USD files and assets on disk can be opened in a file browser by selecting Window -> Warp -> Sample Scenes.
## OmniGraph Nodes
The OmniGraph nodes added by this extension are found under the "Warp" category
in the OmniGraph Editor's node library.
## Documentation
A webpage containing material to get started using Warp in Omniverse can be opened in a web browser by selecting
Window -> Warp -> Getting Started.
The online Warp documentation can be accessed by selecting Window -> Warp -> Documentation, which automatically opens
a web browser at https://nvidia.github.io/warp.
| 1,312 | Markdown | 40.031249 | 126 | 0.78811 |
NVIDIA/warp/exts/omni.warp.core/PACKAGE-LICENSES/omni.warp.core-LICENSE.md | 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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
NVIDIA/warp/exts/omni.warp.core/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.1.1"
authors = ["NVIDIA"]
title = "Warp Core"
description="The core Warp Python module"
readme = "docs/README.md"
repository="https://github.com/nvidia/warp"
category = "core"
keywords = ["warp", "simulation"]
changelog="docs/CHANGELOG.md"
support_level = "Enterprise"
preview_image = "data/preview.png"
icon = "data/icon.png"
# Watch files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.py"]
# Extension module
# It must be defined before the module `warp` in order to give
# the `omni.warp.core` extension a chance to create a symlink towards Warp's
# core directory, if needed, before Carbonite tries to evaluate `import warp`.
[[python.module]]
name = "omni.warp.core"
# Core language module
[[python.module]]
name = "warp"
path = "."
public = true
# Kit testing flags
[[test]]
pyCoverageOmit = [
"warp/stubs.py",
"warp/jax.py",
"warp/torch.py",
"warp/build.py",
"warp/build_dll.py",
"warp/sim/**",
"warp/render/**",
"warp/optim/**",
"warp/fem/**",
"warp/thirdparty/**",
"warp/tests/**"
]
pyCoverageThreshold = 40
timeout = 900
| 1,192 | TOML | 22.392156 | 78 | 0.671141 |
NVIDIA/warp/exts/omni.warp.core/omni/warp/core/__init__.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.
"""Public API for the omni.warp.core extension"""
# Register the extension by importing its entry point class.
from omni.warp.core._impl.extension import OmniWarpCoreExtension as _
| 606 | Python | 49.583329 | 76 | 0.806931 |
NVIDIA/warp/exts/omni.warp.core/omni/warp/core/_impl/extension.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 os
import stat
import subprocess
import sys
from typing import Optional
import omni.ext
HERE = os.path.dirname(__file__)
# Path to the `exts/omni.warp.core` folder.
EXT_PATH = os.path.realpath(os.path.join(HERE, "..", "..", "..", ".."))
# Path to the `warp` link/folder located in `exts/omni.warp.core`.
LOCAL_LIB_PATH = os.path.join(EXT_PATH, "warp")
# Warp's core library path, relative to the `exts/omni.warp.core` folder.
LIB_PATH_REL = os.path.join("..", "..", "warp")
# Warp's core library path.
LIB_PATH_ABS = os.path.realpath(os.path.join(EXT_PATH, LIB_PATH_REL))
def _read_link(path: str) -> Optional[str]:
try:
dst_path = os.readlink(path)
except Exception:
# The given path doesn't exist or the link is invalid.
return None
if os.name == "nt" and dst_path.startswith("\\\\?\\"):
return dst_path[4:]
return dst_path
class OmniWarpCoreExtension(omni.ext.IExt):
def on_startup(self, ext_id):
# We want to make Warp's library available through this `omni.warp.core`
# extension. Due to `extension.toml` expecting the Python package to be
# located at `exts/omni.warp.core/warp`, one way to do achieve that is
# to create a symlink to the actual `warp` folder.
# However, symlinks tend to be annoying to deploy to Windows users since
# they require special privileges, so we don't commit it as part of
# our code repository and, instead, we try to create a link in one way
# or another while the extension is being loaded.
# Eventually, this link is only used/created when developers are loading
# the extension directly from Warp's code repository.
# End-users loading the published extension from Omniverse won't see or
# need any link since the process that publishes the extension will
# include a copy of Warp's library.
# Try reading the content of the link.
link_dst_path = _read_link(LOCAL_LIB_PATH)
try:
# We're using `os.stat()` instead of `os.path.is*()` since
# we don't want to follow links, otherwise calling `os.path.isdir()`
# would return `True` for links pointing to directories.
file_stat = os.stat(LOCAL_LIB_PATH, follow_symlinks=False)
file_stat_mode = file_stat.st_mode
except FileNotFoundError:
file_stat_mode = 0
# Check if we have a directory.
# Windows' junctions are a bit special and return `True` when
# checked against `stat.S_ISDIR()`, so we also need to check that
# the link is invalid, in which case we can safely assume that we have
# an actual directory instead of a junction.
is_dir = stat.S_ISDIR(file_stat_mode) and link_dst_path is None
if not is_dir and link_dst_path not in (LIB_PATH_REL, LIB_PATH_ABS):
# No valid folder/link corresponding to the library were found in
# the extension, so let's try creating a new link.
if stat.S_ISREG(file_stat_mode) or stat.S_ISLNK(file_stat_mode):
# We have an invalid file/link, remove it.
os.remove(LOCAL_LIB_PATH)
try:
os.symlink(LIB_PATH_REL, LOCAL_LIB_PATH, target_is_directory=True)
except OSError as e:
# On Windows, creating symbolic links might fail due to lack of
# privileges. In that case, try creating a junction instead.
if os.name == "nt":
# Junctions don't support relative paths so we need
# to use an absolute path for the destination.
cmd = ("mklink", "/j", LOCAL_LIB_PATH, LIB_PATH_ABS)
subprocess.run(cmd, stdout=subprocess.DEVNULL, shell=True)
else:
raise RuntimeError(f"Failed to create the symlink `{LOCAL_LIB_PATH}`") from e
# Due to Kit's fast importer mechanism having already cached our
# extension's Python path before we had a chance to create the link,
# we need to update Python's standard `sys.path` for `import warp`
# to work as expected.
sys.path.insert(0, EXT_PATH)
| 4,687 | Python | 43.647619 | 97 | 0.640708 |
NVIDIA/warp/exts/omni.warp.core/omni/warp/core/_impl/__init__.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.
"""Private Python implementation for the extension."""
| 479 | Python | 52.333328 | 76 | 0.810021 |
NVIDIA/warp/exts/omni.warp.core/omni/warp/core/tests/__init__.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.
"""Tests for the extension omni.warp."""
scan_for_test_modules = True
| 495 | Python | 44.090905 | 76 | 0.8 |
NVIDIA/warp/exts/omni.warp.core/omni/warp/core/tests/test_ext.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.
"""Tests for the Warp core library in Kit.
Only a trimmed down list of tests is run since the full suite is too slow.
More information about testing in Kit:
https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/testing_exts_python.html
"""
import importlib
import omni.kit.test
TEST_DESCS = (
("test_array", "TestArray"),
("test_array_reduce", "TestArrayReduce"),
("test_bvh", "TestBvh"),
("test_codegen", "TestCodeGen"),
("test_compile_consts", "TestConstants"),
("test_conditional", "TestConditional"),
("test_ctypes", "TestCTypes"),
("test_devices", "TestDevices"),
("test_dlpack", "TestDLPack"),
("test_fabricarray", "TestFabricArray"),
("test_func", "TestFunc"),
("test_generics", "TestGenerics"),
("test_grad_customs", "TestGradCustoms"),
("test_hash_grid", "TestHashGrid"),
("test_indexedarray", "TestIndexedArray"),
("test_launch", "TestLaunch"),
("test_marching_cubes", "TestMarchingCubes"),
("test_mat_lite", "TestMatLite"),
("test_math", "TestMath"),
("test_matmul_lite", "TestMatmulLite"),
("test_mesh", "TestMesh"),
("test_mesh_query_aabb", "TestMeshQueryAABBMethods"),
("test_mesh_query_point", "TestMeshQueryPoint"),
("test_mesh_query_ray", "TestMeshQueryRay"),
("test_modules_lite", "TestModuleLite"),
("test_noise", "TestNoise"),
("test_operators", "TestOperators"),
("test_quat", "TestQuat"),
("test_rand", "TestRand"),
("test_reload", "TestReload"),
("test_rounding", "TestRounding"),
("test_runlength_encode", "TestRunlengthEncode"),
("test_sparse", "TestSparse"),
("test_streams", "TestStreams"),
("test_tape", "TestTape"),
("test_transient_module", "TestTransientModule"),
("test_types", "TestTypes"),
("test_utils", "TestUtils"),
("test_vec_lite", "TestVecLite"),
("test_volume", "TestVolume"),
("test_volume_write", "TestVolumeWrite"),
)
test_clss = []
for module_name, cls_name in TEST_DESCS:
module = importlib.import_module(f"warp.tests.{module_name}")
cls = getattr(module, cls_name)
# Change the base class from unittest.TestCase
cls.__bases__ = (omni.kit.test.AsyncTestCase,)
test_clss.append(cls)
# Each test class needs to be defined at the module level to be found by
# the test runners.
locals().update({str(i): x for i, x in enumerate(test_clss)})
| 2,819 | Python | 34.696202 | 95 | 0.669741 |
NVIDIA/warp/exts/omni.warp.core/docs/CHANGELOG.md | # CHANGELOG
## [1.1.1] - 2024-05-24
- Implicitly initialize Warp when first required
- Speed up `omni.warp.core`'s startup time
## [1.1.0] - 2024-05-09
- Support returning a value from `@wp.func_native` CUDA functions using type hints
- Improved differentiability of the `wp.sim.FeatherstoneIntegrator`
- Fix gradient propagation for rigid body contacts in `wp.sim.collide()`
- Added support for event-based timing, see `wp.ScopedTimer()`
- Added Tape visualization and debugging functions, see `wp.Tape.visualize()`
- Support constructing Warp arrays from objects that define the `__cuda_array_interface__` attribute
- Support copying a struct to another device, use `struct.to(device)` to migrate struct arrays
- Allow rigid shapes to not have any collisions with other shapes in `wp.sim.Model`
- Change default test behavior to test redundant GPUs (up to 2x)
- Test each example in an individual subprocess
- Polish and optimize various examples and tests
- Allow non-contiguous point arrays to be passed to `wp.HashGrid.build()`
- Upgrade LLVM to 18.1.3 for from-source builds and Linux x86-64 builds
- Build DLL source code as C++17 and require GCC 9.4 as a minimum
- Array clone, assign, and copy are now differentiable
- Use `Ruff` for formatting and linting
- Various documentation improvements (infinity, math constants, etc.)
- Improve URDF importer, handle joint armature
- Allow builtins.bool to be used in Warp data structures
- Use external gradient arrays in backward passes when passed to `wp.launch()`
- Add Conjugate Residual linear solver, see `wp.optim.linear.cr()`
- Fix propagation of gradients on aliased copy of variables in kernels
- Facilitate debugging and speed up `import warp` by eliminating raising any exceptions
- Improve support for nested vec/mat assignments in structs
- Recommend Python 3.9 or higher, which is required for JAX and soon PyTorch.
- Support gradient propagation for indexing sliced multi-dimensional arrays, i.e. `a[i][j]` vs. `a[i, j]`
- Provide an informative message if setting DLL C-types failed, instructing to try rebuilding the library
## [1.0.3] - 2024-04-17
- Add a `support_level` entry to the configuration file of the extensions
## [1.0.2] - 2024-03-22
- Make examples runnable from any location
- Fix the examples not running directly from their Python file
- Add the example gallery to the documentation
- Update `README.md` examples USD location
- Update `example_graph_capture.py` description
## [1.0.1] - 2024-03-15
- Document Device `total_memory` and `free_memory`
- Documentation for allocators, streams, peer access, and generics
- Changed example output directory to current working directory
- Added `python -m warp.examples.browse` for browsing the examples folder
- Print where the USD stage file is being saved
- Added `examples/optim/example_walker.py` sample
- Make the drone example not specific to USD
- Reduce the time taken to run some examples
- Optimise rendering points with a single colour
- Clarify an error message around needing USD
- Raise exception when module is unloaded during graph capture
- Added `wp.synchronize_event()` for blocking the host thread until a recorded event completes
- Flush C print buffers when ending `stdout` capture
- Remove more unneeded CUTLASS files
- Allow setting mempool release threshold as a fractional value
## [1.0.0] - 2024-03-07
- Add `FeatherstoneIntegrator` which provides more stable simulation of articulated rigid body dynamics in generalized coordinates (`State.joint_q` and `State.joint_qd`)
- Introduce `warp.sim.Control` struct to store control inputs for simulations (optional, by default the `Model` control inputs are used as before); integrators now have a different simulation signature: `integrator.simulate(model: Model, state_in: State, state_out: State, dt: float, control: Control)`
- `joint_act` can now behave in 3 modes: with `joint_axis_mode` set to `JOINT_MODE_FORCE` it behaves as a force/torque, with `JOINT_MODE_VELOCITY` it behaves as a velocity target, and with `JOINT_MODE_POSITION` it behaves as a position target; `joint_target` has been removed
- Add adhesive contact to Euler integrators via `Model.shape_materials.ka` which controls the contact distance at which the adhesive force is applied
- Improve handling of visual/collision shapes in URDF importer so visual shapes are not involved in contact dynamics
- Experimental JAX kernel callback support
- Improve module load exception message
- Add `wp.ScopedCapture`
- Removing `enable_backward` warning for callables
- Copy docstrings and annotations from wrapped kernels, functions, structs
## [0.15.1] - 2024-03-05
- Add examples assets to the wheel packages
- Fix broken image link in documentation
- Fix codegen for custom grad functions calling their respective forward functions
- Fix custom grad function handling for functions that have no outputs
- Fix issues when `wp.config.quiet = True`
## [0.15.0] - 2024-03-04
- Add thumbnails to examples gallery
- Apply colored lighting to examples
- Moved `examples` directory under `warp/`
- Add example usage to `python -m warp.tests --help`
- Adding `torch.autograd.function` example + docs
- Add error-checking to array shapes during creation
- Adding `example_graph_capture`
- Add a Diffsim Example of a Drone
- Fix `verify_fp` causing compiler errors and support CPU kernels
- Fix to enable `matmul` to be called in CUDA graph capture
- Enable mempools by default
- Update `wp.launch` to support tuple args
- Fix BiCGSTAB and GMRES producing NaNs when converging early
- Fix warning about backward codegen being disabled in `test_fem`
- Fix `assert_np_equal` when NaN's and tolerance are involved
- Improve error message to discern between CUDA being disabled or not supported
- Support cross-module functions with user-defined gradients
- Suppress superfluous CUDA error when ending capture after errors
- Make output during initialization atomic
- Add `warp.config.max_unroll`, fix custom gradient unrolling
- Support native replay snippets using `@wp.func_native(snippet, replay_snippet=replay_snippet)`
- Look for the CUDA Toolkit in default locations if the `CUDA_PATH` environment variable or `--cuda_path` build option are not used
- Added `wp.ones()` to efficiently create one-initialized arrays
- Rename `wp.config.graph_capture_module_load_default` to `wp.config.enable_graph_capture_module_load_by_default`
## [0.14.0] - 2024-02-19
- Add support for CUDA pooled (stream-ordered) allocators
- Support memory allocation during graph capture
- Support copying non-contiguous CUDA arrays during graph capture
- Improved memory allocation/deallocation performance with pooled allocators
- Use `wp.config.enable_mempools_at_init` to enable pooled allocators during Warp initialization (if supported)
- `wp.is_mempool_supported()` - check if a device supports pooled allocators
- `wp.is_mempool_enabled()`, `wp.set_mempool_enabled()` - enable or disable pooled allocators per device
- `wp.set_mempool_release_threshold()`, `wp.get_mempool_release_threshold()` - configure memory pool release threshold
- Add support for direct memory access between devices
- Improved peer-to-peer memory transfer performance if access is enabled
- Caveat: enabling peer access may impact memory allocation/deallocation performance and increase memory consumption
- `wp.is_peer_access_supported()` - check if the memory of a device can be accessed by a peer device
- `wp.is_peer_access_enabled()`, `wp.set_peer_access_enabled()` - manage peer access for memory allocated using default CUDA allocators
- `wp.is_mempool_access_supported()` - check if the memory pool of a device can be accessed by a peer device
- `wp.is_mempool_access_enabled()`, `wp.set_mempool_access_enabled()` - manage access for memory allocated using pooled CUDA allocators
- Refined stream synchronization semantics
- `wp.ScopedStream` can synchronize with the previous stream on entry and/or exit (only sync on entry by default)
- Functions taking an optional stream argument do no implicit synchronization for max performance (e.g., `wp.copy()`, `wp.launch()`, `wp.capture_launch()`)
- Support for passing a custom `deleter` argument when constructing arrays
- Deprecation of `owner` argument - use `deleter` to transfer ownership
- Optimizations for various core API functions (e.g., `wp.zeros()`, `wp.full()`, and more)
- Fix `wp.matmul()` to always use the correct CUDA context
- Fix memory leak in BSR transpose
- Fix stream synchronization issues when copying non-contiguous arrays
- API change: `wp.matmul()` no longer accepts a device as a parameter; instead, it infers the correct device from the arrays being multiplied
- Updated DLPack utilities to the latest published standard
- External arrays can be imported into Warp directly, e.g., `wp.from_dlpack(external_array)`
- Warp arrays can be exported to consumer frameworks directly, e.g., `jax.dlpack.from_dlpack(warp_array)`
- Added CUDA stream synchronization for CUDA arrays
- The original DLPack protocol can still be used for better performance when stream synchronization is not required, see interoperability docs for details
- `warp.to_dlpack()` is about 3-4x faster in common cases
- `warp.from_dlpack()` is about 2x faster when called with a DLPack capsule
- Fixed a small CPU memory leak related to DLPack interop
- Improved performance of creating arrays
## [0.13.1] - 2024-02-22
- Ensure that the results from the `Noise Deform` are deterministic across different Kit sessions
## [0.13.0] - 2024-02-16
- Update the license to *NVIDIA Software License*, allowing commercial use (see `LICENSE.md`)
- Add `CONTRIBUTING.md` guidelines (for NVIDIA employees)
- Hash CUDA `snippet` and `adj_snippet` strings to fix caching
- Fix `build_docs.py` on Windows
- Add missing `.py` extension to `warp/tests/walkthrough_debug`
- Allow `wp.bool` usage in vector and matrix types
## [0.12.0] - 2024-02-05
- Add a warning when the `enable_backward` setting is set to `False` upon calling `wp.Tape.backward()`
- Fix kernels not being recompiled as expected when defined using a closure
- Change the kernel cache appauthor subdirectory to just "NVIDIA"
- Ensure that gradients attached to PyTorch tensors have compatible strides when calling `wp.from_torch()`
- Add a `Noise Deform` node for OmniGraph that deforms points using a perlin/curl noise
## [0.11.0] - 2024-01-23
- Re-release 1.0.0-beta.7 as a non-pre-release 0.11.0 version so it gets selected by `pip install warp-lang`.
- Introducing a new versioning and release process, detailed in `PACKAGING.md` and resembling that of [Python itself](https://devguide.python.org/developer-workflow/development-cycle/#devcycle):
- The 0.11 release(s) can be found on the `release-0.11` branch.
- Point releases (if any) go on the same minor release branch and only contain bug fixes, not new features.
- The `public` branch, previously used to merge releases into and corresponding with the GitHub `main` branch, is retired.
## [1.0.0-beta.7] - 2024-01-23
- Ensure captures are always enclosed in `try`/`finally`
- Only include .py files from the warp subdirectory into wheel packages
- Fix an extension's sample node failing at parsing some version numbers
- Allow examples to run without USD when possible
- Add a setting to disable the main Warp menu in Kit
- Add iterative linear solvers, see `wp.optim.linear.cg`, `wp.optim.linear.bicgstab`, `wp.optim.linear.gmres`, and `wp.optim.linear.LinearOperator`
- Improve error messages around global variables
- Improve error messages around mat/vec assignments
- Support conversion of scalars to native/ctypes, e.g.: `float(wp.float32(1.23))` or `ctypes.c_float(wp.float32(1.23))`
- Add a constant for infinity, see `wp.inf`
- Add a FAQ entry about array assignments
- Add a mass spring cage diff simulation example, see `examples/example_diffsim_mass_spring_cage.py`
- Add `-s`, `--suite` option for only running tests belonging to the given suites
- Fix common spelling mistakes
- Fix indentation of generated code
- Show deprecation warnings only once
- Improve `wp.render.OpenGLRenderer`
- Create the extension's symlink to the *core library* at runtime
- Fix some built-ins failing to compile the backward pass when nested inside if/else blocks
- Update examples with the new variants of the mesh query built-ins
- Fix type members that weren't zero-initialized
- Fix missing adjoint function for `wp.mesh_query_ray()`
## [1.0.0-beta.6] - 2024-01-10
- Do not create CPU copy of grad array when calling `array.numpy()`
- Fix `assert_np_equal()` bug
- Support Linux AArch64 platforms, including Jetson/Tegra devices
- Add parallel testing runner (invoke with `python -m warp.tests`, use `warp/tests/unittest_serial.py` for serial testing)
- Fix support for function calls in `range()`
- `wp.matmul()` adjoints now accumulate
- Expand available operators (e.g. vector @ matrix, scalar as dividend) and improve support for calling native built-ins
- Fix multi-gpu synchronization issue in `sparse.py`
- Add depth rendering to `wp.render.OpenGLRenderer`, document `wp.render`
- Make `wp.atomic_min()`, `wp.atomic_max()` differentiable
- Fix error reporting using the exact source segment
- Add user-friendly mesh query overloads, returning a struct instead of overwriting parameters
- Address multiple differentiability issues
- Fix backpropagation for returning array element references
- Support passing the return value to adjoints
- Add point basis space and explicit point-based quadrature for `wp.fem`
- Support overriding the LLVM project source directory path using `build_lib.py --build_llvm --llvm_source_path=`
- Fix the error message for accessing non-existing attributes
- Flatten faces array for Mesh constructor in URDF parser
## [1.0.0-beta.5] - 2023-11-22
- Fix for kernel caching when function argument types change
- Fix code-gen ordering of dependent structs
- Fix for `wp.Mesh` build on MGPU systems
- Fix for name clash bug with adjoint code: https://github.com/NVIDIA/warp/issues/154
- Add `wp.frac()` for returning the fractional part of a floating point value
- Add support for custom native CUDA snippets using `@wp.func_native` decorator
- Add support for batched matmul with batch size > 2^16-1
- Add support for transposed CUTLASS `wp.matmul()` and additional error checking
- Add support for quad and hex meshes in `wp.fem`
- Detect and warn when C++ runtime doesn't match compiler during build, e.g.: ``libstdc++.so.6: version `GLIBCXX_3.4.30' not found``
- Documentation update for `wp.BVH`
- Documentation and simplified API for runtime kernel specialization `wp.Kernel`
## [1.0.0-beta.4] - 2023-11-01
- Add `wp.cbrt()` for cube root calculation
- Add `wp.mesh_furthest_point_no_sign()` to compute furthest point on a surface from a query point
- Add support for GPU BVH builds, 10-100x faster than CPU builds for large meshes
- Add support for chained comparisons, i.e.: `0 < x < 2`
- Add support for running `wp.fem` examples headless
- Fix for unit test determinism
- Fix for possible GC collection of array during graph capture
- Fix for `wp.utils.array_sum()` output initialization when used with vector types
- Coverage and documentation updates
## [1.0.0-beta.3] - 2023-10-19
- Add support for code coverage scans (test_coverage.py), coverage at 85% in `omni.warp.core`
- Add support for named component access for vector types, e.g.: `a = v.x`
- Add support for lvalue expressions, e.g.: `array[i] += b`
- Add casting constructors for matrix and vector types
- Add support for `type()` operator that can be used to return type inside kernels
- Add support for grid-stride kernels to support kernels with > 2^31-1 thread blocks
- Fix for multi-process initialization warnings
- Fix alignment issues with empty `wp.struct`
- Fix for return statement warning with tuple-returning functions
- Fix for `wp.batched_matmul()` registering the wrong function in the Tape
- Fix and document for `wp.sim` forward + inverse kinematics
- Fix for `wp.func` to return a default value if function does not return on all control paths
- Refactor `wp.fem` support for new basis functions, decoupled function spaces
- Optimizations for `wp.noise` functions, up to 10x faster in most cases
- Optimizations for `type_size_in_bytes()` used in array construction'
### Breaking Changes
- To support grid-stride kernels, `wp.tid()` can no longer be called inside `wp.func` functions.
## [1.0.0-beta.2] - 2023-09-01
- Fix for passing bool into `wp.func` functions
- Fix for deprecation warnings appearing on `stderr`, now redirected to `stdout`
- Fix for using `for i in wp.hash_grid_query(..)` syntax
## [1.0.0-beta.1] - 2023-08-29
- Fix for `wp.float16` being passed as kernel arguments
- Fix for compile errors with kernels using structs in backward pass
- Fix for `wp.Mesh.refit()` not being CUDA graph capturable due to synchronous temp. allocs
- Fix for dynamic texture example flickering / MGPU crashes demo in Kit by reusing `ui.DynamicImageProvider` instances
- Fix for a regression that disabled bundle change tracking in samples
- Fix for incorrect surface velocities when meshes are deforming in `OgnClothSimulate`
- Fix for incorrect lower-case when setting USD stage "up_axis" in examples
- Fix for incompatible gradient types when wrapping PyTorch tensor as a vector or matrix type
- Fix for adding open edges when building cloth constraints from meshes in `wp.sim.ModelBuilder.add_cloth_mesh()`
- Add support for `wp.fabricarray` to directly access Fabric data from Warp kernels, see https://docs.omniverse.nvidia.com/kit/docs/usdrt/latest/docs/usdrt_prim_selection.html for examples
- Add support for user defined gradient functions, see `@wp.func_replay`, and `@wp.func_grad` decorators
- Add support for more OG attribute types in `omni.warp.from_omni_graph()`
- Add support for creating NanoVDB `wp.Volume` objects from dense NumPy arrays
- Add support for `wp.volume_sample_grad_f()` which returns the value + gradient efficiently from an NVDB volume
- Add support for LLVM fp16 intrinsics for half-precision arithmetic
- Add implementation of stochastic gradient descent, see `wp.optim.SGD`
- Add `wp.fem` framework for solving weak-form PDE problems (see https://nvidia.github.io/warp/modules/fem.html)
- Optimizations for `omni.warp` extension load time (2.2s to 625ms cold start)
- Make all `omni.ui` dependencies optional so that Warp unit tests can run headless
- Deprecation of `wp.tid()` outside of kernel functions, users should pass `tid()` values to `wp.func` functions explicitly
- Deprecation of `wp.sim.Model.flatten()` for returning all contained tensors from the model
- Add support for clamping particle max velocity in `wp.sim.Model.particle_max_velocity`
- Remove dependency on `urdfpy` package, improve MJCF parser handling of default values
## [0.10.1] - 2023-07-25
- Fix for large multidimensional kernel launches (> 2^32 threads)
- Fix for module hashing with generics
- Fix for unrolling loops with break or continue statements (will skip unrolling)
- Fix for passing boolean arguments to build_lib.py (previously ignored)
- Fix build warnings on Linux
- Fix for creating array of structs from NumPy structured array
- Fix for regression on kernel load times in Kit when using `wp.sim`
- Update `wp.array.reshape()` to handle `-1` dimensions
- Update margin used by for mesh queries when using `wp.sim.create_soft_body_contacts()`
- Improvements to gradient handling with `wp.from_torch()`, `wp.to_torch()` plus documentation
## [0.10.0] - 2023-07-05
- Add support for macOS universal binaries (x86 + aarch64) for M1+ support
- Add additional methods for SDF generation please see the following new methods:
- `wp.mesh_query_point_nosign()` - closest point query with no sign determination
- `wp.mesh_query_point_sign_normal()` - closest point query with sign from angle-weighted normal
- `wp.mesh_query_point_sign_winding_number()` - closest point query with fast winding number sign determination
- Add CSR/BSR sparse matrix support, see `wp.sparse` module:
- `wp.sparse.BsrMatrix`
- `wp.sparse.bsr_zeros()`, `wp.sparse.bsr_set_from_triplets()` for construction
- `wp.sparse.bsr_mm()`, `wp.sparse_bsr_mv()` for matrix-matrix and matrix-vector products respectively
- Add array-wide utilities:
- `wp.utils.array_scan()` - prefix sum (inclusive or exclusive)
- `wp.utils.array_sum()` - sum across array
- `wp.utils.radix_sort_pairs()` - in-place radix sort (key,value) pairs
- Add support for calling `@wp.func` functions from Python (outside of kernel scope)
- Add support for recording kernel launches using a `wp.Launch` object that can be replayed with low overhead, use `wp.launch(..., record_cmd=True)` to generate a command object
- Optimizations for `wp.struct` kernel arguments, up to 20x faster launches for kernels with large structs or number of params
- Refresh USD samples to use bundle based workflow + change tracking
- Add Python API for manipulating mesh and point bundle data in OmniGraph, see `omni.warp.nodes` module, see `omni.warp.nodes.mesh_create_bundle()`, `omni.warp.nodes.mesh_get_points()`, etc
- Improvements to `wp.array`:
- Fix a number of array methods misbehaving with empty arrays
- Fix a number of bugs and memory leaks related to gradient arrays
- Fix array construction when creating arrays in pinned memory from a data source in pageable memory
- `wp.empty()` no longer zeroes-out memory and returns an uninitialized array, as intended
- `array.zero_()` and `array.fill_()` work with non-contiguous arrays
- Support wrapping non-contiguous NumPy arrays without a copy
- Support preserving the outer dimensions of NumPy arrays when wrapping them as Warp arrays of vector or matrix types
- Improve PyTorch and DLPack interop with Warp arrays of arbitrary vectors and matrices
- `array.fill_()` can now take lists or other sequences when filling arrays of vectors or matrices, e.g. `arr.fill_([[1, 2], [3, 4]])`
- `array.fill_()` now works with arrays of structs (pass a struct instance)
- `wp.copy()` gracefully handles copying between non-contiguous arrays on different devices
- Add `wp.full()` and `wp.full_like()`, e.g., `a = wp.full(shape, value)`
- Add optional `device` argument to `wp.empty_like()`, `wp.zeros_like()`, `wp.full_like()`, and `wp.clone()`
- Add `indexedarray` methods `.zero_()`, `.fill_()`, and `.assign()`
- Fix `indexedarray` methods `.numpy()` and `.list()`
- Fix `array.list()` to work with arrays of any Warp data type
- Fix `array.list()` synchronization issue with CUDA arrays
- `array.numpy()` called on an array of structs returns a structured NumPy array with named fields
- Improve the performance of creating arrays
- Fix for `Error: No module named 'omni.warp.core'` when running some Kit configurations (e.g.: stubgen)
- Fix for `wp.struct` instance address being included in module content hash
- Fix codegen with overridden function names
- Fix for kernel hashing so it occurs after code generation and before loading to fix a bug with stale kernel cache
- Fix for `wp.BVH.refit()` when executed on the CPU
- Fix adjoint of `wp.struct` constructor
- Fix element accessors for `wp.float16` vectors and matrices in Python
- Fix `wp.float16` members in structs
- Remove deprecated `wp.ScopedCudaGuard()`, please use `wp.ScopedDevice()` instead
## [0.9.0] - 2023-06-01
- Add support for in-place modifications to vector, matrix, and struct types inside kernels (will warn during backward pass with `wp.verbose` if using gradients)
- Add support for step-through VSCode debugging of kernel code with standalone LLVM compiler, see `wp.breakpoint()`, and `walkthrough_debug.py`
- Add support for default values on built-in functions
- Add support for multi-valued `@wp.func` functions
- Add support for `pass`, `continue`, and `break` statements
- Add missing `__sincos_stret` symbol for macOS
- Add support for gradient propagation through `wp.Mesh.points`, and other cases where arrays are passed to native functions
- Add support for Python `@` operator as an alias for `wp.matmul()`
- Add XPBD support for particle-particle collision
- Add support for individual particle radii: `ModelBuilder.add_particle` has a new `radius` argument, `Model.particle_radius` is now a Warp array
- Add per-particle flags as a `Model.particle_flags` Warp array, introduce `PARTICLE_FLAG_ACTIVE` to define whether a particle is being simulated and participates in contact dynamics
- Add support for Python bitwise operators `&`, `|`, `~`, `<<`, `>>`
- Switch to using standalone LLVM compiler by default for `cpu` devices
- Split `omni.warp` into `omni.warp.core` for Omniverse applications that want to use the Warp Python module with minimal additional dependencies
- Disable kernel gradient generation by default inside Omniverse for improved compile times
- Fix for bounds checking on element access of vector/matrix types
- Fix for stream initialization when a custom (non-primary) external CUDA context has been set on the calling thread
- Fix for duplicate `@wp.struct` registration during hot reload
- Fix for array `unot()` operator so kernel writers can use `if not array:` syntax
- Fix for case where dynamic loops are nested within unrolled loops
- Change `wp.hash_grid_point_id()` now returns -1 if the `wp.HashGrid` has not been reserved before
- Deprecate `wp.Model.soft_contact_distance` which is now replaced by `wp.Model.particle_radius`
- Deprecate single scalar particle radius (should be a per-particle array)
## [0.8.2] - 2023-04-21
- Add `ModelBuilder.soft_contact_max` to control the maximum number of soft contacts that can be registered. Use `Model.allocate_soft_contacts(new_count)` to change count on existing `Model` objects.
- Add support for `bool` parameters
- Add support for logical boolean operators with `int` types
- Fix for `wp.quat()` default constructor
- Fix conditional reassignments
- Add sign determination using angle weighted normal version of `wp.mesh_query_point()` as `wp.mesh_query_sign_normal()`
- Add sign determination using winding number of `wp.mesh_query_point()` as `wp.mesh_query_sign_winding_number()`
- Add query point without sign determination `wp.mesh_query_no_sign()`
## [0.8.1] - 2023-04-13
- Fix for regression when passing flattened numeric lists as matrix arguments to kernels
- Fix for regressions when passing `wp.struct` types with uninitialized (`None`) member attributes
## [0.8.0] - 2023-04-05
- Add `Texture Write` node for updating dynamic RTX textures from Warp kernels / nodes
- Add multi-dimensional kernel support to Warp Kernel Node
- Add `wp.load_module()` to pre-load specific modules (pass `recursive=True` to load recursively)
- Add `wp.poisson()` for sampling Poisson distributions
- Add support for UsdPhysics schema see `wp.sim.parse_usd()`
- Add XPBD rigid body implementation plus diff. simulation examples
- Add support for standalone CPU compilation (no host-compiler) with LLVM backed, enable with `--standalone` build option
- Add support for per-timer color in `wp.ScopedTimer()`
- Add support for row-based construction of matrix types outside of kernels
- Add support for setting and getting row vectors for Python matrices, see `matrix.get_row()`, `matrix.set_row()`
- Add support for instantiating `wp.struct` types within kernels
- Add support for indexed arrays, `slice = array[indices]` will now generate a sparse slice of array data
- Add support for generic kernel params, use `def compute(param: Any):`
- Add support for `with wp.ScopedDevice("cuda") as device:` syntax (same for `wp.ScopedStream()`, `wp.Tape()`)
- Add support for creating custom length vector/matrices inside kernels, see `wp.vector()`, and `wp.matrix()`
- Add support for creating identity matrices in kernels with, e.g.: `I = wp.identity(n=3, dtype=float)`
- Add support for unary plus operator (`wp.pos()`)
- Add support for `wp.constant` variables to be used directly in Python without having to use `.val` member
- Add support for nested `wp.struct` types
- Add support for returning `wp.struct` from functions
- Add `--quick` build for faster local dev. iteration (uses a reduced set of SASS arches)
- Add optional `requires_grad` parameter to `wp.from_torch()` to override gradient allocation
- Add type hints for generic vector / matrix types in Python stubs
- Add support for custom user function recording in `wp.Tape()`
- Add support for registering CUTLASS `wp.matmul()` with tape backward pass
- Add support for grids with > 2^31 threads (each dimension may be up to INT_MAX in length)
- Add CPU fallback for `wp.matmul()`
- Optimizations for `wp.launch()`, up to 3x faster launches in common cases
- Fix `wp.randf()` conversion to float to reduce bias for uniform sampling
- Fix capture of `wp.func` and `wp.constant` types from inside Python closures
- Fix for CUDA on WSL
- Fix for matrices in structs
- Fix for transpose indexing for some non-square matrices
- Enable Python faulthandler by default
- Update to VS2019
### Breaking Changes
- `wp.constant` variables can now be treated as their true type, accessing the underlying value through `constant.val` is no longer supported
- `wp.sim.model.ground_plane` is now a `wp.array` to support gradient, users should call `builder.set_ground_plane()` to create the ground
- `wp.sim` capsule, cones, and cylinders are now aligned with the default USD up-axis
## [0.7.2] - 2023-02-15
- Reduce test time for vec/math types
- Clean-up CUDA disabled build pipeline
- Remove extension.gen.toml to make Kit packages Python version independent
- Handle additional cases for array indexing inside Python
## [0.7.1] - 2023-02-14
- Disabling some slow tests for Kit
- Make unit tests run on first GPU only by default
## [0.7.0] - 2023-02-13
- Add support for arbitrary length / type vector and matrices e.g.: `wp.vec(length=7, dtype=wp.float16)`, see `wp.vec()`, and `wp.mat()`
- Add support for `array.flatten()`, `array.reshape()`, and `array.view()` with NumPy semantics
- Add support for slicing `wp.array` types in Python
- Add `wp.from_ptr()` helper to construct arrays from an existing allocation
- Add support for `break` statements in ranged-for and while loops (backward pass support currently not implemented)
- Add built-in mathematic constants, see `wp.pi`, `wp.e`, `wp.log2e`, etc.
- Add built-in conversion between degrees and radians, see `wp.degrees()`, `wp.radians()`
- Add security pop-up for Kernel Node
- Improve error handling for kernel return values
## [0.6.3] - 2023-01-31
- Add DLPack utilities, see `wp.from_dlpack()`, `wp.to_dlpack()`
- Add Jax utilities, see `wp.from_jax()`, `wp.to_jax()`, `wp.device_from_jax()`, `wp.device_to_jax()`
- Fix for Linux Kit extensions OM-80132, OM-80133
## [0.6.2] - 2023-01-19
- Updated `wp.from_torch()` to support more data types
- Updated `wp.from_torch()` to automatically determine the target Warp data type if not specified
- Updated `wp.from_torch()` to support non-contiguous tensors with arbitrary strides
- Add CUTLASS integration for dense GEMMs, see `wp.matmul()` and `wp.matmul_batched()`
- Add QR and Eigen decompositions for `mat33` types, see `wp.qr3()`, and `wp.eig3()`
- Add default (zero) constructors for matrix types
- Add a flag to suppress all output except errors and warnings (set `wp.config.quiet = True`)
- Skip recompilation when Kernel Node attributes are edited
- Allow optional attributes for Kernel Node
- Allow disabling backward pass code-gen on a per-kernel basis, use `@wp.kernel(enable_backward=False)`
- Replace Python `imp` package with `importlib`
- Fix for quaternion slerp gradients (`wp.quat_slerp()`)
## [0.6.1] - 2022-12-05
- Fix for non-CUDA builds
- Fix strides computation in array_t constructor, fixes a bug with accessing mesh indices through mesh.indices[]
- Disable backward pass code generation for kernel node (4-6x faster compilation)
- Switch to linbuild for universal Linux binaries (affects TeamCity builds only)
## [0.6.0] - 2022-11-28
- Add support for CUDA streams, see `wp.Stream`, `wp.get_stream()`, `wp.set_stream()`, `wp.synchronize_stream()`, `wp.ScopedStream`
- Add support for CUDA events, see `wp.Event`, `wp.record_event()`, `wp.wait_event()`, `wp.wait_stream()`, `wp.Stream.record_event()`, `wp.Stream.wait_event()`, `wp.Stream.wait_stream()`
- Add support for PyTorch stream interop, see `wp.stream_from_torch()`, `wp.stream_to_torch()`
- Add support for allocating host arrays in pinned memory for asynchronous data transfers, use `wp.array(..., pinned=True)` (default is non-pinned)
- Add support for direct conversions between all scalar types, e.g.: `x = wp.uint8(wp.float64(3.0))`
- Add per-module option to enable fast math, use `wp.set_module_options({"fast_math": True})`, fast math is now *disabled* by default
- Add support for generating CUBIN kernels instead of PTX on systems with older drivers
- Add user preference options for CUDA kernel output ("ptx" or "cubin", e.g.: `wp.config.cuda_output = "ptx"` or per-module `wp.set_module_options({"cuda_output": "ptx"})`)
- Add kernel node for OmniGraph
- Add `wp.quat_slerp()`, `wp.quat_to_axis_angle()`, `wp.rotate_rodriquez()` and adjoints for all remaining quaternion operations
- Add support for unrolling for-loops when range is a `wp.constant`
- Add support for arithmetic operators on built-in vector / matrix types outside of `wp.kernel`
- Add support for multiple solution variables in `wp.optim` Adam optimization
- Add nested attribute support for `wp.struct` attributes
- Add missing adjoint implementations for spatial math types, and document all functions with missing adjoints
- Add support for retrieving NanoVDB tiles and voxel size, see `wp.Volume.get_tiles()`, and `wp.Volume.get_voxel_size()`
- Add support for store operations on integer NanoVDB volumes, see `wp.volume_store_i()`
- Expose `wp.Mesh` points, indices, as arrays inside kernels, see `wp.mesh_get()`
- Optimizations for `wp.array` construction, 2-3x faster on average
- Optimizations for URDF import
- Fix various deployment issues by statically linking with all CUDA libs
- Update warp.so/warp.dll to CUDA Toolkit 11.5
## [0.5.1] - 2022-11-01
- Fix for unit tests in Kit
## [0.5.0] - 2022-10-31
- Add smoothed particle hydrodynamics (SPH) example, see `example_sph.py`
- Add support for accessing `array.shape` inside kernels, e.g.: `width = arr.shape[0]`
- Add dependency tracking to hot-reload modules if dependencies were modified
- Add lazy acquisition of CUDA kernel contexts (save ~300Mb of GPU memory in MGPU environments)
- Add BVH object, see `wp.Bvh` and `bvh_query_ray()`, `bvh_query_aabb()` functions
- Add component index operations for `spatial_vector`, `spatial_matrix` types
- Add `wp.lerp()` and `wp.smoothstep()` builtins
- Add `wp.optim` module with implementation of the Adam optimizer for float and vector types
- Add support for transient Python modules (fix for Houdini integration)
- Add `wp.length_sq()`, `wp.trace()` for vector / matrix types respectively
- Add missing adjoints for `wp.quat_rpy()`, `wp.determinant()`
- Add `wp.atomic_min()`, `wp.atomic_max()` operators
- Add vectorized version of `wp.sim.model.add_cloth_mesh()`
- Add NVDB volume allocation API, see `wp.Volume.allocate()`, and `wp.Volume.allocate_by_tiles()`
- Add NVDB volume write methods, see `wp.volume_store_i()`, `wp.volume_store_f()`, `wp.volume_store_v()`
- Add MGPU documentation
- Add example showing how to compute Jacobian of multiple environments in parallel, see `example_jacobian_ik.py`
- Add `wp.Tape.zero()` support for `wp.struct` types
- Make SampleBrowser an optional dependency for Kit extension
- Make `wp.Mesh` object accept both 1d and 2d arrays of face vertex indices
- Fix for reloading of class member kernel / function definitions using `importlib.reload()`
- Fix for hashing of `wp.constants()` not invalidating kernels
- Fix for reload when multiple `.ptx` versions are present
- Improved error reporting during code-gen
## [0.4.3] - 2022-09-20
- Update all samples to use GPU interop path by default
- Fix for arrays > 2GB in length
- Add support for per-vertex USD mesh colors with `wp.render` class
## [0.4.2] - 2022-09-07
- Register Warp samples to the sample browser in Kit
- Add NDEBUG flag to release mode kernel builds
- Fix for particle solver node when using a large number of particles
- Fix for broken cameras in Warp sample scenes
## [0.4.1] - 2022-08-30
- Add geometry sampling methods, see `wp.sample_unit_cube()`, `wp.sample_unit_disk()`, etc
- Add `wp.lower_bound()` for searching sorted arrays
- Add an option for disabling code-gen of backward pass to improve compilation times, see `wp.set_module_options({"enable_backward": False})`, True by default
- Fix for using Warp from Script Editor or when module does not have a `__file__` attribute
- Fix for hot reload of modules containing `wp.func()` definitions
- Fix for debug flags not being set correctly on CUDA when `wp.config.mode == "debug"`, this enables bounds checking on CUDA kernels in debug mode
- Fix for code gen of functions that do not return a value
## [0.4.0] - 2022-08-09
- Fix for FP16 conversions on GPUs without hardware support
- Fix for `runtime = None` errors when reloading the Warp module
- Fix for PTX architecture version when running with older drivers, see `wp.config.ptx_target_arch`
- Fix for USD imports from `__init__.py`, defer them to individual functions that need them
- Fix for robustness issues with sign determination for `wp.mesh_query_point()`
- Fix for `wp.HashGrid` memory leak when creating/destroying grids
- Add CUDA version checks for toolkit and driver
- Add support for cross-module `@wp.struct` references
- Support running even if CUDA initialization failed, use `wp.is_cuda_available()` to check availability
- Statically linking with the CUDA runtime library to avoid deployment issues
### Breaking Changes
- Removed `wp.runtime` reference from the top-level module, as it should be considered private
## [0.3.2] - 2022-07-19
- Remove Torch import from `__init__.py`, defer import to `wp.from_torch()`, `wp.to_torch()`
## [0.3.1] - 2022-07-12
- Fix for marching cubes reallocation after initialization
- Add support for closest point between line segment tests, see `wp.closest_point_edge_edge()` builtin
- Add support for per-triangle elasticity coefficients in simulation, see `wp.sim.ModelBuilder.add_cloth_mesh()`
- Add support for specifying default device, see `wp.set_device()`, `wp.get_device()`, `wp.ScopedDevice`
- Add support for multiple GPUs (e.g., `"cuda:0"`, `"cuda:1"`), see `wp.get_cuda_devices()`, `wp.get_cuda_device_count()`, `wp.get_cuda_device()`
- Add support for explicitly targeting the current CUDA context using device alias `"cuda"`
- Add support for using arbitrary external CUDA contexts, see `wp.map_cuda_device()`, `wp.unmap_cuda_device()`
- Add PyTorch device aliasing functions, see `wp.device_from_torch()`, `wp.device_to_torch()`
### Breaking Changes
- A CUDA device is used by default, if available (aligned with `wp.get_preferred_device()`)
- `wp.ScopedCudaGuard` is deprecated, use `wp.ScopedDevice` instead
- `wp.synchronize()` now synchronizes all devices; for finer-grained control, use `wp.synchronize_device()`
- Device alias `"cuda"` now refers to the current CUDA context, rather than a specific device like `"cuda:0"` or `"cuda:1"`
## [0.3.0] - 2022-07-08
- Add support for FP16 storage type, see `wp.float16`
- Add support for per-dimension byte strides, see `wp.array.strides`
- Add support for passing Python classes as kernel arguments, see `@wp.struct` decorator
- Add additional bounds checks for builtin matrix types
- Add additional floating point checks, see `wp.config.verify_fp`
- Add interleaved user source with generated code to aid debugging
- Add generalized GPU marching cubes implementation, see `wp.MarchingCubes` class
- Add additional scalar*matrix vector operators
- Add support for retrieving a single row from builtin types, e.g.: `r = m33[i]`
- Add `wp.log2()` and `wp.log10()` builtins
- Add support for quickly instancing `wp.sim.ModelBuilder` objects to improve env. creation performance for RL
- Remove custom CUB version and improve compatibility with CUDA 11.7
- Fix to preserve external user-gradients when calling `wp.Tape.zero()`
- Fix to only allocate gradient of a Torch tensor if `requires_grad=True`
- Fix for missing `wp.mat22` constructor adjoint
- Fix for ray-cast precision in edge case on GPU (watertightness issue)
- Fix for kernel hot-reload when definition changes
- Fix for NVCC warnings on Linux
- Fix for generated function names when kernels are defined as class functions
- Fix for reload of generated CPU kernel code on Linux
- Fix for example scripts to output USD at 60 timecodes per-second (better Kit compatibility)
## [0.2.3] - 2022-06-13
- Fix for incorrect 4d array bounds checking
- Fix for `wp.constant` changes not updating module hash
- Fix for stale CUDA kernel cache when CPU kernels launched first
- Array gradients are now allocated along with the arrays and accessible as `wp.array.grad`, users should take care to always call `wp.Tape.zero()` to clear gradients between different invocations of `wp.Tape.backward()`
- Added `wp.array.fill_()` to set all entries to a scalar value (4-byte values only currently)
### Breaking Changes
- Tape `capture` option has been removed, users can now capture tapes inside existing CUDA graphs (e.g.: inside Torch)
- Scalar loss arrays should now explicitly set `requires_grad=True` at creation time
## [0.2.2] - 2022-05-30
- Fix for `from import *` inside Warp initialization
- Fix for body space velocity when using deforming Mesh objects with scale
- Fix for noise gradient discontinuities affecting `wp.curlnoise()`
- Fix for `wp.from_torch()` to correctly preserve shape
- Fix for URDF parser incorrectly passing density to scale parameter
- Optimizations for startup time from 3s -> 0.3s
- Add support for custom kernel cache location, Warp will now store generated binaries in the user's application directory
- Add support for cross-module function references, e.g.: call another modules @wp.func functions
- Add support for overloading `@wp.func` functions based on argument type
- Add support for calling built-in functions directly from Python interpreter outside kernels (experimental)
- Add support for auto-complete and docstring lookup for builtins in IDEs like VSCode, PyCharm, etc
- Add support for doing partial array copies, see `wp.copy()` for details
- Add support for accessing mesh data directly in kernels, see `wp.mesh_get_point()`, `wp.mesh_get_index()`, `wp.mesh_eval_face_normal()`
- Change to only compile for targets where kernel is launched (e.g.: will not compile CPU unless explicitly requested)
### Breaking Changes
- Builtin methods such as `wp.quat_identity()` now call the Warp native implementation directly and will return a `wp.quat` object instead of NumPy array
- NumPy implementations of many builtin methods have been moved to `wp.utils` and will be deprecated
- Local `@wp.func` functions should not be namespaced when called, e.g.: previously `wp.myfunc()` would work even if `myfunc()` was not a builtin
- Removed `wp.rpy2quat()`, please use `wp.quat_rpy()` instead
## [0.2.1] - 2022-05-11
- Fix for unit tests in Kit
## [0.2.0] - 2022-05-02
### Warp Core
- Fix for unrolling loops with negative bounds
- Fix for unresolved symbol `hash_grid_build_device()` not found when lib is compiled without CUDA support
- Fix for failure to load nvrtc-builtins64_113.dll when user has a newer CUDA toolkit installed on their machine
- Fix for conversion of Torch tensors to `wp.array` with a vector dtype (incorrect row count)
- Fix for `warp.dll` not found on some Windows installations
- Fix for macOS builds on Clang 13.x
- Fix for step-through debugging of kernels on Linux
- Add argument type checking for user defined `@wp.func` functions
- Add support for custom iterable types, supports ranges, hash grid, and mesh query objects
- Add support for multi-dimensional arrays, for example use `x = array[i,j,k]` syntax to address a 3-dimensional array
- Add support for multi-dimensional kernel launches, use `launch(kernel, dim=(i,j,k), ...` and `i,j,k = wp.tid()` to obtain thread indices
- Add support for bounds-checking array memory accesses in debug mode, use `wp.config.mode = "debug"` to enable
- Add support for differentiating through dynamic and nested for-loops
- Add support for evaluating MLP neural network layers inside kernels with custom activation functions, see `wp.mlp()`
- Add additional NVDB sampling methods and adjoints, see `wp.volume_sample_i()`, `wp.volume_sample_f()`, and `wp.volume_sample_vec()`
- Add support for loading zlib compressed NVDB volumes, see `wp.Volume.load_from_nvdb()`
- Add support for triangle intersection testing, see `wp.intersect_tri_tri()`
- Add support for NVTX profile zones in `wp.ScopedTimer()`
- Add support for additional transform and quaternion math operations, see `wp.inverse()`, `wp.quat_to_matrix()`, `wp.quat_from_matrix()`
- Add fast math (`--fast-math`) to kernel compilation by default
- Add `wp.torch` import by default (if PyTorch is installed)
### Warp Kit
- Add Kit menu for browsing Warp documentation and example scenes under 'Window->Warp'
- Fix for OgnParticleSolver.py example when collider is coming from Read Prim into Bundle node
### Warp Sim
- Fix for joint attachment forces
- Fix for URDF importer and floating base support
- Add examples showing how to use differentiable forward kinematics to solve inverse kinematics
- Add examples for URDF cartpole and quadruped simulation
### Breaking Changes
- `wp.volume_sample_world()` is now replaced by `wp.volume_sample_f/i/vec()` which operate in index (local) space. Users should use `wp.volume_world_to_index()` to transform points from world space to index space before sampling.
- `wp.mlp()` expects multi-dimensional arrays instead of one-dimensional arrays for inference, all other semantics remain the same as earlier versions of this API.
- `wp.array.length` member has been removed, please use `wp.array.shape` to access array dimensions, or use `wp.array.size` to get total element count
- Marking `dense_gemm()`, `dense_chol()`, etc methods as experimental until we revisit them
## [0.1.25] - 2022-03-20
- Add support for class methods to be Warp kernels
- Add HashGrid reserve() so it can be used with CUDA graphs
- Add support for CUDA graph capture of tape forward/backward passes
- Add support for Python 3.8.x and 3.9.x
- Add hyperbolic trigonometric functions, see `wp.tanh()`, `wp.sinh()`, `wp.cosh()`
- Add support for floored division on integer types
- Move tests into core library so they can be run in Kit environment
## [0.1.24] - 2022-03-03
### Warp Core
- Add NanoVDB support, see `wp.volume_sample*()` methods
- Add support for reading compile-time constants in kernels, see `wp.constant()`
- Add support for __cuda_array_interface__ protocol for zero-copy interop with PyTorch, see `wp.torch.to_torch()`
- Add support for additional numeric types, i8, u8, i16, u16, etc
- Add better checks for device strings during allocation / launch
- Add support for sampling random numbers with a normal distribution, see `wp.randn()`
- Upgrade to CUDA 11.3
- Update example scenes to Kit 103.1
- Deduce array dtype from np.array when one is not provided
- Fix for ranged for loops with negative step sizes
- Fix for 3d and 4d spherical gradient distributions
## [0.1.23] - 2022-02-17
### Warp Core
- Fix for generated code folder being removed during Showroom installation
- Fix for macOS support
- Fix for dynamic for-loop code gen edge case
- Add procedural noise primitives, see `wp.noise()`, `wp.pnoise()`, `wp.curlnoise()`
- Move simulation helpers our of test into `wp.sim` module
## [0.1.22] - 2022-02-14
### Warp Core
- Fix for .so reloading on Linux
- Fix for while loop code-gen in some edge cases
- Add rounding functions `wp.round()`, `wp.rint()`, `wp.trunc()`, `wp.floor()`, `wp.ceil()`
- Add support for printing strings and formatted strings from kernels
- Add MSVC compiler version detection and require minimum
### Warp Sim
- Add support for universal and compound joint types
## [0.1.21] - 2022-01-19
### Warp Core
- Fix for exception on shutdown in empty `wp.array` objects
- Fix for hot reload of CPU kernels in Kit
- Add hash grid primitive for point-based spatial queries, see `wp.hash_grid_query()`, `wp.hash_grid_query_next()`
- Add new PRNG methods using PCG-based generators, see `wp.rand_init()`, `wp.randf()`, `wp.randi()`
- Add support for AABB mesh queries, see `wp.mesh_query_aabb()`, `wp.mesh_query_aabb_next()`
- Add support for all Python `range()` loop variants
- Add builtin vec2 type and additional math operators, `wp.pow()`, `wp.tan()`, `wp.atan()`, `wp.atan2()`
- Remove dependency on CUDA driver library at build time
- Remove unused NVRTC binary dependencies (50mb smaller Linux distribution)
### Warp Sim
- Bundle import of multiple shapes for simulation nodes
- New OgnParticleVolume node for sampling shapes -> particles
- New OgnParticleSolver node for DEM style granular materials
## [0.1.20] - 2021-11-02
- Updates to the ripple solver for GTC (support for multiple colliders, buoyancy, etc)
## [0.1.19] - 2021-10-15
- Publish from 2021.3 to avoid omni.graph database incompatibilities
## [0.1.18] - 2021-10-08
- Enable Linux support (tested on 20.04)
## [0.1.17] - 2021-09-30
- Fix for 3x3 SVD adjoint
- Fix for A6000 GPU (bump compute model to sm_52 minimum)
- Fix for .dll unload on rebuild
- Fix for possible array destruction warnings on shutdown
- Rename spatial_transform -> transform
- Documentation update
## [0.1.16] - 2021-09-06
- Fix for case where simple assignments (a = b) incorrectly generated reference rather than value copy
- Handle passing zero-length (empty) arrays to kernels
## [0.1.15] - 2021-09-03
- Add additional math library functions (asin, etc)
- Add builtin 3x3 SVD support
- Add support for named constants (True, False, None)
- Add support for if/else statements (differentiable)
- Add custom memset kernel to avoid CPU overhead of cudaMemset()
- Add rigid body joint model to `wp.sim` (based on Brax)
- Add Linux, MacOS support in core library
- Fix for incorrectly treating pure assignment as reference instead of value copy
- Removes the need to transfer array to CPU before numpy conversion (will be done implicitly)
- Update the example OgnRipple wave equation solver to use bundles
## [0.1.14] - 2021-08-09
- Fix for out-of-bounds memory access in CUDA BVH
- Better error checking after kernel launches (use `wp.config.verify_cuda=True`)
- Fix for vec3 normalize adjoint code
## [0.1.13] - 2021-07-29
- Remove OgnShrinkWrap.py test node
## [0.1.12] - 2021-07-29
- Switch to Woop et al.'s watertight ray-tri intersection test
- Disable --fast-math in CUDA compilation step for improved precision
## [0.1.11] - 2021-07-28
- Fix for `wp.mesh_query_ray()` returning incorrect t-value
## [0.1.10] - 2021-07-28
- Fix for OV extension fwatcher filters to avoid hot-reload loop due to OGN regeneration
## [0.1.9] - 2021-07-21
- Fix for loading sibling DLL paths
- Better type checking for built-in function arguments
- Added runtime docs, can now list all builtins using `wp.print_builtins()`
## [0.1.8] - 2021-07-14
- Fix for hot-reload of CUDA kernels
- Add Tape object for replaying differentiable kernels
- Add helpers for Torch interop (convert `torch.Tensor` to `wp.Array`)
## [0.1.7] - 2021-07-05
- Switch to NVRTC for CUDA runtime
- Allow running without host compiler
- Disable asserts in kernel release mode (small perf. improvement)
## [0.1.6] - 2021-06-14
- Look for CUDA toolchain in target-deps
## [0.1.5] - 2021-06-14
- Rename OgLang -> Warp
- Improve CUDA environment error checking
- Clean-up some logging, add verbose mode (`wp.config.verbose`)
## [0.1.4] - 2021-06-10
- Add support for mesh raycast
## [0.1.3] - 2021-06-09
- Add support for unary negation operator
- Add support for mutating variables during dynamic loops (non-differentiable)
- Add support for in-place operators
- Improve kernel cache start up times (avoids adjointing before cache check)
- Update README.md with requirements / examples
## [0.1.2] - 2021-06-03
- Add support for querying mesh velocities
- Add CUDA graph support, see `wp.capture_begin()`, `wp.capture_end()`, `wp.capture_launch()`
- Add explicit initialization phase, `wp.init()`
- Add variational Euler solver (sim)
- Add contact caching, switch to nonlinear friction model (sim)
- Fix for Linux/macOS support
## [0.1.1] - 2021-05-18
- Fix bug with conflicting CUDA contexts
## [0.1.0] - 2021-05-17
- Initial publish for alpha testing
| 52,860 | Markdown | 55.962284 | 302 | 0.753462 |
NVIDIA/warp/exts/omni.warp.core/docs/README.md | # Warp Core [omni.warp.core]
This extension simply provides the core Python module for NVIDIA Warp.
It can be used by other extensions that want to use the Warp Python module with
minimal additional dependencies, such as for headless execution.
After enabling, use `import warp` from Python to use Warp inside the Omniverse Application's Python environment.
For higher-level components, including Warp-specialized OmniGraph nodes and sample scenes, see the
omni.warp extension.
## About Warp
NVIDIA Warp is a Python framework for writing high-performance simulation and graphics code.
Compute kernels are defined in Python syntax and JIT converted to C++/CUDA and compiled at runtime.
## Documentation
The online Warp documentation is hosted at https://nvidia.github.io/warp.
| 784 | Markdown | 36.380951 | 112 | 0.802296 |
NVIDIA/warp/warp/stubs.py | # Autogenerated file, do not edit, this file provides stubs for builtins autocomplete in VSCode, PyCharm, etc
from typing import Any
from typing import Tuple
from typing import Callable
from typing import TypeVar
from typing import Generic
from typing import overload as over
Length = TypeVar("Length", bound=int)
Rows = TypeVar("Rows", bound=int)
Cols = TypeVar("Cols", bound=int)
DType = TypeVar("DType")
Int = TypeVar("Int")
Float = TypeVar("Float")
Scalar = TypeVar("Scalar")
Vector = Generic[Length, Scalar]
Matrix = Generic[Rows, Cols, Scalar]
Quaternion = Generic[Float]
Transformation = Generic[Float]
Array = Generic[DType]
FabricArray = Generic[DType]
IndexedFabricArray = Generic[DType]
from warp.types import array, array1d, array2d, array3d, array4d, constant
from warp.types import indexedarray, indexedarray1d, indexedarray2d, indexedarray3d, indexedarray4d
from warp.fabric import fabricarray, fabricarrayarray, indexedfabricarray, indexedfabricarrayarray
from warp.types import bool, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float16, float32, float64
from warp.types import vec2, vec2b, vec2ub, vec2s, vec2us, vec2i, vec2ui, vec2l, vec2ul, vec2h, vec2f, vec2d
from warp.types import vec3, vec3b, vec3ub, vec3s, vec3us, vec3i, vec3ui, vec3l, vec3ul, vec3h, vec3f, vec3d
from warp.types import vec4, vec4b, vec4ub, vec4s, vec4us, vec4i, vec4ui, vec4l, vec4ul, vec4h, vec4f, vec4d
from warp.types import mat22, mat22h, mat22f, mat22d
from warp.types import mat33, mat33h, mat33f, mat33d
from warp.types import mat44, mat44h, mat44f, mat44d
from warp.types import quat, quath, quatf, quatd
from warp.types import transform, transformh, transformf, transformd
from warp.types import spatial_vector, spatial_vectorh, spatial_vectorf, spatial_vectord
from warp.types import spatial_matrix, spatial_matrixh, spatial_matrixf, spatial_matrixd
from warp.types import Bvh, Mesh, HashGrid, Volume, MarchingCubes
from warp.types import bvh_query_t, hash_grid_query_t, mesh_query_aabb_t, mesh_query_point_t, mesh_query_ray_t
from warp.types import matmul, adj_matmul, batched_matmul, adj_batched_matmul, from_ptr
from warp.types import vector as vec
from warp.types import matrix as mat
from warp.types import dtype_from_numpy, dtype_to_numpy
from warp.context import init, func, func_grad, func_replay, func_native, kernel, struct, overload
from warp.context import is_cpu_available, is_cuda_available, is_device_available
from warp.context import get_devices, get_preferred_device
from warp.context import get_cuda_devices, get_cuda_device_count, get_cuda_device, map_cuda_device, unmap_cuda_device
from warp.context import get_device, set_device, synchronize_device
from warp.context import (
zeros,
zeros_like,
ones,
ones_like,
full,
full_like,
clone,
empty,
empty_like,
copy,
from_numpy,
launch,
synchronize,
force_load,
load_module,
)
from warp.context import set_module_options, get_module_options, get_module
from warp.context import capture_begin, capture_end, capture_launch
from warp.context import Kernel, Function, Launch
from warp.context import Stream, get_stream, set_stream, wait_stream, synchronize_stream
from warp.context import Event, record_event, wait_event, synchronize_event, get_event_elapsed_time
from warp.context import RegisteredGLBuffer
from warp.context import is_mempool_supported, is_mempool_enabled, set_mempool_enabled
from warp.context import set_mempool_release_threshold, get_mempool_release_threshold
from warp.context import is_mempool_access_supported, is_mempool_access_enabled, set_mempool_access_enabled
from warp.context import is_peer_access_supported, is_peer_access_enabled, set_peer_access_enabled
from warp.tape import Tape
from warp.utils import ScopedTimer, ScopedDevice, ScopedStream
from warp.utils import ScopedMempool, ScopedMempoolAccess, ScopedPeerAccess
from warp.utils import ScopedCapture
from warp.utils import transform_expand, quat_between_vectors
from warp.utils import TimingResult, timing_begin, timing_end, timing_print
from warp.utils import (
TIMING_KERNEL,
TIMING_KERNEL_BUILTIN,
TIMING_MEMCPY,
TIMING_MEMSET,
TIMING_GRAPH,
TIMING_ALL,
)
from warp.torch import from_torch, to_torch
from warp.torch import dtype_from_torch, dtype_to_torch
from warp.torch import device_from_torch, device_to_torch
from warp.torch import stream_from_torch, stream_to_torch
from warp.jax import from_jax, to_jax
from warp.jax import dtype_from_jax, dtype_to_jax
from warp.jax import device_from_jax, device_to_jax
from warp.dlpack import from_dlpack, to_dlpack
from warp.constants import *
from . import builtins
import warp.config
__version__ = warp.config.version
@over
def min(x: Scalar, y: Scalar) -> Scalar:
"""Return the minimum of two scalars."""
...
@over
def min(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
"""Return the element-wise minimum of two vectors."""
...
@over
def min(v: Vector[Any, Scalar]) -> Scalar:
"""Return the minimum element of a vector ``v``."""
...
@over
def max(x: Scalar, y: Scalar) -> Scalar:
"""Return the maximum of two scalars."""
...
@over
def max(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
"""Return the element-wise maximum of two vectors."""
...
@over
def max(v: Vector[Any, Scalar]) -> Scalar:
"""Return the maximum element of a vector ``v``."""
...
@over
def clamp(x: Scalar, a: Scalar, b: Scalar) -> Scalar:
"""Clamp the value of ``x`` to the range [a, b]."""
...
@over
def abs(x: Scalar) -> Scalar:
"""Return the absolute value of ``x``."""
...
@over
def sign(x: Scalar) -> Scalar:
"""Return -1 if ``x`` < 0, return 1 otherwise."""
...
@over
def step(x: Scalar) -> Scalar:
"""Return 1.0 if ``x`` < 0.0, return 0.0 otherwise."""
...
@over
def nonzero(x: Scalar) -> Scalar:
"""Return 1.0 if ``x`` is not equal to zero, return 0.0 otherwise."""
...
@over
def sin(x: Float) -> Float:
"""Return the sine of ``x`` in radians."""
...
@over
def cos(x: Float) -> Float:
"""Return the cosine of ``x`` in radians."""
...
@over
def acos(x: Float) -> Float:
"""Return arccos of ``x`` in radians. Inputs are automatically clamped to [-1.0, 1.0]."""
...
@over
def asin(x: Float) -> Float:
"""Return arcsin of ``x`` in radians. Inputs are automatically clamped to [-1.0, 1.0]."""
...
@over
def sqrt(x: Float) -> Float:
"""Return the square root of ``x``, where ``x`` is positive."""
...
@over
def cbrt(x: Float) -> Float:
"""Return the cube root of ``x``."""
...
@over
def tan(x: Float) -> Float:
"""Return the tangent of ``x`` in radians."""
...
@over
def atan(x: Float) -> Float:
"""Return the arctangent of ``x`` in radians."""
...
@over
def atan2(y: Float, x: Float) -> Float:
"""Return the 2-argument arctangent, atan2, of the point ``(x, y)`` in radians."""
...
@over
def sinh(x: Float) -> Float:
"""Return the sinh of ``x``."""
...
@over
def cosh(x: Float) -> Float:
"""Return the cosh of ``x``."""
...
@over
def tanh(x: Float) -> Float:
"""Return the tanh of ``x``."""
...
@over
def degrees(x: Float) -> Float:
"""Convert ``x`` from radians into degrees."""
...
@over
def radians(x: Float) -> Float:
"""Convert ``x`` from degrees into radians."""
...
@over
def log(x: Float) -> Float:
"""Return the natural logarithm (base-e) of ``x``, where ``x`` is positive."""
...
@over
def log2(x: Float) -> Float:
"""Return the binary logarithm (base-2) of ``x``, where ``x`` is positive."""
...
@over
def log10(x: Float) -> Float:
"""Return the common logarithm (base-10) of ``x``, where ``x`` is positive."""
...
@over
def exp(x: Float) -> Float:
"""Return the value of the exponential function :math:`e^x`."""
...
@over
def pow(x: Float, y: Float) -> Float:
"""Return the result of ``x`` raised to power of ``y``."""
...
@over
def round(x: Float) -> Float:
"""Return the nearest integer value to ``x``, rounding halfway cases away from zero.
This is the most intuitive form of rounding in the colloquial sense, but can be slower than other options like :func:`warp.rint()`.
Differs from :func:`numpy.round()`, which behaves the same way as :func:`numpy.rint()`.
"""
...
@over
def rint(x: Float) -> Float:
"""Return the nearest integer value to ``x``, rounding halfway cases to nearest even integer.
It is generally faster than :func:`warp.round()`. Equivalent to :func:`numpy.rint()`.
"""
...
@over
def trunc(x: Float) -> Float:
"""Return the nearest integer that is closer to zero than ``x``.
In other words, it discards the fractional part of ``x``.
It is similar to casting ``float(int(x))``, but preserves the negative sign when x is in the range [-0.0, -1.0).
Equivalent to :func:`numpy.trunc()` and :func:`numpy.fix()`.
"""
...
@over
def floor(x: Float) -> Float:
"""Return the largest integer that is less than or equal to ``x``."""
...
@over
def ceil(x: Float) -> Float:
"""Return the smallest integer that is greater than or equal to ``x``."""
...
@over
def frac(x: Float) -> Float:
"""Retrieve the fractional part of x.
In other words, it discards the integer part of x and is equivalent to ``x - trunc(x)``.
"""
...
@over
def isfinite(x: Scalar) -> bool:
"""Return ``True`` if x is a finite number, otherwise return ``False``."""
...
@over
def isfinite(x: Vector[Any, Scalar]) -> bool:
"""Return ``True`` if all elements of the vector ``x`` are finite, otherwise return ``False``."""
...
@over
def isfinite(x: Quaternion[Scalar]) -> bool:
"""Return ``True`` if all elements of the quaternion ``x`` are finite, otherwise return ``False``."""
...
@over
def isfinite(m: Matrix[Any, Any, Scalar]) -> bool:
"""Return ``True`` if all elements of the matrix ``m`` are finite, otherwise return ``False``."""
...
@over
def isnan(x: Scalar) -> bool:
"""Return ``True`` if ``x`` is NaN, otherwise return ``False``."""
...
@over
def isnan(x: Vector[Any, Scalar]) -> bool:
"""Return ``True`` if any element of the vector ``x`` is NaN, otherwise return ``False``."""
...
@over
def isnan(x: Quaternion[Scalar]) -> bool:
"""Return ``True`` if any element of the quaternion ``x`` is NaN, otherwise return ``False``."""
...
@over
def isnan(m: Matrix[Any, Any, Scalar]) -> bool:
"""Return ``True`` if any element of the matrix ``m`` is NaN, otherwise return ``False``."""
...
@over
def isinf(x: Scalar) -> bool:
"""Return ``True`` if x is positive or negative infinity, otherwise return ``False``."""
...
@over
def isinf(x: Vector[Any, Scalar]) -> bool:
"""Return ``True`` if any element of the vector ``x`` is positive or negative infinity, otherwise return ``False``."""
...
@over
def isinf(x: Quaternion[Scalar]) -> bool:
"""Return ``True`` if any element of the quaternion ``x`` is positive or negative infinity, otherwise return ``False``."""
...
@over
def isinf(m: Matrix[Any, Any, Scalar]) -> bool:
"""Return ``True`` if any element of the matrix ``m`` is positive or negative infinity, otherwise return ``False``."""
...
@over
def dot(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Scalar:
"""Compute the dot product between two vectors."""
...
@over
def dot(x: Quaternion[Float], y: Quaternion[Float]) -> Scalar:
"""Compute the dot product between two quaternions."""
...
@over
def ddot(x: Matrix[Any, Any, Scalar], y: Matrix[Any, Any, Scalar]) -> Scalar:
"""Compute the double dot product between two matrices."""
...
@over
def argmin(v: Vector[Any, Scalar]) -> uint32:
"""Return the index of the minimum element of a vector ``v``."""
...
@over
def argmax(v: Vector[Any, Scalar]) -> uint32:
"""Return the index of the maximum element of a vector ``v``."""
...
@over
def outer(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Matrix[Any, Any, Scalar]:
"""Compute the outer product ``x*y^T`` for two vectors."""
...
@over
def cross(x: Vector[3, Scalar], y: Vector[3, Scalar]) -> Vector[3, Scalar]:
"""Compute the cross product of two 3D vectors."""
...
@over
def skew(x: Vector[3, Scalar]):
"""Compute the skew-symmetric 3x3 matrix for a 3D vector ``x``."""
...
@over
def length(x: Vector[Any, Float]) -> Scalar:
"""Compute the length of a floating-point vector ``x``."""
...
@over
def length(x: Quaternion[Float]) -> Scalar:
"""Compute the length of a quaternion ``x``."""
...
@over
def length_sq(x: Vector[Any, Scalar]) -> Scalar:
"""Compute the squared length of a vector ``x``."""
...
@over
def length_sq(x: Quaternion[Scalar]) -> Scalar:
"""Compute the squared length of a quaternion ``x``."""
...
@over
def normalize(x: Vector[Any, Float]) -> Vector[Any, Scalar]:
"""Compute the normalized value of ``x``. If ``length(x)`` is 0 then the zero vector is returned."""
...
@over
def normalize(x: Quaternion[Float]) -> Quaternion[Scalar]:
"""Compute the normalized value of ``x``. If ``length(x)`` is 0, then the zero quaternion is returned."""
...
@over
def transpose(m: Matrix[Any, Any, Scalar]):
"""Return the transpose of the matrix ``m``."""
...
@over
def inverse(m: Matrix[2, 2, Float]) -> Matrix[Any, Any, Float]:
"""Return the inverse of a 2x2 matrix ``m``."""
...
@over
def inverse(m: Matrix[3, 3, Float]) -> Matrix[Any, Any, Float]:
"""Return the inverse of a 3x3 matrix ``m``."""
...
@over
def inverse(m: Matrix[4, 4, Float]) -> Matrix[Any, Any, Float]:
"""Return the inverse of a 4x4 matrix ``m``."""
...
@over
def determinant(m: Matrix[2, 2, Float]) -> Scalar:
"""Return the determinant of a 2x2 matrix ``m``."""
...
@over
def determinant(m: Matrix[3, 3, Float]) -> Scalar:
"""Return the determinant of a 3x3 matrix ``m``."""
...
@over
def determinant(m: Matrix[4, 4, Float]) -> Scalar:
"""Return the determinant of a 4x4 matrix ``m``."""
...
@over
def trace(m: Matrix[Any, Any, Scalar]) -> Scalar:
"""Return the trace of the matrix ``m``."""
...
@over
def diag(d: Vector[Any, Scalar]) -> Matrix[Any, Any, Scalar]:
"""Returns a matrix with the components of the vector ``d`` on the diagonal."""
...
@over
def get_diag(m: Matrix[Any, Any, Scalar]) -> Vector[Any, Scalar]:
"""Returns a vector containing the diagonal elements of the square matrix ``m``."""
...
@over
def cw_mul(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
"""Component-wise multiplication of two vectors."""
...
@over
def cw_mul(x: Matrix[Any, Any, Scalar], y: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
"""Component-wise multiplication of two matrices."""
...
@over
def cw_div(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
"""Component-wise division of two vectors."""
...
@over
def cw_div(x: Matrix[Any, Any, Scalar], y: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
"""Component-wise division of two matrices."""
...
@over
def quat_identity() -> quatf:
"""Construct an identity quaternion with zero imaginary part and real part of 1.0"""
...
@over
def quat_from_axis_angle(axis: Vector[3, Float], angle: Float) -> Quaternion[Scalar]:
"""Construct a quaternion representing a rotation of angle radians around the given axis."""
...
@over
def quat_to_axis_angle(q: Quaternion[Float], axis: Vector[3, Float], angle: Float):
"""Extract the rotation axis and angle radians a quaternion represents."""
...
@over
def quat_from_matrix(m: Matrix[3, 3, Float]) -> Quaternion[Scalar]:
"""Construct a quaternion from a 3x3 matrix."""
...
@over
def quat_rpy(roll: Float, pitch: Float, yaw: Float) -> Quaternion[Scalar]:
"""Construct a quaternion representing a combined roll (z), pitch (x), yaw rotations (y) in radians."""
...
@over
def quat_inverse(q: Quaternion[Float]) -> Quaternion[Scalar]:
"""Compute quaternion conjugate."""
...
@over
def quat_rotate(q: Quaternion[Float], p: Vector[3, Float]) -> Vector[3, Scalar]:
"""Rotate a vector by a quaternion."""
...
@over
def quat_rotate_inv(q: Quaternion[Float], p: Vector[3, Float]) -> Vector[3, Scalar]:
"""Rotate a vector by the inverse of a quaternion."""
...
@over
def quat_slerp(q0: Quaternion[Float], q1: Quaternion[Float], t: Float) -> Quaternion[Scalar]:
"""Linearly interpolate between two quaternions."""
...
@over
def quat_to_matrix(q: Quaternion[Float]) -> Matrix[3, 3, Scalar]:
"""Convert a quaternion to a 3x3 rotation matrix."""
...
@over
def transform_identity() -> transformf:
"""Construct an identity transform with zero translation and identity rotation."""
...
@over
def transform_get_translation(t: Transformation[Float]) -> Vector[3, Scalar]:
"""Return the translational part of a transform ``t``."""
...
@over
def transform_get_rotation(t: Transformation[Float]) -> Quaternion[Scalar]:
"""Return the rotational part of a transform ``t``."""
...
@over
def transform_multiply(a: Transformation[Float], b: Transformation[Float]) -> Transformation[Scalar]:
"""Multiply two rigid body transformations together."""
...
@over
def transform_point(t: Transformation[Scalar], p: Vector[3, Scalar]) -> Vector[3, Scalar]:
"""Apply the transform to a point ``p`` treating the homogeneous coordinate as w=1 (translation and rotation)."""
...
@over
def transform_point(m: Matrix[4, 4, Scalar], p: Vector[3, Scalar]) -> Vector[3, Scalar]:
"""Apply the transform to a point ``p`` treating the homogeneous coordinate as w=1.
The transformation is applied treating ``p`` as a column vector, e.g.: ``y = M*p``.
Note this is in contrast to some libraries, notably USD, which applies transforms to row vectors, ``y^T = p^T*M^T``.
If the transform is coming from a library that uses row-vectors, then users should transpose the transformation
matrix before calling this method.
"""
...
@over
def transform_vector(t: Transformation[Scalar], v: Vector[3, Scalar]) -> Vector[3, Scalar]:
"""Apply the transform to a vector ``v`` treating the homogeneous coordinate as w=0 (rotation only)."""
...
@over
def transform_vector(m: Matrix[4, 4, Scalar], v: Vector[3, Scalar]) -> Vector[3, Scalar]:
"""Apply the transform to a vector ``v`` treating the homogeneous coordinate as w=0.
The transformation is applied treating ``v`` as a column vector, e.g.: ``y = M*v``
note this is in contrast to some libraries, notably USD, which applies transforms to row vectors, ``y^T = v^T*M^T``.
If the transform is coming from a library that uses row-vectors, then users should transpose the transformation
matrix before calling this method.
"""
...
@over
def transform_inverse(t: Transformation[Float]) -> Transformation[Float]:
"""Compute the inverse of the transformation ``t``."""
...
@over
def spatial_dot(a: Vector[6, Float], b: Vector[6, Float]) -> Scalar:
"""Compute the dot product of two 6D screw vectors."""
...
@over
def spatial_cross(a: Vector[6, Float], b: Vector[6, Float]) -> Vector[6, Float]:
"""Compute the cross product of two 6D screw vectors."""
...
@over
def spatial_cross_dual(a: Vector[6, Float], b: Vector[6, Float]) -> Vector[6, Float]:
"""Compute the dual cross product of two 6D screw vectors."""
...
@over
def spatial_top(a: Vector[6, Float]):
"""Return the top (first) part of a 6D screw vector."""
...
@over
def spatial_bottom(a: Vector[6, Float]):
"""Return the bottom (second) part of a 6D screw vector."""
...
@over
def spatial_jacobian(
S: Array[Vector[6, Float]],
joint_parents: Array[int32],
joint_qd_start: Array[int32],
joint_start: int32,
joint_count: int32,
J_start: int32,
J_out: Array[Float],
):
""" """
...
@over
def spatial_mass(
I_s: Array[Matrix[6, 6, Float]], joint_start: int32, joint_count: int32, M_start: int32, M: Array[Float]
):
""" """
...
@over
def mlp(
weights: Array[float32],
bias: Array[float32],
activation: Callable,
index: int32,
x: Array[float32],
out: Array[float32],
):
"""Evaluate a multi-layer perceptron (MLP) layer in the form: ``out = act(weights*x + bias)``.
:param weights: A layer's network weights with dimensions ``(m, n)``.
:param bias: An array with dimensions ``(n)``.
:param activation: A ``wp.func`` function that takes a single scalar float as input and returns a scalar float as output
:param index: The batch item to process, typically each thread will process one item in the batch, in which case
index should be ``wp.tid()``
:param x: The feature matrix with dimensions ``(n, b)``
:param out: The network output with dimensions ``(m, b)``
:note: Feature and output matrices are transposed compared to some other frameworks such as PyTorch.
All matrices are assumed to be stored in flattened row-major memory layout (NumPy default).
"""
...
@over
def bvh_query_aabb(id: uint64, lower: vec3f, upper: vec3f) -> bvh_query_t:
"""Construct an axis-aligned bounding box query against a BVH object.
This query can be used to iterate over all bounds inside a BVH.
:param id: The BVH identifier
:param lower: The lower bound of the bounding box in BVH space
:param upper: The upper bound of the bounding box in BVH space
"""
...
@over
def bvh_query_ray(id: uint64, start: vec3f, dir: vec3f) -> bvh_query_t:
"""Construct a ray query against a BVH object.
This query can be used to iterate over all bounds that intersect the ray.
:param id: The BVH identifier
:param start: The start of the ray in BVH space
:param dir: The direction of the ray in BVH space
"""
...
@over
def bvh_query_next(query: bvh_query_t, index: int32) -> bool:
"""Move to the next bound returned by the query.
The index of the current bound is stored in ``index``, returns ``False`` if there are no more overlapping bound.
"""
...
@over
def mesh_query_point(id: uint64, point: vec3f, max_dist: float32) -> mesh_query_point_t:
"""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space.
Identifies the sign of the distance using additional ray-casts to determine if the point is inside or outside.
This method is relatively robust, but does increase computational cost.
See below for additional sign determination methods.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
"""
...
@over
def mesh_query_point_no_sign(id: uint64, point: vec3f, max_dist: float32) -> mesh_query_point_t:
"""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space.
This method does not compute the sign of the point (inside/outside) which makes it faster than other point query methods.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
"""
...
@over
def mesh_query_furthest_point_no_sign(id: uint64, point: vec3f, min_dist: float32) -> mesh_query_point_t:
"""Computes the furthest point on the mesh with identifier `id` to the given point in space.
This method does not compute the sign of the point (inside/outside).
:param id: The mesh identifier
:param point: The point in space to query
:param min_dist: Mesh faces below this distance will not be considered by the query
"""
...
@over
def mesh_query_point_sign_normal(id: uint64, point: vec3f, max_dist: float32, epsilon: float32) -> mesh_query_point_t:
"""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space.
Identifies the sign of the distance (inside/outside) using the angle-weighted pseudo normal.
This approach to sign determination is robust for well conditioned meshes that are watertight and non-self intersecting.
It is also comparatively fast to compute.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param epsilon: Epsilon treating distance values as equal, when locating the minimum distance vertex/face/edge, as a
fraction of the average edge length, also for treating closest point as being on edge/vertex default 1e-3
"""
...
@over
def mesh_query_point_sign_winding_number(
id: uint64, point: vec3f, max_dist: float32, accuracy: float32, threshold: float32
) -> mesh_query_point_t:
"""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given point in space.
Identifies the sign using the winding number of the mesh relative to the query point. This method of sign determination is robust for poorly conditioned meshes
and provides a smooth approximation to sign even when the mesh is not watertight. This method is the most robust and accurate of the sign determination meshes
but also the most expensive.
.. note:: The :class:`Mesh` object must be constructed with ``support_winding_number=True`` for this method to return correct results.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param accuracy: Accuracy for computing the winding number with fast winding number method utilizing second-order dipole approximation, default 2.0
:param threshold: The threshold of the winding number to be considered inside, default 0.5
"""
...
@over
def mesh_query_ray(id: uint64, start: vec3f, dir: vec3f, max_t: float32) -> mesh_query_ray_t:
"""Computes the closest ray hit on the :class:`Mesh` with identifier ``id``.
:param id: The mesh identifier
:param start: The start point of the ray
:param dir: The ray direction (should be normalized)
:param max_t: The maximum distance along the ray to check for intersections
"""
...
@over
def mesh_query_aabb(id: uint64, lower: vec3f, upper: vec3f) -> mesh_query_aabb_t:
"""Construct an axis-aligned bounding box query against a :class:`Mesh`.
This query can be used to iterate over all triangles inside a volume.
:param id: The mesh identifier
:param lower: The lower bound of the bounding box in mesh space
:param upper: The upper bound of the bounding box in mesh space
"""
...
@over
def mesh_query_aabb_next(query: mesh_query_aabb_t, index: int32) -> bool:
"""Move to the next triangle overlapping the query bounding box.
The index of the current face is stored in ``index``, returns ``False`` if there are no more overlapping triangles.
"""
...
@over
def mesh_eval_position(id: uint64, face: int32, bary_u: float32, bary_v: float32) -> vec3f:
"""Evaluates the position on the :class:`Mesh` given a face index and barycentric coordinates."""
...
@over
def mesh_eval_velocity(id: uint64, face: int32, bary_u: float32, bary_v: float32) -> vec3f:
"""Evaluates the velocity on the :class:`Mesh` given a face index and barycentric coordinates."""
...
@over
def hash_grid_query(id: uint64, point: vec3f, max_dist: float32) -> hash_grid_query_t:
"""Construct a point query against a :class:`HashGrid`.
This query can be used to iterate over all neighboring point within a fixed radius from the query point.
"""
...
@over
def hash_grid_query_next(query: hash_grid_query_t, index: int32) -> bool:
"""Move to the next point in the hash grid query.
The index of the current neighbor is stored in ``index``, returns ``False`` if there are no more neighbors.
"""
...
@over
def hash_grid_point_id(id: uint64, index: int32) -> int:
"""Return the index of a point in the :class:`HashGrid`.
This can be used to reorder threads such that grid traversal occurs in a spatially coherent order.
Returns -1 if the :class:`HashGrid` has not been reserved.
"""
...
@over
def intersect_tri_tri(v0: vec3f, v1: vec3f, v2: vec3f, u0: vec3f, u1: vec3f, u2: vec3f) -> int:
"""Tests for intersection between two triangles (v0, v1, v2) and (u0, u1, u2) using Moller's method.
Returns > 0 if triangles intersect.
"""
...
@over
def mesh_get(id: uint64) -> Mesh:
"""Retrieves the mesh given its index."""
...
@over
def mesh_eval_face_normal(id: uint64, face: int32) -> vec3f:
"""Evaluates the face normal the mesh given a face index."""
...
@over
def mesh_get_point(id: uint64, index: int32) -> vec3f:
"""Returns the point of the mesh given a index."""
...
@over
def mesh_get_velocity(id: uint64, index: int32) -> vec3f:
"""Returns the velocity of the mesh given a index."""
...
@over
def mesh_get_index(id: uint64, index: int32) -> int:
"""Returns the point-index of the mesh given a face-vertex index."""
...
@over
def closest_point_edge_edge(p1: vec3f, q1: vec3f, p2: vec3f, q2: vec3f, epsilon: float32) -> vec3f:
"""Finds the closest points between two edges.
Returns barycentric weights to the points on each edge, as well as the closest distance between the edges.
:param p1: First point of first edge
:param q1: Second point of first edge
:param p2: First point of second edge
:param q2: Second point of second edge
:param epsilon: Zero tolerance for determining if points in an edge are degenerate.
:param out: vec3 output containing (s,t,d), where `s` in [0,1] is the barycentric weight for the first edge, `t` is the barycentric weight for the second edge, and `d` is the distance between the two edges at these two closest points.
"""
...
@over
def volume_sample_f(id: uint64, uvw: vec3f, sampling_mode: int32) -> float:
"""Sample the volume given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`
"""
...
@over
def volume_sample_grad_f(id: uint64, uvw: vec3f, sampling_mode: int32, grad: vec3f) -> float:
"""Sample the volume and its gradient given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`
"""
...
@over
def volume_lookup_f(id: uint64, i: int32, j: int32, k: int32) -> float:
"""Returns the value of voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns the background value
"""
...
@over
def volume_store_f(id: uint64, i: int32, j: int32, k: int32, value: float32):
"""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``."""
...
@over
def volume_sample_v(id: uint64, uvw: vec3f, sampling_mode: int32) -> vec3f:
"""Sample the vector volume given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`
"""
...
@over
def volume_lookup_v(id: uint64, i: int32, j: int32, k: int32) -> vec3f:
"""Returns the vector value of voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns the background value.
"""
...
@over
def volume_store_v(id: uint64, i: int32, j: int32, k: int32, value: vec3f):
"""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``."""
...
@over
def volume_sample_i(id: uint64, uvw: vec3f) -> int:
"""Sample the :class:`int32` volume given by ``id`` at the volume local-space point ``uvw``."""
...
@over
def volume_lookup_i(id: uint64, i: int32, j: int32, k: int32) -> int:
"""Returns the :class:`int32` value of voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns the background value.
"""
...
@over
def volume_store_i(id: uint64, i: int32, j: int32, k: int32, value: int32):
"""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``."""
...
@over
def volume_lookup_index(id: uint64, i: int32, j: int32, k: int32) -> int32:
"""Returns the index associated to the voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns -1.
This function is available for both index grids and classical volumes.
"""
...
@over
def volume_index_to_world(id: uint64, uvw: vec3f) -> vec3f:
"""Transform a point ``uvw`` defined in volume index space to world space given the volume's intrinsic affine transformation."""
...
@over
def volume_world_to_index(id: uint64, xyz: vec3f) -> vec3f:
"""Transform a point ``xyz`` defined in volume world space to the volume's index space given the volume's intrinsic affine transformation."""
...
@over
def volume_index_to_world_dir(id: uint64, uvw: vec3f) -> vec3f:
"""Transform a direction ``uvw`` defined in volume index space to world space given the volume's intrinsic affine transformation."""
...
@over
def volume_world_to_index_dir(id: uint64, xyz: vec3f) -> vec3f:
"""Transform a direction ``xyz`` defined in volume world space to the volume's index space given the volume's intrinsic affine transformation."""
...
@over
def rand_init(seed: int32) -> uint32:
"""Initialize a new random number generator given a user-defined seed. Returns a 32-bit integer representing the RNG state."""
...
@over
def rand_init(seed: int32, offset: int32) -> uint32:
"""Initialize a new random number generator given a user-defined seed and an offset.
This alternative constructor can be useful in parallel programs, where a kernel as a whole should share a seed,
but each thread should generate uncorrelated values. In this case usage should be ``r = rand_init(seed, tid)``
"""
...
@over
def randi(state: uint32) -> int:
"""Return a random integer in the range [0, 2^32)."""
...
@over
def randi(state: uint32, min: int32, max: int32) -> int:
"""Return a random integer between [min, max)."""
...
@over
def randf(state: uint32) -> float:
"""Return a random float between [0.0, 1.0)."""
...
@over
def randf(state: uint32, min: float32, max: float32) -> float:
"""Return a random float between [min, max)."""
...
@over
def randn(state: uint32) -> float:
"""Sample a normal distribution."""
...
@over
def sample_cdf(state: uint32, cdf: Array[float32]) -> int:
"""Inverse-transform sample a cumulative distribution function."""
...
@over
def sample_triangle(state: uint32) -> vec2f:
"""Uniformly sample a triangle. Returns sample barycentric coordinates."""
...
@over
def sample_unit_ring(state: uint32) -> vec2f:
"""Uniformly sample a ring in the xy plane."""
...
@over
def sample_unit_disk(state: uint32) -> vec2f:
"""Uniformly sample a disk in the xy plane."""
...
@over
def sample_unit_sphere_surface(state: uint32) -> vec3f:
"""Uniformly sample a unit sphere surface."""
...
@over
def sample_unit_sphere(state: uint32) -> vec3f:
"""Uniformly sample a unit sphere."""
...
@over
def sample_unit_hemisphere_surface(state: uint32) -> vec3f:
"""Uniformly sample a unit hemisphere surface."""
...
@over
def sample_unit_hemisphere(state: uint32) -> vec3f:
"""Uniformly sample a unit hemisphere."""
...
@over
def sample_unit_square(state: uint32) -> vec2f:
"""Uniformly sample a unit square."""
...
@over
def sample_unit_cube(state: uint32) -> vec3f:
"""Uniformly sample a unit cube."""
...
@over
def poisson(state: uint32, lam: float32) -> uint32:
"""Generate a random sample from a Poisson distribution.
:param state: RNG state
:param lam: The expected value of the distribution
"""
...
@over
def noise(state: uint32, x: float32) -> float:
"""Non-periodic Perlin-style noise in 1D."""
...
@over
def noise(state: uint32, xy: vec2f) -> float:
"""Non-periodic Perlin-style noise in 2D."""
...
@over
def noise(state: uint32, xyz: vec3f) -> float:
"""Non-periodic Perlin-style noise in 3D."""
...
@over
def noise(state: uint32, xyzt: vec4f) -> float:
"""Non-periodic Perlin-style noise in 4D."""
...
@over
def pnoise(state: uint32, x: float32, px: int32) -> float:
"""Periodic Perlin-style noise in 1D."""
...
@over
def pnoise(state: uint32, xy: vec2f, px: int32, py: int32) -> float:
"""Periodic Perlin-style noise in 2D."""
...
@over
def pnoise(state: uint32, xyz: vec3f, px: int32, py: int32, pz: int32) -> float:
"""Periodic Perlin-style noise in 3D."""
...
@over
def pnoise(state: uint32, xyzt: vec4f, px: int32, py: int32, pz: int32, pt: int32) -> float:
"""Periodic Perlin-style noise in 4D."""
...
@over
def curlnoise(state: uint32, xy: vec2f, octaves: uint32, lacunarity: float32, gain: float32) -> vec2f:
"""Divergence-free vector field based on the gradient of a Perlin noise function."""
...
@over
def curlnoise(state: uint32, xyz: vec3f, octaves: uint32, lacunarity: float32, gain: float32) -> vec3f:
"""Divergence-free vector field based on the curl of three Perlin noise functions."""
...
@over
def curlnoise(state: uint32, xyzt: vec4f, octaves: uint32, lacunarity: float32, gain: float32) -> vec3f:
"""Divergence-free vector field based on the curl of three Perlin noise functions."""
...
@over
def printf():
"""Allows printing formatted strings using C-style format specifiers."""
...
@over
def tid() -> Tuple[int, int]:
"""Return the current thread indices for a 2D kernel launch.
Use ``i,j = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid.
This function may not be called from user-defined Warp functions.
"""
...
@over
def tid() -> Tuple[int, int, int]:
"""Return the current thread indices for a 3D kernel launch.
Use ``i,j,k = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid.
This function may not be called from user-defined Warp functions.
"""
...
@over
def tid() -> Tuple[int, int, int, int]:
"""Return the current thread indices for a 4D kernel launch.
Use ``i,j,k,l = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid.
This function may not be called from user-defined Warp functions.
"""
...
@over
def select(cond: bool, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: int8, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: uint8, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: int16, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: uint16, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: int32, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: uint32, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: int64, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(cond: uint64, arg1: Any, arg2: Any):
"""Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``"""
...
@over
def select(arr: Array[Any], arg1: Any, arg2: Any):
"""Select between two arguments, if ``arr`` is null then return ``arg1``, otherwise return ``arg2``"""
...
@over
def atomic_add(a: Array[Any], i: int32, value: Any):
"""Atomically add ``value`` onto ``a[i]``."""
...
@over
def atomic_add(a: Array[Any], i: int32, j: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j]``."""
...
@over
def atomic_add(a: Array[Any], i: int32, j: int32, k: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j,k]``."""
...
@over
def atomic_add(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j,k,l]``."""
...
@over
def atomic_add(a: FabricArray[Any], i: int32, value: Any):
"""Atomically add ``value`` onto ``a[i]``."""
...
@over
def atomic_add(a: FabricArray[Any], i: int32, j: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j]``."""
...
@over
def atomic_add(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j,k]``."""
...
@over
def atomic_add(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j,k,l]``."""
...
@over
def atomic_add(a: IndexedFabricArray[Any], i: int32, value: Any):
"""Atomically add ``value`` onto ``a[i]``."""
...
@over
def atomic_add(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j]``."""
...
@over
def atomic_add(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j,k]``."""
...
@over
def atomic_add(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Atomically add ``value`` onto ``a[i,j,k,l]``."""
...
@over
def atomic_sub(a: Array[Any], i: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i]``."""
...
@over
def atomic_sub(a: Array[Any], i: int32, j: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j]``."""
...
@over
def atomic_sub(a: Array[Any], i: int32, j: int32, k: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j,k]``."""
...
@over
def atomic_sub(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j,k,l]``."""
...
@over
def atomic_sub(a: FabricArray[Any], i: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i]``."""
...
@over
def atomic_sub(a: FabricArray[Any], i: int32, j: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j]``."""
...
@over
def atomic_sub(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j,k]``."""
...
@over
def atomic_sub(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j,k,l]``."""
...
@over
def atomic_sub(a: IndexedFabricArray[Any], i: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i]``."""
...
@over
def atomic_sub(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j]``."""
...
@over
def atomic_sub(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j,k]``."""
...
@over
def atomic_sub(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Atomically subtract ``value`` onto ``a[i,j,k,l]``."""
...
@over
def atomic_min(a: Array[Any], i: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: Array[Any], i: int32, j: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: Array[Any], i: int32, j: int32, k: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: FabricArray[Any], i: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: FabricArray[Any], i: int32, j: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: IndexedFabricArray[Any], i: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_min(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: Array[Any], i: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: Array[Any], i: int32, j: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: Array[Any], i: int32, j: int32, k: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: Array[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: FabricArray[Any], i: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: FabricArray[Any], i: int32, j: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: FabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: FabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: IndexedFabricArray[Any], i: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: IndexedFabricArray[Any], i: int32, j: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def atomic_max(a: IndexedFabricArray[Any], i: int32, j: int32, k: int32, l: int32, value: Any):
"""Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.
"""
...
@over
def lerp(a: Float, b: Float, t: Float) -> Float:
"""Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``"""
...
@over
def lerp(a: Vector[Any, Float], b: Vector[Any, Float], t: Float) -> Vector[Any, Float]:
"""Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``"""
...
@over
def lerp(a: Matrix[Any, Any, Float], b: Matrix[Any, Any, Float], t: Float) -> Matrix[Any, Any, Float]:
"""Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``"""
...
@over
def lerp(a: Quaternion[Float], b: Quaternion[Float], t: Float) -> Quaternion[Float]:
"""Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``"""
...
@over
def lerp(a: Transformation[Float], b: Transformation[Float], t: Float) -> Transformation[Float]:
"""Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``"""
...
@over
def smoothstep(edge0: Float, edge1: Float, x: Float) -> Float:
"""Smoothly interpolate between two values ``edge0`` and ``edge1`` using a factor ``x``,
and return a result between 0 and 1 using a cubic Hermite interpolation after clamping.
"""
...
@over
def expect_near(arg1: Float, arg2: Float, tolerance: Float):
"""Prints an error to stdout if ``arg1`` and ``arg2`` are not closer than tolerance in magnitude"""
...
@over
def expect_near(arg1: vec3f, arg2: vec3f, tolerance: float32):
"""Prints an error to stdout if any element of ``arg1`` and ``arg2`` are not closer than tolerance in magnitude"""
...
@over
def lower_bound(arr: Array[Scalar], value: Scalar) -> int:
"""Search a sorted array ``arr`` for the closest element greater than or equal to ``value``."""
...
@over
def lower_bound(arr: Array[Scalar], arr_begin: int32, arr_end: int32, value: Scalar) -> int:
"""Search a sorted array ``arr`` in the range [arr_begin, arr_end) for the closest element greater than or equal to ``value``."""
...
@over
def add(x: Scalar, y: Scalar) -> Scalar:
""" """
...
@over
def add(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def add(x: Quaternion[Scalar], y: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def add(x: Matrix[Any, Any, Scalar], y: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def add(x: Transformation[Scalar], y: Transformation[Scalar]) -> Transformation[Scalar]:
""" """
...
@over
def sub(x: Scalar, y: Scalar) -> Scalar:
""" """
...
@over
def sub(x: Vector[Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def sub(x: Matrix[Any, Any, Scalar], y: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def sub(x: Quaternion[Scalar], y: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def sub(x: Transformation[Scalar], y: Transformation[Scalar]) -> Transformation[Scalar]:
""" """
...
@over
def bit_and(x: Int, y: Int) -> Int:
""" """
...
@over
def bit_or(x: Int, y: Int) -> Int:
""" """
...
@over
def bit_xor(x: Int, y: Int) -> Int:
""" """
...
@over
def lshift(x: Int, y: Int) -> Int:
""" """
...
@over
def rshift(x: Int, y: Int) -> Int:
""" """
...
@over
def invert(x: Int) -> Int:
""" """
...
@over
def mul(x: Scalar, y: Scalar) -> Scalar:
""" """
...
@over
def mul(x: Vector[Any, Scalar], y: Scalar) -> Vector[Any, Scalar]:
""" """
...
@over
def mul(x: Scalar, y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def mul(x: Quaternion[Scalar], y: Scalar) -> Quaternion[Scalar]:
""" """
...
@over
def mul(x: Scalar, y: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def mul(x: Quaternion[Scalar], y: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def mul(x: Scalar, y: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def mul(x: Matrix[Any, Any, Scalar], y: Scalar) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def mul(x: Matrix[Any, Any, Scalar], y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def mul(x: Vector[Any, Scalar], y: Matrix[Any, Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def mul(x: Matrix[Any, Any, Scalar], y: Matrix[Any, Any, Scalar]):
""" """
...
@over
def mul(x: Transformation[Scalar], y: Transformation[Scalar]) -> Transformation[Scalar]:
""" """
...
@over
def mul(x: Scalar, y: Transformation[Scalar]) -> Transformation[Scalar]:
""" """
...
@over
def mul(x: Transformation[Scalar], y: Scalar) -> Transformation[Scalar]:
""" """
...
@over
def mod(x: Scalar, y: Scalar) -> Scalar:
""" """
...
@over
def div(x: Scalar, y: Scalar) -> Scalar:
""" """
...
@over
def div(x: Vector[Any, Scalar], y: Scalar) -> Vector[Any, Scalar]:
""" """
...
@over
def div(x: Scalar, y: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def div(x: Matrix[Any, Any, Scalar], y: Scalar) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def div(x: Scalar, y: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def div(x: Quaternion[Scalar], y: Scalar) -> Quaternion[Scalar]:
""" """
...
@over
def div(x: Scalar, y: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def floordiv(x: Scalar, y: Scalar) -> Scalar:
""" """
...
@over
def pos(x: Scalar) -> Scalar:
""" """
...
@over
def pos(x: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def pos(x: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def pos(x: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def neg(x: Scalar) -> Scalar:
""" """
...
@over
def neg(x: Vector[Any, Scalar]) -> Vector[Any, Scalar]:
""" """
...
@over
def neg(x: Quaternion[Scalar]) -> Quaternion[Scalar]:
""" """
...
@over
def neg(x: Matrix[Any, Any, Scalar]) -> Matrix[Any, Any, Scalar]:
""" """
...
@over
def unot(b: bool) -> bool:
""" """
...
@over
def unot(b: int8) -> bool:
""" """
...
@over
def unot(b: uint8) -> bool:
""" """
...
@over
def unot(b: int16) -> bool:
""" """
...
@over
def unot(b: uint16) -> bool:
""" """
...
@over
def unot(b: int32) -> bool:
""" """
...
@over
def unot(b: uint32) -> bool:
""" """
...
@over
def unot(b: int64) -> bool:
""" """
...
@over
def unot(b: uint64) -> bool:
""" """
...
@over
def unot(a: Array[Any]) -> bool:
""" """
...
| 57,977 | Python | 25.437756 | 238 | 0.634476 |
NVIDIA/warp/warp/config.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 Optional
version: str = "1.1.1"
verify_fp: bool = False # verify inputs and outputs are finite after each launch
verify_cuda: bool = False # if true will check CUDA errors after each kernel launch / memory operation
print_launches: bool = False # if true will print out launch information
mode: str = "release"
verbose: bool = False # print extra informative messages
verbose_warnings: bool = False # whether file and line info gets included in Warp warnings
quiet: bool = False # suppress all output except errors and warnings
cache_kernels: bool = True
kernel_cache_dir: bool = None # path to kernel cache directory, if None a default path will be used
cuda_output: Optional[str] = (
None # preferred CUDA output format for kernels ("ptx" or "cubin"), determined automatically if unspecified
)
ptx_target_arch: int = 75 # target architecture for PTX generation, defaults to the lowest architecture that supports all of Warp's features
enable_backward: bool = True # whether to compiler the backward passes of the kernels
llvm_cuda: bool = False # use Clang/LLVM instead of NVRTC to compile CUDA
enable_graph_capture_module_load_by_default: bool = (
True # Default value of force_module_load for capture_begin() if CUDA driver does not support at least CUDA 12.3
)
enable_mempools_at_init: bool = True # Whether CUDA devices will be initialized with mempools enabled (if supported)
max_unroll: int = 16
| 1,879 | Python | 44.853657 | 141 | 0.767962 |
NVIDIA/warp/warp/dlpack.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.
# Python specification for DLpack:
# https://dmlc.github.io/dlpack/latest/python_spec.html
import ctypes
import warp
from warp.thirdparty.dlpack import (
DLDataType,
DLDataTypeCode,
DLDevice,
DLDeviceType,
DLManagedTensor,
_c_str_dltensor,
)
_c_str_used_dltensor = b"used_dltensor"
PyMem_RawMalloc = ctypes.pythonapi.PyMem_RawMalloc
PyMem_RawMalloc.argtypes = [ctypes.c_size_t]
PyMem_RawMalloc.restype = ctypes.c_void_p
PyMem_RawFree = ctypes.pythonapi.PyMem_RawFree
PyMem_RawFree.argtypes = [ctypes.c_void_p]
PyMem_RawFree.restype = None
Py_IncRef = ctypes.pythonapi.Py_IncRef
Py_IncRef.argtypes = [ctypes.py_object]
Py_IncRef.restype = None
Py_DecRef = ctypes.pythonapi.Py_DecRef
Py_DecRef.argtypes = [ctypes.py_object]
Py_DecRef.restype = None
PyCapsule_Destructor = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
PyCapsule_New = ctypes.pythonapi.PyCapsule_New
PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, PyCapsule_Destructor]
PyCapsule_New.restype = ctypes.py_object
PyCapsule_IsValid = ctypes.pythonapi.PyCapsule_IsValid
PyCapsule_IsValid.argtypes = [ctypes.py_object, ctypes.c_char_p]
PyCapsule_IsValid.restype = ctypes.c_int
PyCapsule_GetPointer = ctypes.pythonapi.PyCapsule_GetPointer
PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
PyCapsule_GetPointer.restype = ctypes.c_void_p
PyCapsule_SetName = ctypes.pythonapi.PyCapsule_SetName
PyCapsule_SetName.argtypes = [ctypes.py_object, ctypes.c_char_p]
PyCapsule_SetName.restype = ctypes.c_int
class _DLPackTensorHolder:
"""Class responsible for deleting DLManagedTensor memory after ownership is transferred from a capsule."""
def __init__(self, mem_ptr):
self.mem_ptr = mem_ptr
def __del__(self):
managed_tensor = DLManagedTensor.from_address(self.mem_ptr)
if managed_tensor.deleter:
managed_tensor.deleter(self.mem_ptr)
@ctypes.CFUNCTYPE(None, ctypes.c_void_p)
def _dlpack_tensor_deleter(managed_ptr) -> None:
"""A function to deallocate a DLManagedTensor."""
managed_tensor = DLManagedTensor.from_address(managed_ptr)
# unreference the source array
manager = ctypes.cast(managed_tensor.manager_ctx, ctypes.py_object)
ctypes.pythonapi.Py_DecRef(manager)
# free the DLManagedTensor memory, including shape and strides
PyMem_RawFree(ctypes.c_void_p(managed_ptr))
@PyCapsule_Destructor
def _dlpack_capsule_deleter(ptr) -> None:
"""Destructor for a capsule holding a DLManagedTensor."""
capsule = ctypes.cast(ptr, ctypes.py_object)
if ctypes.pythonapi.PyCapsule_IsValid(capsule, _c_str_dltensor):
managed_ptr = ctypes.pythonapi.PyCapsule_GetPointer(capsule, _c_str_dltensor)
managed_tensor = DLManagedTensor.from_address(managed_ptr)
if managed_tensor.deleter:
managed_tensor.deleter(managed_ptr)
def _device_to_dlpack(wp_device: warp.context.Device) -> DLDevice:
dl_device = DLDevice()
if wp_device.is_cpu:
dl_device.device_type = DLDeviceType.kDLCPU
dl_device.device_id = 0
elif wp_device.is_cuda:
dl_device.device_type = DLDeviceType.kDLCUDA
dl_device.device_id = wp_device.ordinal
else:
raise RuntimeError(f"Invalid device type converting to DLPack: {wp_device}")
return dl_device
def device_to_dlpack(wp_device) -> DLDevice:
return _device_to_dlpack(warp.get_device(wp_device))
def dtype_to_dlpack(wp_dtype) -> DLDataType:
if wp_dtype == warp.int8:
return (DLDataTypeCode.kDLInt, 8, 1)
elif wp_dtype == warp.uint8:
return (DLDataTypeCode.kDLUInt, 8, 1)
elif wp_dtype == warp.int16:
return (DLDataTypeCode.kDLInt, 16, 1)
elif wp_dtype == warp.uint16:
return (DLDataTypeCode.kDLUInt, 16, 1)
elif wp_dtype == warp.int32:
return (DLDataTypeCode.kDLInt, 32, 1)
elif wp_dtype == warp.uint32:
return (DLDataTypeCode.kDLUInt, 32, 1)
elif wp_dtype == warp.int64:
return (DLDataTypeCode.kDLInt, 64, 1)
elif wp_dtype == warp.uint64:
return (DLDataTypeCode.kDLUInt, 64, 1)
elif wp_dtype == warp.float16:
return (DLDataTypeCode.kDLFloat, 16, 1)
elif wp_dtype == warp.float32:
return (DLDataTypeCode.kDLFloat, 32, 1)
elif wp_dtype == warp.float64:
return (DLDataTypeCode.kDLFloat, 64, 1)
else:
raise RuntimeError(f"No conversion from Warp type {wp_dtype} to DLPack type")
def dtype_from_dlpack(dl_dtype):
# unpack to tuple for easier comparison
dl_dtype = (dl_dtype.type_code.value, dl_dtype.bits)
if dl_dtype == (DLDataTypeCode.kDLUInt, 1):
raise RuntimeError("Warp does not support bit boolean types")
elif dl_dtype == (DLDataTypeCode.kDLInt, 8):
return warp.types.int8
elif dl_dtype == (DLDataTypeCode.kDLInt, 16):
return warp.types.int16
elif dl_dtype == (DLDataTypeCode.kDLInt, 32):
return warp.types.int32
elif dl_dtype == (DLDataTypeCode.kDLInt, 64):
return warp.types.int64
elif dl_dtype == (DLDataTypeCode.kDLUInt, 8):
return warp.types.uint8
elif dl_dtype == (DLDataTypeCode.kDLUInt, 16):
return warp.types.uint16
elif dl_dtype == (DLDataTypeCode.kDLUInt, 32):
return warp.types.uint32
elif dl_dtype == (DLDataTypeCode.kDLUInt, 64):
return warp.types.uint64
elif dl_dtype == (DLDataTypeCode.kDLFloat, 16):
return warp.types.float16
elif dl_dtype == (DLDataTypeCode.kDLFloat, 32):
return warp.types.float32
elif dl_dtype == (DLDataTypeCode.kDLFloat, 64):
return warp.types.float64
elif dl_dtype == (DLDataTypeCode.kDLComplex, 64):
raise RuntimeError("Warp does not support complex types")
elif dl_dtype == (DLDataTypeCode.kDLComplex, 128):
raise RuntimeError("Warp does not support complex types")
else:
raise RuntimeError(f"Unknown DLPack datatype {dl_dtype}")
def device_from_dlpack(dl_device):
assert warp.context.runtime is not None, "Warp not initialized, call wp.init() before use"
if dl_device.device_type.value == DLDeviceType.kDLCPU or dl_device.device_type.value == DLDeviceType.kDLCUDAHost:
return warp.context.runtime.cpu_device
elif (
dl_device.device_type.value == DLDeviceType.kDLCUDA
or dl_device.device_type.value == DLDeviceType.kDLCUDAManaged
):
return warp.context.runtime.cuda_devices[dl_device.device_id]
else:
raise RuntimeError(f"Unknown device type from DLPack: {dl_device.device_type.value}")
def shape_to_dlpack(shape):
a = (ctypes.c_int64 * len(shape))(*shape)
return a
def strides_to_dlpack(strides, dtype):
# convert from byte count to element count
ndim = len(strides)
a = (ctypes.c_int64 * ndim)()
dtype_size = warp.types.type_size_in_bytes(dtype)
for i in range(ndim):
a[i] = strides[i] // dtype_size
return a
def to_dlpack(wp_array: warp.array):
"""Convert a Warp array to another type of DLPack-compatible array.
Args:
wp_array: The source Warp array that will be converted.
Returns:
A capsule containing a DLManagedTensor that can be converted
to another array type without copying the underlying memory.
"""
# DLPack does not support structured arrays
if isinstance(wp_array.dtype, warp.codegen.Struct):
raise RuntimeError("Cannot convert structured Warp arrays to DLPack.")
# handle vector types
if hasattr(wp_array.dtype, "_wp_scalar_type_"):
# vector type, flatten the dimensions into one tuple
target_dtype = wp_array.dtype._wp_scalar_type_
target_ndim = wp_array.ndim + len(wp_array.dtype._shape_)
target_shape = (*wp_array.shape, *wp_array.dtype._shape_)
dtype_strides = warp.types.strides_from_shape(wp_array.dtype._shape_, wp_array.dtype._wp_scalar_type_)
target_strides = (*wp_array.strides, *dtype_strides)
else:
# scalar type
target_dtype = wp_array.dtype
target_ndim = wp_array.ndim
target_shape = wp_array.shape
target_strides = wp_array.strides
if wp_array.pinned:
dl_device = DLDevice()
dl_device.device_type = DLDeviceType.kDLCUDAHost
dl_device.device_id = 0
else:
dl_device = _device_to_dlpack(wp_array.device)
# allocate DLManagedTensor, shape, and strides together
managed_tensor_size = ctypes.sizeof(DLManagedTensor)
padding = managed_tensor_size & 7
shape_size = target_ndim * 8
mem_size = managed_tensor_size + padding + 2 * shape_size
mem_ptr = PyMem_RawMalloc(mem_size)
assert mem_ptr, "Failed to allocate memory for DLManagedTensor"
# set managed tensor attributes
managed_tensor = DLManagedTensor.from_address(mem_ptr)
managed_tensor.dl_tensor.data = wp_array.ptr
managed_tensor.dl_tensor.device = dl_device
managed_tensor.dl_tensor.ndim = target_ndim
managed_tensor.dl_tensor.dtype = dtype_to_dlpack(target_dtype)
managed_tensor.dl_tensor.byte_offset = 0
# shape
shape_offset = managed_tensor_size + padding
shape_ptr = ctypes.cast(mem_ptr + shape_offset, ctypes.POINTER(ctypes.c_int64))
for i in range(target_ndim):
shape_ptr[i] = target_shape[i]
managed_tensor.dl_tensor.shape = shape_ptr
# strides, if not contiguous
if wp_array.is_contiguous:
managed_tensor.dl_tensor.strides = None
else:
stride_offset = shape_offset + shape_size
stride_ptr = ctypes.cast(mem_ptr + stride_offset, ctypes.POINTER(ctypes.c_int64))
dtype_size = warp.types.type_size_in_bytes(target_dtype)
for i in range(target_ndim):
stride_ptr[i] = target_strides[i] // dtype_size
managed_tensor.dl_tensor.strides = stride_ptr
# DLManagedTensor holds a reference to the source array
managed_tensor.manager_ctx = id(wp_array)
Py_IncRef(wp_array)
managed_tensor.deleter = _dlpack_tensor_deleter
capsule = PyCapsule_New(
ctypes.byref(managed_tensor),
_c_str_dltensor,
_dlpack_capsule_deleter,
)
return capsule
def dtype_is_compatible(dl_dtype, wp_dtype):
if dl_dtype.bits % 8 != 0:
raise RuntimeError("Data types with less than 8 bits are not supported")
if dl_dtype.type_code.value == DLDataTypeCode.kDLFloat:
if dl_dtype.bits == 16:
return wp_dtype == warp.float16
elif dl_dtype.bits == 32:
return wp_dtype == warp.float32
elif dl_dtype.bits == 64:
return wp_dtype == warp.float64
elif dl_dtype.type_code.value == DLDataTypeCode.kDLInt or dl_dtype.type_code.value == DLDataTypeCode.kDLUInt:
if dl_dtype.bits == 8:
return wp_dtype == warp.int8 or wp_dtype == warp.uint8
elif dl_dtype.bits == 16:
return wp_dtype == warp.int16 or wp_dtype == warp.uint16
elif dl_dtype.bits == 32:
return wp_dtype == warp.int32 or wp_dtype == warp.uint32
elif dl_dtype.bits == 64:
return wp_dtype == warp.int64 or wp_dtype == warp.uint64
elif dl_dtype.type_code.value == DLDataTypeCode.kDLBfloat:
raise RuntimeError("Bfloat data type is not supported")
elif dl_dtype.type_code.value == DLDataTypeCode.kDLComplex:
raise RuntimeError("Complex data types are not supported")
else:
raise RuntimeError(f"Unsupported DLPack dtype {(str(dl_dtype.type_code), dl_dtype.bits)}")
def _from_dlpack(capsule, dtype=None) -> warp.array:
"""Convert a DLPack capsule into a Warp array without copying.
Args:
capsule: A DLPack capsule wrapping an external array or tensor.
dtype: An optional Warp data type to interpret the source data.
Returns:
A new Warp array that uses the same underlying memory as the input capsule.
"""
assert PyCapsule_IsValid(capsule, _c_str_dltensor), "Invalid capsule"
mem_ptr = PyCapsule_GetPointer(capsule, _c_str_dltensor)
managed_tensor = DLManagedTensor.from_address(mem_ptr)
dlt = managed_tensor.dl_tensor
device = device_from_dlpack(dlt.device)
pinned = dlt.device.device_type.value == DLDeviceType.kDLCUDAHost
shape = tuple(dlt.shape[dim] for dim in range(dlt.ndim))
# strides, if not contiguous
itemsize = dlt.dtype.bits // 8
if dlt.strides:
strides = tuple(dlt.strides[dim] * itemsize for dim in range(dlt.ndim))
else:
strides = None
# handle multi-lane dtypes as another dimension
if dlt.dtype.lanes > 1:
shape = (*shape, dlt.dtype.lanes)
if strides is not None:
strides = (*strides, itemsize)
if dtype is None:
# automatically detect dtype
dtype = dtype_from_dlpack(dlt.dtype)
elif hasattr(dtype, "_wp_scalar_type_"):
# handle vector/matrix types
if not dtype_is_compatible(dlt.dtype, dtype._wp_scalar_type_):
raise RuntimeError(f"Incompatible data types: {dlt.dtype} and {dtype}")
dtype_shape = dtype._shape_
dtype_dims = len(dtype._shape_)
if dtype_dims > len(shape) or dtype_shape != shape[-dtype_dims:]:
raise RuntimeError(
f"Could not convert DLPack tensor with shape {shape} to Warp array with dtype={dtype}, ensure that source inner shape is {dtype_shape}"
)
if strides is not None:
# ensure the inner strides are contiguous
stride = itemsize
for i in range(dtype_dims):
if strides[-i - 1] != stride:
raise RuntimeError(
f"Could not convert DLPack tensor with shape {shape} to Warp array with dtype={dtype}, because the source inner strides are not contiguous"
)
stride *= dtype_shape[-i - 1]
strides = tuple(strides[:-dtype_dims]) or (itemsize,)
shape = tuple(shape[:-dtype_dims]) or (1,)
elif not dtype_is_compatible(dlt.dtype, dtype):
# incompatible dtype requested
raise RuntimeError(f"Incompatible data types: {dlt.dtype} and {dtype}")
a = warp.types.array(
ptr=dlt.data, dtype=dtype, shape=shape, strides=strides, copy=False, device=device, pinned=pinned
)
# take ownership of the DLManagedTensor
a._dlpack_tensor_holder = _DLPackTensorHolder(mem_ptr)
# rename the capsule so that it no longer owns the DLManagedTensor
PyCapsule_SetName(capsule, _c_str_used_dltensor)
return a
def from_dlpack(source, dtype=None) -> warp.array:
"""Convert a source array or DLPack capsule into a Warp array without copying.
Args:
source: A DLPack-compatible array or PyCapsule
dtype: An optional Warp data type to interpret the source data.
Returns:
A new Warp array that uses the same underlying memory as the input
pycapsule.
"""
# See https://data-apis.org/array-api/2022.12/API_specification/generated/array_api.array.__dlpack__.html
if hasattr(source, "__dlpack__"):
device_type, device_id = source.__dlpack_device__()
# Check if the source lives on a CUDA device
if device_type in (DLDeviceType.kDLCUDA, DLDeviceType.kDLCUDAManaged):
# Assume that the caller will use the array on its device's current stream.
# Note that we pass 1 for the null stream, per DLPack spec.
cuda_stream = warp.get_cuda_device(device_id).stream.cuda_stream or 1
elif device_type == DLDeviceType.kDLCPU:
# No stream sync for CPU arrays.
cuda_stream = None
elif device_type == DLDeviceType.kDLCUDAHost:
# For pinned memory, we sync with the current CUDA device's stream.
# Note that we pass 1 for the null stream, per DLPack spec.
cuda_stream = warp.get_cuda_device().stream.cuda_stream or 1
else:
raise TypeError("Unsupported source device")
capsule = source.__dlpack__(stream=cuda_stream)
else:
# legacy behaviour, assume source is a capsule
capsule = source
return _from_dlpack(capsule, dtype=dtype)
| 16,568 | Python | 36.401806 | 163 | 0.67226 |
NVIDIA/warp/warp/builtins.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 builtins
from typing import Any, Callable, Tuple
from warp.codegen import Reference
from warp.types import *
from .context import add_builtin
def sametypes(arg_types):
return all(types_equal(arg_types[0], t) for t in arg_types[1:])
def sametype_value_func(default):
def fn(arg_types, kwds, _):
if arg_types is None:
return default
if not sametypes(arg_types):
raise RuntimeError(f"Input types must be the same, found: {[type_repr(t) for t in arg_types]}")
return arg_types[0]
return fn
# ---------------------------------
# Scalar Math
add_builtin(
"min",
input_types={"x": Scalar, "y": Scalar},
value_func=sametype_value_func(Scalar),
doc="Return the minimum of two scalars.",
group="Scalar Math",
)
add_builtin(
"max",
input_types={"x": Scalar, "y": Scalar},
value_func=sametype_value_func(Scalar),
doc="Return the maximum of two scalars.",
group="Scalar Math",
)
add_builtin(
"clamp",
input_types={"x": Scalar, "a": Scalar, "b": Scalar},
value_func=sametype_value_func(Scalar),
doc="Clamp the value of ``x`` to the range [a, b].",
group="Scalar Math",
)
add_builtin(
"abs",
input_types={"x": Scalar},
value_func=sametype_value_func(Scalar),
doc="Return the absolute value of ``x``.",
group="Scalar Math",
)
add_builtin(
"sign",
input_types={"x": Scalar},
value_func=sametype_value_func(Scalar),
doc="Return -1 if ``x`` < 0, return 1 otherwise.",
group="Scalar Math",
)
add_builtin(
"step",
input_types={"x": Scalar},
value_func=sametype_value_func(Scalar),
doc="Return 1.0 if ``x`` < 0.0, return 0.0 otherwise.",
group="Scalar Math",
)
add_builtin(
"nonzero",
input_types={"x": Scalar},
value_func=sametype_value_func(Scalar),
doc="Return 1.0 if ``x`` is not equal to zero, return 0.0 otherwise.",
group="Scalar Math",
)
add_builtin(
"sin",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the sine of ``x`` in radians.",
group="Scalar Math",
)
add_builtin(
"cos",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the cosine of ``x`` in radians.",
group="Scalar Math",
)
add_builtin(
"acos",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return arccos of ``x`` in radians. Inputs are automatically clamped to [-1.0, 1.0].",
group="Scalar Math",
)
add_builtin(
"asin",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return arcsin of ``x`` in radians. Inputs are automatically clamped to [-1.0, 1.0].",
group="Scalar Math",
)
add_builtin(
"sqrt",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the square root of ``x``, where ``x`` is positive.",
group="Scalar Math",
require_original_output_arg=True,
)
add_builtin(
"cbrt",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the cube root of ``x``.",
group="Scalar Math",
require_original_output_arg=True,
)
add_builtin(
"tan",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the tangent of ``x`` in radians.",
group="Scalar Math",
)
add_builtin(
"atan",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the arctangent of ``x`` in radians.",
group="Scalar Math",
)
add_builtin(
"atan2",
input_types={"y": Float, "x": Float},
value_func=sametype_value_func(Float),
doc="Return the 2-argument arctangent, atan2, of the point ``(x, y)`` in radians.",
group="Scalar Math",
)
add_builtin(
"sinh",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the sinh of ``x``.",
group="Scalar Math",
)
add_builtin(
"cosh",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the cosh of ``x``.",
group="Scalar Math",
)
add_builtin(
"tanh",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the tanh of ``x``.",
group="Scalar Math",
require_original_output_arg=True,
)
add_builtin(
"degrees",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Convert ``x`` from radians into degrees.",
group="Scalar Math",
)
add_builtin(
"radians",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Convert ``x`` from degrees into radians.",
group="Scalar Math",
)
add_builtin(
"log",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the natural logarithm (base-e) of ``x``, where ``x`` is positive.",
group="Scalar Math",
)
add_builtin(
"log2",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the binary logarithm (base-2) of ``x``, where ``x`` is positive.",
group="Scalar Math",
)
add_builtin(
"log10",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the common logarithm (base-10) of ``x``, where ``x`` is positive.",
group="Scalar Math",
)
add_builtin(
"exp",
input_types={"x": Float},
value_func=sametype_value_func(Float),
doc="Return the value of the exponential function :math:`e^x`.",
group="Scalar Math",
require_original_output_arg=True,
)
add_builtin(
"pow",
input_types={"x": Float, "y": Float},
value_func=sametype_value_func(Float),
doc="Return the result of ``x`` raised to power of ``y``.",
group="Scalar Math",
require_original_output_arg=True,
)
add_builtin(
"round",
input_types={"x": Float},
value_func=sametype_value_func(Float),
group="Scalar Math",
doc="""Return the nearest integer value to ``x``, rounding halfway cases away from zero.
This is the most intuitive form of rounding in the colloquial sense, but can be slower than other options like :func:`warp.rint()`.
Differs from :func:`numpy.round()`, which behaves the same way as :func:`numpy.rint()`.""",
)
add_builtin(
"rint",
input_types={"x": Float},
value_func=sametype_value_func(Float),
group="Scalar Math",
doc="""Return the nearest integer value to ``x``, rounding halfway cases to nearest even integer.
It is generally faster than :func:`warp.round()`. Equivalent to :func:`numpy.rint()`.""",
)
add_builtin(
"trunc",
input_types={"x": Float},
value_func=sametype_value_func(Float),
group="Scalar Math",
doc="""Return the nearest integer that is closer to zero than ``x``.
In other words, it discards the fractional part of ``x``.
It is similar to casting ``float(int(x))``, but preserves the negative sign when x is in the range [-0.0, -1.0).
Equivalent to :func:`numpy.trunc()` and :func:`numpy.fix()`.""",
)
add_builtin(
"floor",
input_types={"x": Float},
value_func=sametype_value_func(Float),
group="Scalar Math",
doc="""Return the largest integer that is less than or equal to ``x``.""",
)
add_builtin(
"ceil",
input_types={"x": Float},
value_func=sametype_value_func(Float),
group="Scalar Math",
doc="""Return the smallest integer that is greater than or equal to ``x``.""",
)
add_builtin(
"frac",
input_types={"x": Float},
value_func=sametype_value_func(Float),
group="Scalar Math",
doc="""Retrieve the fractional part of x.
In other words, it discards the integer part of x and is equivalent to ``x - trunc(x)``.""",
)
add_builtin(
"isfinite",
input_types={"x": Scalar},
value_type=builtins.bool,
group="Scalar Math",
doc="""Return ``True`` if x is a finite number, otherwise return ``False``.""",
)
add_builtin(
"isfinite",
input_types={"x": vector(length=Any, dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if all elements of the vector ``x`` are finite, otherwise return ``False``.",
)
add_builtin(
"isfinite",
input_types={"x": quaternion(dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if all elements of the quaternion ``x`` are finite, otherwise return ``False``.",
)
add_builtin(
"isfinite",
input_types={"m": matrix(shape=(Any, Any), dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if all elements of the matrix ``m`` are finite, otherwise return ``False``.",
)
add_builtin(
"isnan",
input_types={"x": Scalar},
value_type=builtins.bool,
doc="Return ``True`` if ``x`` is NaN, otherwise return ``False``.",
group="Scalar Math",
)
add_builtin(
"isnan",
input_types={"x": vector(length=Any, dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if any element of the vector ``x`` is NaN, otherwise return ``False``.",
)
add_builtin(
"isnan",
input_types={"x": quaternion(dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if any element of the quaternion ``x`` is NaN, otherwise return ``False``.",
)
add_builtin(
"isnan",
input_types={"m": matrix(shape=(Any, Any), dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if any element of the matrix ``m`` is NaN, otherwise return ``False``.",
)
add_builtin(
"isinf",
input_types={"x": Scalar},
value_type=builtins.bool,
group="Scalar Math",
doc="""Return ``True`` if x is positive or negative infinity, otherwise return ``False``.""",
)
add_builtin(
"isinf",
input_types={"x": vector(length=Any, dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if any element of the vector ``x`` is positive or negative infinity, otherwise return ``False``.",
)
add_builtin(
"isinf",
input_types={"x": quaternion(dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if any element of the quaternion ``x`` is positive or negative infinity, otherwise return ``False``.",
)
add_builtin(
"isinf",
input_types={"m": matrix(shape=(Any, Any), dtype=Scalar)},
value_type=builtins.bool,
group="Vector Math",
doc="Return ``True`` if any element of the matrix ``m`` is positive or negative infinity, otherwise return ``False``.",
)
def infer_scalar_type(arg_types):
if arg_types is None:
return Scalar
def iterate_scalar_types(arg_types):
for t in arg_types:
if hasattr(t, "_wp_scalar_type_"):
yield t._wp_scalar_type_
elif t in scalar_and_bool_types:
yield t
scalarTypes = set(iterate_scalar_types(arg_types))
if len(scalarTypes) > 1:
raise RuntimeError(
f"Couldn't figure out return type as arguments have multiple precisions: {list(scalarTypes)}"
)
return list(scalarTypes)[0]
def sametype_scalar_value_func(arg_types, kwds, _):
if arg_types is None:
return Scalar
if not sametypes(arg_types):
raise RuntimeError(f"Input types must be exactly the same, {list(arg_types)}")
return infer_scalar_type(arg_types)
# ---------------------------------
# Vector Math
add_builtin(
"dot",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_scalar_value_func,
group="Vector Math",
doc="Compute the dot product between two vectors.",
)
add_builtin(
"ddot",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=sametype_scalar_value_func,
group="Vector Math",
doc="Compute the double dot product between two matrices.",
)
add_builtin(
"min",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
doc="Return the element-wise minimum of two vectors.",
group="Vector Math",
)
add_builtin(
"max",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
doc="Return the element-wise maximum of two vectors.",
group="Vector Math",
)
add_builtin(
"min",
input_types={"v": vector(length=Any, dtype=Scalar)},
value_func=sametype_scalar_value_func,
doc="Return the minimum element of a vector ``v``.",
group="Vector Math",
)
add_builtin(
"max",
input_types={"v": vector(length=Any, dtype=Scalar)},
value_func=sametype_scalar_value_func,
doc="Return the maximum element of a vector ``v``.",
group="Vector Math",
)
add_builtin(
"argmin",
input_types={"v": vector(length=Any, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: warp.uint32,
doc="Return the index of the minimum element of a vector ``v``.",
group="Vector Math",
missing_grad=True,
)
add_builtin(
"argmax",
input_types={"v": vector(length=Any, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: warp.uint32,
doc="Return the index of the maximum element of a vector ``v``.",
group="Vector Math",
missing_grad=True,
)
def value_func_outer(arg_types, kwds, _):
if arg_types is None:
return matrix(shape=(Any, Any), dtype=Scalar)
scalarType = infer_scalar_type(arg_types)
vectorLengths = [t._length_ for t in arg_types]
return matrix(shape=(vectorLengths), dtype=scalarType)
add_builtin(
"outer",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
value_func=value_func_outer,
group="Vector Math",
doc="Compute the outer product ``x*y^T`` for two vectors.",
)
add_builtin(
"cross",
input_types={"x": vector(length=3, dtype=Scalar), "y": vector(length=3, dtype=Scalar)},
value_func=sametype_value_func(vector(length=3, dtype=Scalar)),
group="Vector Math",
doc="Compute the cross product of two 3D vectors.",
)
add_builtin(
"skew",
input_types={"x": vector(length=3, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: matrix(shape=(3, 3), dtype=arg_types[0]._wp_scalar_type_),
group="Vector Math",
doc="Compute the skew-symmetric 3x3 matrix for a 3D vector ``x``.",
)
add_builtin(
"length",
input_types={"x": vector(length=Any, dtype=Float)},
value_func=sametype_scalar_value_func,
group="Vector Math",
doc="Compute the length of a floating-point vector ``x``.",
require_original_output_arg=True,
)
add_builtin(
"length",
input_types={"x": quaternion(dtype=Float)},
value_func=sametype_scalar_value_func,
group="Vector Math",
doc="Compute the length of a quaternion ``x``.",
require_original_output_arg=True,
)
add_builtin(
"length_sq",
input_types={"x": vector(length=Any, dtype=Scalar)},
value_func=sametype_scalar_value_func,
group="Vector Math",
doc="Compute the squared length of a vector ``x``.",
)
add_builtin(
"length_sq",
input_types={"x": quaternion(dtype=Scalar)},
value_func=sametype_scalar_value_func,
group="Vector Math",
doc="Compute the squared length of a quaternion ``x``.",
)
add_builtin(
"normalize",
input_types={"x": vector(length=Any, dtype=Float)},
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
group="Vector Math",
doc="Compute the normalized value of ``x``. If ``length(x)`` is 0 then the zero vector is returned.",
require_original_output_arg=True,
)
add_builtin(
"normalize",
input_types={"x": quaternion(dtype=Float)},
value_func=sametype_value_func(quaternion(dtype=Scalar)),
group="Vector Math",
doc="Compute the normalized value of ``x``. If ``length(x)`` is 0, then the zero quaternion is returned.",
)
add_builtin(
"transpose",
input_types={"m": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=lambda arg_types, kwds, _: matrix(
shape=(arg_types[0]._shape_[1], arg_types[0]._shape_[0]), dtype=arg_types[0]._wp_scalar_type_
),
group="Vector Math",
doc="Return the transpose of the matrix ``m``.",
)
def value_func_mat_inv(arg_types, kwds, _):
if arg_types is None:
return matrix(shape=(Any, Any), dtype=Float)
return arg_types[0]
add_builtin(
"inverse",
input_types={"m": matrix(shape=(2, 2), dtype=Float)},
value_func=value_func_mat_inv,
group="Vector Math",
doc="Return the inverse of a 2x2 matrix ``m``.",
require_original_output_arg=True,
)
add_builtin(
"inverse",
input_types={"m": matrix(shape=(3, 3), dtype=Float)},
value_func=value_func_mat_inv,
group="Vector Math",
doc="Return the inverse of a 3x3 matrix ``m``.",
require_original_output_arg=True,
)
add_builtin(
"inverse",
input_types={"m": matrix(shape=(4, 4), dtype=Float)},
value_func=value_func_mat_inv,
group="Vector Math",
doc="Return the inverse of a 4x4 matrix ``m``.",
require_original_output_arg=True,
)
def value_func_mat_det(arg_types, kwds, _):
if arg_types is None:
return Scalar
return arg_types[0]._wp_scalar_type_
add_builtin(
"determinant",
input_types={"m": matrix(shape=(2, 2), dtype=Float)},
value_func=value_func_mat_det,
group="Vector Math",
doc="Return the determinant of a 2x2 matrix ``m``.",
)
add_builtin(
"determinant",
input_types={"m": matrix(shape=(3, 3), dtype=Float)},
value_func=value_func_mat_det,
group="Vector Math",
doc="Return the determinant of a 3x3 matrix ``m``.",
)
add_builtin(
"determinant",
input_types={"m": matrix(shape=(4, 4), dtype=Float)},
value_func=value_func_mat_det,
group="Vector Math",
doc="Return the determinant of a 4x4 matrix ``m``.",
)
def value_func_mat_trace(arg_types, kwds, _):
if arg_types is None:
return Scalar
if arg_types[0]._shape_[0] != arg_types[0]._shape_[1]:
raise RuntimeError(f"Matrix shape is {arg_types[0]._shape_}. Cannot find the trace of non square matrices")
return arg_types[0]._wp_scalar_type_
add_builtin(
"trace",
input_types={"m": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=value_func_mat_trace,
group="Vector Math",
doc="Return the trace of the matrix ``m``.",
)
def value_func_diag(arg_types, kwds, _):
if arg_types is None:
return matrix(shape=(Any, Any), dtype=Scalar)
else:
return matrix(shape=(arg_types[0]._length_, arg_types[0]._length_), dtype=arg_types[0]._wp_scalar_type_)
add_builtin(
"diag",
input_types={"d": vector(length=Any, dtype=Scalar)},
value_func=value_func_diag,
group="Vector Math",
doc="Returns a matrix with the components of the vector ``d`` on the diagonal.",
)
def value_func_get_diag(arg_types, kwds, _):
if arg_types is None:
return vector(length=(Any), dtype=Scalar)
else:
if arg_types[0]._shape_[0] != arg_types[0]._shape_[1]:
raise RuntimeError(
f"Matrix shape is {arg_types[0]._shape_}; get_diag is only available for square matrices."
)
return vector(length=arg_types[0]._shape_[0], dtype=arg_types[0]._wp_scalar_type_)
add_builtin(
"get_diag",
input_types={"m": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=value_func_get_diag,
group="Vector Math",
doc="Returns a vector containing the diagonal elements of the square matrix ``m``.",
)
add_builtin(
"cw_mul",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
group="Vector Math",
doc="Component-wise multiplication of two vectors.",
)
add_builtin(
"cw_div",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
group="Vector Math",
doc="Component-wise division of two vectors.",
require_original_output_arg=True,
)
add_builtin(
"cw_mul",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
group="Vector Math",
doc="Component-wise multiplication of two matrices.",
)
add_builtin(
"cw_div",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
group="Vector Math",
doc="Component-wise division of two matrices.",
require_original_output_arg=True,
)
# scalar type constructors between all storage / compute types
scalar_types_all = [*scalar_types, bool, int, float]
for t in scalar_types_all:
for u in scalar_types_all:
add_builtin(
t.__name__,
input_types={"u": u},
value_type=t,
doc="",
hidden=True,
group="Scalar Math",
export=False,
namespace="wp::" if t is not bool else "",
)
def vector_constructor_func(arg_types, kwds, templates):
if arg_types is None:
return vector(length=Any, dtype=Scalar)
if templates is None or len(templates) == 0:
# handle construction of anonymous (undeclared) vector types
if "length" in kwds:
if len(arg_types) == 0:
if "dtype" not in kwds:
raise RuntimeError(
"vec() must have dtype as a keyword argument if it has no positional arguments, e.g.: wp.vector(length=5, dtype=wp.float32)"
)
# zero initialization e.g.: wp.vector(length=5, dtype=wp.float32)
veclen = kwds["length"]
vectype = kwds["dtype"]
elif len(arg_types) == 1:
# value initialization e.g.: wp.vec(1.0, length=5)
veclen = kwds["length"]
vectype = arg_types[0]
if type_is_vector(vectype):
# constructor from another vector
if vectype._length_ != veclen:
raise RuntimeError(
f"Incompatible vector lengths for casting copy constructor, {veclen} vs {vectype._length_}"
)
vectype = vectype._wp_scalar_type_
else:
raise RuntimeError(
"vec() must have one scalar argument or the dtype keyword argument if the length keyword argument is specified, e.g.: wp.vec(1.0, length=5)"
)
else:
if len(arg_types) == 0:
raise RuntimeError(
"vec() must have at least one numeric argument, if it's length, dtype is not specified"
)
if "dtype" in kwds:
# casting constructor
if len(arg_types) == 1 and types_equal(
arg_types[0], vector(length=Any, dtype=Scalar), match_generic=True
):
veclen = arg_types[0]._length_
vectype = kwds["dtype"]
templates.append(veclen)
templates.append(vectype)
return vector(length=veclen, dtype=vectype)
raise RuntimeError(
"vec() should not have dtype specified if numeric arguments are given, the dtype will be inferred from the argument types"
)
# component wise construction of an anonymous vector, e.g. wp.vec(wp.float16(1.0), wp.float16(2.0), ....)
# we infer the length and data type from the number and type of the arg values
veclen = len(arg_types)
vectype = arg_types[0]
if len(arg_types) == 1 and type_is_vector(vectype):
# constructor from another vector
veclen = vectype._length_
vectype = vectype._wp_scalar_type_
elif not all(vectype == t for t in arg_types):
raise RuntimeError(
f"All numeric arguments to vec() constructor should have the same type, expected {veclen} arg_types of type {vectype}, received { ','.join([str(t) for t in arg_types]) }"
)
# update the templates list, so we can generate vec<len, type>() correctly in codegen
templates.append(veclen)
templates.append(vectype)
else:
# construction of a predeclared type, e.g.: vec5d
veclen, vectype = templates
if len(arg_types) == 1 and type_is_vector(arg_types[0]):
# constructor from another vector
if arg_types[0]._length_ != veclen:
raise RuntimeError(
f"Incompatible matrix sizes for casting copy constructor, {veclen} vs {arg_types[0]._length_}"
)
elif not all(vectype == t for t in arg_types):
raise RuntimeError(
f"All numeric arguments to vec() constructor should have the same type, expected {veclen} arg_types of type {vectype}, received { ','.join([str(t) for t in arg_types]) }"
)
retvalue = vector(length=veclen, dtype=vectype)
return retvalue
add_builtin(
"vector",
input_types={"*arg_types": Scalar, "length": int, "dtype": Scalar},
variadic=True,
initializer_list_func=lambda arg_types, _: len(arg_types) > 4,
value_func=vector_constructor_func,
native_func="vec_t",
doc="Construct a vector of with given length and dtype.",
group="Vector Math",
export=False,
)
def matrix_constructor_func(arg_types, kwds, templates):
if arg_types is None:
return matrix(shape=(Any, Any), dtype=Scalar)
if len(templates) == 0:
# anonymous construction
if "shape" not in kwds:
raise RuntimeError("shape keyword must be specified when calling matrix() function")
if len(arg_types) == 0:
if "dtype" not in kwds:
raise RuntimeError("matrix() must have dtype as a keyword argument if it has no positional arguments")
# zero initialization, e.g.: m = matrix(shape=(3,2), dtype=wp.float16)
shape = kwds["shape"]
dtype = kwds["dtype"]
else:
# value initialization, e.g.: m = matrix(1.0, shape=(3,2))
shape = kwds["shape"]
dtype = arg_types[0]
if len(arg_types) == 1 and type_is_matrix(dtype):
# constructor from another matrix
if arg_types[0]._shape_ != shape:
raise RuntimeError(
f"Incompatible matrix sizes for casting copy constructor, {shape} vs {arg_types[0]._shape_}"
)
dtype = dtype._wp_scalar_type_
elif len(arg_types) > 1 and len(arg_types) != shape[0] * shape[1]:
raise RuntimeError(
"Wrong number of arguments for matrix() function, must initialize with either a scalar value, or m*n values"
)
templates.append(shape[0])
templates.append(shape[1])
templates.append(dtype)
else:
# predeclared type, e.g.: mat32d
shape = (templates[0], templates[1])
dtype = templates[2]
if len(arg_types) > 0:
if len(arg_types) == 1 and type_is_matrix(arg_types[0]):
# constructor from another matrix with same dimension but possibly different type
if arg_types[0]._shape_ != shape:
raise RuntimeError(
f"Incompatible matrix sizes for casting copy constructor, {shape} vs {arg_types[0]._shape_}"
)
else:
# check scalar arg type matches declared type
if infer_scalar_type(arg_types) != dtype:
raise RuntimeError("Wrong scalar type for mat {} constructor".format(",".join(map(str, templates))))
# check vector arg type matches declared type
if all(type_is_vector(a) for a in arg_types):
cols = len(arg_types)
if shape[1] != cols:
raise RuntimeError(
"Wrong number of vectors when attempting to construct a matrix with column vectors"
)
if not all(a._length_ == shape[0] for a in arg_types):
raise RuntimeError(
"Wrong vector row count when attempting to construct a matrix with column vectors"
)
else:
# check that we either got 1 arg (scalar construction), or enough values for whole matrix
size = shape[0] * shape[1]
if len(arg_types) > 1 and len(arg_types) != size:
raise RuntimeError(
"Wrong number of scalars when attempting to construct a matrix from a list of components"
)
return matrix(shape=shape, dtype=dtype)
# only use initializer list if matrix size < 5x5, or for scalar construction
def matrix_initlist_func(arg_types, templates):
m, n, dtype = templates
return not (
len(arg_types) == 0
or len(arg_types) == 1 # zero construction
or (m == n and n < 5) # scalar construction # value construction for small matrices
)
add_builtin(
"matrix",
input_types={"*arg_types": Scalar, "shape": Tuple[int, int], "dtype": Scalar},
variadic=True,
initializer_list_func=matrix_initlist_func,
value_func=matrix_constructor_func,
native_func="mat_t",
doc="Construct a matrix. If the positional ``arg_types`` are not given, then matrix will be zero-initialized.",
group="Vector Math",
export=False,
)
# identity:
def matrix_identity_value_func(arg_types, kwds, templates):
if arg_types is None:
return matrix(shape=(Any, Any), dtype=Scalar)
if len(arg_types):
raise RuntimeError("identity() function does not accept positional arguments")
if "n" not in kwds:
raise RuntimeError("'n' keyword argument must be specified when calling identity() function")
if "dtype" not in kwds:
raise RuntimeError("'dtype' keyword argument must be specified when calling identity() function")
n, dtype = [kwds["n"], kwds["dtype"]]
if n is None:
raise RuntimeError("'n' must be a constant when calling identity() function")
templates.append(n)
templates.append(dtype)
return matrix(shape=(n, n), dtype=dtype)
add_builtin(
"identity",
input_types={"n": int, "dtype": Scalar},
value_func=matrix_identity_value_func,
variadic=True,
doc="Create an identity matrix with shape=(n,n) with the type given by ``dtype``.",
group="Vector Math",
export=False,
)
def matrix_transform_value_func(arg_types, kwds, templates):
if templates is None:
return matrix(shape=(4, 4), dtype=Float)
if len(templates) == 0:
raise RuntimeError("Cannot use a generic type name in a kernel")
m, n, dtype = templates
if (m, n) != (4, 4):
raise RuntimeError("Can only construct 4x4 matrices with position, rotation and scale")
if infer_scalar_type(arg_types) != dtype:
raise RuntimeError("Wrong scalar type for mat<{}> constructor".format(",".join(map(str, templates))))
return matrix(shape=(4, 4), dtype=dtype)
add_builtin(
"matrix",
input_types={
"pos": vector(length=3, dtype=Float),
"rot": quaternion(dtype=Float),
"scale": vector(length=3, dtype=Float),
},
value_func=matrix_transform_value_func,
native_func="mat_t",
doc="""Construct a 4x4 transformation matrix that applies the transformations as
Translation(pos)*Rotation(rot)*Scale(scale) when applied to column vectors, i.e.: y = (TRS)*x""",
group="Vector Math",
export=False,
)
# not making these functions available outside kernels (export=False) as they
# return data via references, which we don't currently support:
add_builtin(
"svd3",
input_types={
"A": matrix(shape=(3, 3), dtype=Float),
"U": matrix(shape=(3, 3), dtype=Float),
"sigma": vector(length=3, dtype=Float),
"V": matrix(shape=(3, 3), dtype=Scalar),
},
value_type=None,
group="Vector Math",
export=False,
doc="""Compute the SVD of a 3x3 matrix ``A``. The singular values are returned in ``sigma``,
while the left and right basis vectors are returned in ``U`` and ``V``.""",
)
add_builtin(
"qr3",
input_types={
"A": matrix(shape=(3, 3), dtype=Float),
"Q": matrix(shape=(3, 3), dtype=Float),
"R": matrix(shape=(3, 3), dtype=Float),
},
value_type=None,
group="Vector Math",
export=False,
doc="""Compute the QR decomposition of a 3x3 matrix ``A``. The orthogonal matrix is returned in ``Q``,
while the upper triangular matrix is returned in ``R``.""",
)
add_builtin(
"eig3",
input_types={
"A": matrix(shape=(3, 3), dtype=Float),
"Q": matrix(shape=(3, 3), dtype=Float),
"d": vector(length=3, dtype=Float),
},
value_type=None,
group="Vector Math",
export=False,
doc="""Compute the eigendecomposition of a 3x3 matrix ``A``. The eigenvectors are returned as the columns of ``Q``,
while the corresponding eigenvalues are returned in ``d``.""",
)
# ---------------------------------
# Quaternion Math
def quaternion_value_func(arg_types, kwds, templates):
if arg_types is None:
return quaternion(dtype=Float)
if len(templates) == 0:
if "dtype" in kwds:
# casting constructor
dtype = kwds["dtype"]
else:
# if constructing anonymous quat type then infer output type from arguments
dtype = infer_scalar_type(arg_types)
templates.append(dtype)
else:
# if constructing predeclared type then check arg_types match expectation
if len(arg_types) > 0 and infer_scalar_type(arg_types) != templates[0]:
raise RuntimeError("Wrong scalar type for quat {} constructor".format(",".join(map(str, templates))))
return quaternion(dtype=templates[0])
def quat_cast_value_func(arg_types, kwds, templates):
if arg_types is None:
raise RuntimeError("Missing quaternion argument.")
if "dtype" not in kwds:
raise RuntimeError("Missing 'dtype' kwd.")
dtype = kwds["dtype"]
templates.append(dtype)
return quaternion(dtype=dtype)
add_builtin(
"quaternion",
input_types={},
value_func=quaternion_value_func,
native_func="quat_t",
group="Quaternion Math",
doc="""Construct a zero-initialized quaternion. Quaternions are laid out as
[ix, iy, iz, r], where ix, iy, iz are the imaginary part, and r the real part.""",
export=False,
)
add_builtin(
"quaternion",
input_types={"x": Float, "y": Float, "z": Float, "w": Float},
value_func=quaternion_value_func,
native_func="quat_t",
group="Quaternion Math",
doc="Create a quaternion using the supplied components (type inferred from component type).",
export=False,
)
add_builtin(
"quaternion",
input_types={"i": vector(length=3, dtype=Float), "r": Float},
value_func=quaternion_value_func,
native_func="quat_t",
group="Quaternion Math",
doc="Create a quaternion using the supplied vector/scalar (type inferred from scalar type).",
export=False,
)
add_builtin(
"quaternion",
input_types={"q": quaternion(dtype=Float)},
value_func=quat_cast_value_func,
native_func="quat_t",
group="Quaternion Math",
doc="Construct a quaternion of type dtype from another quaternion of a different dtype.",
export=False,
)
def quat_identity_value_func(arg_types, kwds, templates):
# if arg_types is None then we are in 'export' mode
if arg_types is None:
return quatf
if "dtype" not in kwds:
# defaulting to float32 to preserve current behavior:
dtype = float32
else:
dtype = kwds["dtype"]
templates.append(dtype)
return quaternion(dtype=dtype)
add_builtin(
"quat_identity",
input_types={},
value_func=quat_identity_value_func,
group="Quaternion Math",
doc="Construct an identity quaternion with zero imaginary part and real part of 1.0",
export=True,
)
add_builtin(
"quat_from_axis_angle",
input_types={"axis": vector(length=3, dtype=Float), "angle": Float},
value_func=lambda arg_types, kwds, _: quaternion(dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Construct a quaternion representing a rotation of angle radians around the given axis.",
)
add_builtin(
"quat_to_axis_angle",
input_types={"q": quaternion(dtype=Float), "axis": vector(length=3, dtype=Float), "angle": Float},
value_type=None,
group="Quaternion Math",
doc="Extract the rotation axis and angle radians a quaternion represents.",
)
add_builtin(
"quat_from_matrix",
input_types={"m": matrix(shape=(3, 3), dtype=Float)},
value_func=lambda arg_types, kwds, _: quaternion(dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Construct a quaternion from a 3x3 matrix.",
)
add_builtin(
"quat_rpy",
input_types={"roll": Float, "pitch": Float, "yaw": Float},
value_func=lambda arg_types, kwds, _: quaternion(dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Construct a quaternion representing a combined roll (z), pitch (x), yaw rotations (y) in radians.",
)
add_builtin(
"quat_inverse",
input_types={"q": quaternion(dtype=Float)},
value_func=lambda arg_types, kwds, _: quaternion(dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Compute quaternion conjugate.",
)
add_builtin(
"quat_rotate",
input_types={"q": quaternion(dtype=Float), "p": vector(length=3, dtype=Float)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Rotate a vector by a quaternion.",
)
add_builtin(
"quat_rotate_inv",
input_types={"q": quaternion(dtype=Float), "p": vector(length=3, dtype=Float)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Rotate a vector by the inverse of a quaternion.",
)
add_builtin(
"quat_slerp",
input_types={"q0": quaternion(dtype=Float), "q1": quaternion(dtype=Float), "t": Float},
value_func=lambda arg_types, kwds, _: quaternion(dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Linearly interpolate between two quaternions.",
require_original_output_arg=True,
)
add_builtin(
"quat_to_matrix",
input_types={"q": quaternion(dtype=Float)},
value_func=lambda arg_types, kwds, _: matrix(shape=(3, 3), dtype=infer_scalar_type(arg_types)),
group="Quaternion Math",
doc="Convert a quaternion to a 3x3 rotation matrix.",
)
add_builtin(
"dot",
input_types={"x": quaternion(dtype=Float), "y": quaternion(dtype=Float)},
value_func=sametype_scalar_value_func,
group="Quaternion Math",
doc="Compute the dot product between two quaternions.",
)
# ---------------------------------
# Transformations
def transform_constructor_value_func(arg_types, kwds, templates):
if templates is None:
return transformation(dtype=Scalar)
if len(templates) == 0:
# if constructing anonymous transform type then infer output type from arguments
dtype = infer_scalar_type(arg_types)
templates.append(dtype)
else:
# if constructing predeclared type then check arg_types match expectation
if infer_scalar_type(arg_types) != templates[0]:
raise RuntimeError(
f"Wrong scalar type for transform constructor expected {templates[0]}, got {','.join([ str(t) for t in arg_types])}"
)
return transformation(dtype=templates[0])
add_builtin(
"transformation",
input_types={"p": vector(length=3, dtype=Float), "q": quaternion(dtype=Float)},
value_func=transform_constructor_value_func,
native_func="transform_t",
group="Transformations",
doc="Construct a rigid-body transformation with translation part ``p`` and rotation ``q``.",
export=False,
)
def transform_identity_value_func(arg_types, kwds, templates):
# if arg_types is None then we are in 'export' mode
if arg_types is None:
return transformf
if "dtype" not in kwds:
# defaulting to float32 to preserve current behavior:
dtype = float32
else:
dtype = kwds["dtype"]
templates.append(dtype)
return transformation(dtype=dtype)
add_builtin(
"transform_identity",
input_types={},
value_func=transform_identity_value_func,
group="Transformations",
doc="Construct an identity transform with zero translation and identity rotation.",
export=True,
)
add_builtin(
"transform_get_translation",
input_types={"t": transformation(dtype=Float)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Transformations",
doc="Return the translational part of a transform ``t``.",
)
add_builtin(
"transform_get_rotation",
input_types={"t": transformation(dtype=Float)},
value_func=lambda arg_types, kwds, _: quaternion(dtype=infer_scalar_type(arg_types)),
group="Transformations",
doc="Return the rotational part of a transform ``t``.",
)
add_builtin(
"transform_multiply",
input_types={"a": transformation(dtype=Float), "b": transformation(dtype=Float)},
value_func=lambda arg_types, kwds, _: transformation(dtype=infer_scalar_type(arg_types)),
group="Transformations",
doc="Multiply two rigid body transformations together.",
)
add_builtin(
"transform_point",
input_types={"t": transformation(dtype=Scalar), "p": vector(length=3, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Transformations",
doc="Apply the transform to a point ``p`` treating the homogeneous coordinate as w=1 (translation and rotation).",
)
add_builtin(
"transform_point",
input_types={"m": matrix(shape=(4, 4), dtype=Scalar), "p": vector(length=3, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Vector Math",
doc="""Apply the transform to a point ``p`` treating the homogeneous coordinate as w=1.
The transformation is applied treating ``p`` as a column vector, e.g.: ``y = M*p``.
Note this is in contrast to some libraries, notably USD, which applies transforms to row vectors, ``y^T = p^T*M^T``.
If the transform is coming from a library that uses row-vectors, then users should transpose the transformation
matrix before calling this method.""",
)
add_builtin(
"transform_vector",
input_types={"t": transformation(dtype=Scalar), "v": vector(length=3, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Transformations",
doc="Apply the transform to a vector ``v`` treating the homogeneous coordinate as w=0 (rotation only).",
)
add_builtin(
"transform_vector",
input_types={"m": matrix(shape=(4, 4), dtype=Scalar), "v": vector(length=3, dtype=Scalar)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=infer_scalar_type(arg_types)),
group="Vector Math",
doc="""Apply the transform to a vector ``v`` treating the homogeneous coordinate as w=0.
The transformation is applied treating ``v`` as a column vector, e.g.: ``y = M*v``
note this is in contrast to some libraries, notably USD, which applies transforms to row vectors, ``y^T = v^T*M^T``.
If the transform is coming from a library that uses row-vectors, then users should transpose the transformation
matrix before calling this method.""",
)
add_builtin(
"transform_inverse",
input_types={"t": transformation(dtype=Float)},
value_func=sametype_value_func(transformation(dtype=Float)),
group="Transformations",
doc="Compute the inverse of the transformation ``t``.",
)
# ---------------------------------
# Spatial Math
def spatial_vector_constructor_value_func(arg_types, kwds, templates):
if templates is None:
return spatial_vector(dtype=Float)
if len(templates) == 0:
raise RuntimeError("Cannot use a generic type name in a kernel")
vectype = templates[1]
if len(arg_types) and infer_scalar_type(arg_types) != vectype:
raise RuntimeError("Wrong scalar type for spatial_vector<{}> constructor".format(",".join(map(str, templates))))
return vector(length=6, dtype=vectype)
add_builtin(
"vector",
input_types={"w": vector(length=3, dtype=Float), "v": vector(length=3, dtype=Float)},
value_func=spatial_vector_constructor_value_func,
native_func="vec_t",
group="Spatial Math",
doc="Construct a 6D screw vector from two 3D vectors.",
export=False,
)
add_builtin(
"spatial_adjoint",
input_types={"r": matrix(shape=(3, 3), dtype=Float), "s": matrix(shape=(3, 3), dtype=Float)},
value_func=lambda arg_types, kwds, _: matrix(shape=(6, 6), dtype=infer_scalar_type(arg_types)),
group="Spatial Math",
doc="Construct a 6x6 spatial inertial matrix from two 3x3 diagonal blocks.",
export=False,
)
add_builtin(
"spatial_dot",
input_types={"a": vector(length=6, dtype=Float), "b": vector(length=6, dtype=Float)},
value_func=sametype_scalar_value_func,
group="Spatial Math",
doc="Compute the dot product of two 6D screw vectors.",
)
add_builtin(
"spatial_cross",
input_types={"a": vector(length=6, dtype=Float), "b": vector(length=6, dtype=Float)},
value_func=sametype_value_func(vector(length=6, dtype=Float)),
group="Spatial Math",
doc="Compute the cross product of two 6D screw vectors.",
)
add_builtin(
"spatial_cross_dual",
input_types={"a": vector(length=6, dtype=Float), "b": vector(length=6, dtype=Float)},
value_func=sametype_value_func(vector(length=6, dtype=Float)),
group="Spatial Math",
doc="Compute the dual cross product of two 6D screw vectors.",
)
add_builtin(
"spatial_top",
input_types={"a": vector(length=6, dtype=Float)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=arg_types[0]._wp_scalar_type_),
group="Spatial Math",
doc="Return the top (first) part of a 6D screw vector.",
)
add_builtin(
"spatial_bottom",
input_types={"a": vector(length=6, dtype=Float)},
value_func=lambda arg_types, kwds, _: vector(length=3, dtype=arg_types[0]._wp_scalar_type_),
group="Spatial Math",
doc="Return the bottom (second) part of a 6D screw vector.",
)
add_builtin(
"spatial_jacobian",
input_types={
"S": array(dtype=vector(length=6, dtype=Float)),
"joint_parents": array(dtype=int),
"joint_qd_start": array(dtype=int),
"joint_start": int,
"joint_count": int,
"J_start": int,
"J_out": array(dtype=Float),
},
value_type=None,
doc="",
group="Spatial Math",
)
add_builtin(
"spatial_mass",
input_types={
"I_s": array(dtype=matrix(shape=(6, 6), dtype=Float)),
"joint_start": int,
"joint_count": int,
"M_start": int,
"M": array(dtype=Float),
},
value_type=None,
doc="",
group="Spatial Math",
)
# ---------------------------------
# Linear Algebra
add_builtin(
"dense_gemm",
input_types={
"m": int,
"n": int,
"p": int,
"t1": int,
"t2": int,
"A": array(dtype=float),
"B": array(dtype=float),
"C": array(dtype=float),
},
value_type=None,
doc="",
group="Utility",
hidden=True,
)
add_builtin(
"dense_gemm_batched",
input_types={
"m": array(dtype=int),
"n": array(dtype=int),
"p": array(dtype=int),
"t1": int,
"t2": int,
"A_start": array(dtype=int),
"B_start": array(dtype=int),
"C_start": array(dtype=int),
"A": array(dtype=float),
"B": array(dtype=float),
"C": array(dtype=float),
},
value_type=None,
doc="",
group="Utility",
hidden=True,
)
add_builtin(
"dense_chol",
input_types={"n": int, "A": array(dtype=float), "regularization": float, "L": array(dtype=float)},
value_type=None,
doc="WIP",
group="Utility",
hidden=True,
)
add_builtin(
"dense_chol_batched",
input_types={
"A_start": array(dtype=int),
"A_dim": array(dtype=int),
"A": array(dtype=float),
"regularization": float,
"L": array(dtype=float),
},
value_type=None,
doc="WIP",
group="Utility",
hidden=True,
)
add_builtin(
"dense_subs",
input_types={"n": int, "L": array(dtype=float), "b": array(dtype=float), "x": array(dtype=float)},
value_type=None,
doc="WIP",
group="Utility",
hidden=True,
)
add_builtin(
"dense_solve",
input_types={
"n": int,
"A": array(dtype=float),
"L": array(dtype=float),
"b": array(dtype=float),
"x": array(dtype=float),
},
value_type=None,
doc="WIP",
group="Utility",
hidden=True,
)
add_builtin(
"dense_solve_batched",
input_types={
"b_start": array(dtype=int),
"A_start": array(dtype=int),
"A_dim": array(dtype=int),
"A": array(dtype=float),
"L": array(dtype=float),
"b": array(dtype=float),
"x": array(dtype=float),
},
value_type=None,
doc="WIP",
group="Utility",
hidden=True,
)
add_builtin(
"mlp",
input_types={
"weights": array(dtype=float, ndim=2),
"bias": array(dtype=float, ndim=1),
"activation": Callable,
"index": int,
"x": array(dtype=float, ndim=2),
"out": array(dtype=float, ndim=2),
},
value_type=None,
skip_replay=True,
doc="""Evaluate a multi-layer perceptron (MLP) layer in the form: ``out = act(weights*x + bias)``.
:param weights: A layer's network weights with dimensions ``(m, n)``.
:param bias: An array with dimensions ``(n)``.
:param activation: A ``wp.func`` function that takes a single scalar float as input and returns a scalar float as output
:param index: The batch item to process, typically each thread will process one item in the batch, in which case
index should be ``wp.tid()``
:param x: The feature matrix with dimensions ``(n, b)``
:param out: The network output with dimensions ``(m, b)``
:note: Feature and output matrices are transposed compared to some other frameworks such as PyTorch.
All matrices are assumed to be stored in flattened row-major memory layout (NumPy default).""",
group="Utility",
)
# ---------------------------------
# Geometry
add_builtin(
"bvh_query_aabb",
input_types={"id": uint64, "lower": vec3, "upper": vec3},
value_type=bvh_query_t,
group="Geometry",
doc="""Construct an axis-aligned bounding box query against a BVH object.
This query can be used to iterate over all bounds inside a BVH.
:param id: The BVH identifier
:param lower: The lower bound of the bounding box in BVH space
:param upper: The upper bound of the bounding box in BVH space""",
)
add_builtin(
"bvh_query_ray",
input_types={"id": uint64, "start": vec3, "dir": vec3},
value_type=bvh_query_t,
group="Geometry",
doc="""Construct a ray query against a BVH object.
This query can be used to iterate over all bounds that intersect the ray.
:param id: The BVH identifier
:param start: The start of the ray in BVH space
:param dir: The direction of the ray in BVH space""",
)
add_builtin(
"bvh_query_next",
input_types={"query": bvh_query_t, "index": int},
value_type=builtins.bool,
group="Geometry",
doc="""Move to the next bound returned by the query.
The index of the current bound is stored in ``index``, returns ``False`` if there are no more overlapping bound.""",
)
add_builtin(
"mesh_query_point",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
"inside": float,
"face": int,
"bary_u": float,
"bary_v": float,
},
value_type=builtins.bool,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space. Returns ``True`` if a point < ``max_dist`` is found.
Identifies the sign of the distance using additional ray-casts to determine if the point is inside or outside.
This method is relatively robust, but does increase computational cost.
See below for additional sign determination methods.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param inside: Returns a value < 0 if query point is inside the mesh, >=0 otherwise.
Note that mesh must be watertight for this to be robust
:param face: Returns the index of the closest face
:param bary_u: Returns the barycentric u coordinate of the closest point
:param bary_v: Returns the barycentric v coordinate of the closest point""",
hidden=True,
)
add_builtin(
"mesh_query_point",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
},
value_type=mesh_query_point_t,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space.
Identifies the sign of the distance using additional ray-casts to determine if the point is inside or outside.
This method is relatively robust, but does increase computational cost.
See below for additional sign determination methods.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query""",
require_original_output_arg=True,
)
add_builtin(
"mesh_query_point_no_sign",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
"face": int,
"bary_u": float,
"bary_v": float,
},
value_type=builtins.bool,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space. Returns ``True`` if a point < ``max_dist`` is found.
This method does not compute the sign of the point (inside/outside) which makes it faster than other point query methods.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param face: Returns the index of the closest face
:param bary_u: Returns the barycentric u coordinate of the closest point
:param bary_v: Returns the barycentric v coordinate of the closest point""",
hidden=True,
)
add_builtin(
"mesh_query_point_no_sign",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
},
value_type=mesh_query_point_t,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space.
This method does not compute the sign of the point (inside/outside) which makes it faster than other point query methods.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query""",
require_original_output_arg=True,
)
add_builtin(
"mesh_query_furthest_point_no_sign",
input_types={
"id": uint64,
"point": vec3,
"min_dist": float,
"face": int,
"bary_u": float,
"bary_v": float,
},
value_type=builtins.bool,
group="Geometry",
doc="""Computes the furthest point on the mesh with identifier `id` to the given point in space. Returns ``True`` if a point > ``min_dist`` is found.
This method does not compute the sign of the point (inside/outside).
:param id: The mesh identifier
:param point: The point in space to query
:param min_dist: Mesh faces below this distance will not be considered by the query
:param face: Returns the index of the furthest face
:param bary_u: Returns the barycentric u coordinate of the furthest point
:param bary_v: Returns the barycentric v coordinate of the furthest point""",
hidden=True,
)
add_builtin(
"mesh_query_furthest_point_no_sign",
input_types={
"id": uint64,
"point": vec3,
"min_dist": float,
},
value_type=mesh_query_point_t,
group="Geometry",
doc="""Computes the furthest point on the mesh with identifier `id` to the given point in space.
This method does not compute the sign of the point (inside/outside).
:param id: The mesh identifier
:param point: The point in space to query
:param min_dist: Mesh faces below this distance will not be considered by the query""",
require_original_output_arg=True,
)
add_builtin(
"mesh_query_point_sign_normal",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
"inside": float,
"face": int,
"bary_u": float,
"bary_v": float,
"epsilon": float,
},
defaults={"epsilon": 1.0e-3},
value_type=builtins.bool,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space. Returns ``True`` if a point < ``max_dist`` is found.
Identifies the sign of the distance (inside/outside) using the angle-weighted pseudo normal.
This approach to sign determination is robust for well conditioned meshes that are watertight and non-self intersecting.
It is also comparatively fast to compute.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param inside: Returns a value < 0 if query point is inside the mesh, >=0 otherwise.
Note that mesh must be watertight for this to be robust
:param face: Returns the index of the closest face
:param bary_u: Returns the barycentric u coordinate of the closest point
:param bary_v: Returns the barycentric v coordinate of the closest point
:param epsilon: Epsilon treating distance values as equal, when locating the minimum distance vertex/face/edge, as a
fraction of the average edge length, also for treating closest point as being on edge/vertex default 1e-3""",
hidden=True,
)
add_builtin(
"mesh_query_point_sign_normal",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
"epsilon": float,
},
defaults={"epsilon": 1.0e-3},
value_type=mesh_query_point_t,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given ``point`` in space.
Identifies the sign of the distance (inside/outside) using the angle-weighted pseudo normal.
This approach to sign determination is robust for well conditioned meshes that are watertight and non-self intersecting.
It is also comparatively fast to compute.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param epsilon: Epsilon treating distance values as equal, when locating the minimum distance vertex/face/edge, as a
fraction of the average edge length, also for treating closest point as being on edge/vertex default 1e-3""",
require_original_output_arg=True,
)
add_builtin(
"mesh_query_point_sign_winding_number",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
"inside": float,
"face": int,
"bary_u": float,
"bary_v": float,
"accuracy": float,
"threshold": float,
},
defaults={"accuracy": 2.0, "threshold": 0.5},
value_type=builtins.bool,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given point in space. Returns ``True`` if a point < ``max_dist`` is found.
Identifies the sign using the winding number of the mesh relative to the query point. This method of sign determination is robust for poorly conditioned meshes
and provides a smooth approximation to sign even when the mesh is not watertight. This method is the most robust and accurate of the sign determination meshes
but also the most expensive.
.. note:: The :class:`Mesh` object must be constructed with ``support_winding_number=True`` for this method to return correct results.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param inside: Returns a value < 0 if query point is inside the mesh, >=0 otherwise.
Note that mesh must be watertight for this to be robust
:param face: Returns the index of the closest face
:param bary_u: Returns the barycentric u coordinate of the closest point
:param bary_v: Returns the barycentric v coordinate of the closest point
:param accuracy: Accuracy for computing the winding number with fast winding number method utilizing second-order dipole approximation, default 2.0
:param threshold: The threshold of the winding number to be considered inside, default 0.5""",
hidden=True,
)
add_builtin(
"mesh_query_point_sign_winding_number",
input_types={
"id": uint64,
"point": vec3,
"max_dist": float,
"accuracy": float,
"threshold": float,
},
defaults={"accuracy": 2.0, "threshold": 0.5},
value_type=mesh_query_point_t,
group="Geometry",
doc="""Computes the closest point on the :class:`Mesh` with identifier ``id`` to the given point in space.
Identifies the sign using the winding number of the mesh relative to the query point. This method of sign determination is robust for poorly conditioned meshes
and provides a smooth approximation to sign even when the mesh is not watertight. This method is the most robust and accurate of the sign determination meshes
but also the most expensive.
.. note:: The :class:`Mesh` object must be constructed with ``support_winding_number=True`` for this method to return correct results.
:param id: The mesh identifier
:param point: The point in space to query
:param max_dist: Mesh faces above this distance will not be considered by the query
:param accuracy: Accuracy for computing the winding number with fast winding number method utilizing second-order dipole approximation, default 2.0
:param threshold: The threshold of the winding number to be considered inside, default 0.5""",
require_original_output_arg=True,
)
add_builtin(
"mesh_query_ray",
input_types={
"id": uint64,
"start": vec3,
"dir": vec3,
"max_t": float,
"t": float,
"bary_u": float,
"bary_v": float,
"sign": float,
"normal": vec3,
"face": int,
},
value_type=builtins.bool,
group="Geometry",
doc="""Computes the closest ray hit on the :class:`Mesh` with identifier ``id``, returns ``True`` if a hit < ``max_t`` is found.
:param id: The mesh identifier
:param start: The start point of the ray
:param dir: The ray direction (should be normalized)
:param max_t: The maximum distance along the ray to check for intersections
:param t: Returns the distance of the closest hit along the ray
:param bary_u: Returns the barycentric u coordinate of the closest hit
:param bary_v: Returns the barycentric v coordinate of the closest hit
:param sign: Returns a value > 0 if the ray hit in front of the face, returns < 0 otherwise
:param normal: Returns the face normal
:param face: Returns the index of the hit face""",
hidden=True,
)
add_builtin(
"mesh_query_ray",
input_types={
"id": uint64,
"start": vec3,
"dir": vec3,
"max_t": float,
},
value_type=mesh_query_ray_t,
group="Geometry",
doc="""Computes the closest ray hit on the :class:`Mesh` with identifier ``id``.
:param id: The mesh identifier
:param start: The start point of the ray
:param dir: The ray direction (should be normalized)
:param max_t: The maximum distance along the ray to check for intersections""",
require_original_output_arg=True,
)
add_builtin(
"mesh_query_aabb",
input_types={"id": uint64, "lower": vec3, "upper": vec3},
value_type=mesh_query_aabb_t,
group="Geometry",
doc="""Construct an axis-aligned bounding box query against a :class:`Mesh`.
This query can be used to iterate over all triangles inside a volume.
:param id: The mesh identifier
:param lower: The lower bound of the bounding box in mesh space
:param upper: The upper bound of the bounding box in mesh space""",
)
add_builtin(
"mesh_query_aabb_next",
input_types={"query": mesh_query_aabb_t, "index": int},
value_type=builtins.bool,
group="Geometry",
doc="""Move to the next triangle overlapping the query bounding box.
The index of the current face is stored in ``index``, returns ``False`` if there are no more overlapping triangles.""",
)
add_builtin(
"mesh_eval_position",
input_types={"id": uint64, "face": int, "bary_u": float, "bary_v": float},
value_type=vec3,
group="Geometry",
doc="""Evaluates the position on the :class:`Mesh` given a face index and barycentric coordinates.""",
)
add_builtin(
"mesh_eval_velocity",
input_types={"id": uint64, "face": int, "bary_u": float, "bary_v": float},
value_type=vec3,
group="Geometry",
doc="""Evaluates the velocity on the :class:`Mesh` given a face index and barycentric coordinates.""",
)
add_builtin(
"hash_grid_query",
input_types={"id": uint64, "point": vec3, "max_dist": float},
value_type=hash_grid_query_t,
group="Geometry",
doc="""Construct a point query against a :class:`HashGrid`.
This query can be used to iterate over all neighboring point within a fixed radius from the query point.""",
)
add_builtin(
"hash_grid_query_next",
input_types={"query": hash_grid_query_t, "index": int},
value_type=builtins.bool,
group="Geometry",
doc="""Move to the next point in the hash grid query.
The index of the current neighbor is stored in ``index``, returns ``False`` if there are no more neighbors.""",
)
add_builtin(
"hash_grid_point_id",
input_types={"id": uint64, "index": int},
value_type=int,
group="Geometry",
doc="""Return the index of a point in the :class:`HashGrid`.
This can be used to reorder threads such that grid traversal occurs in a spatially coherent order.
Returns -1 if the :class:`HashGrid` has not been reserved.""",
)
add_builtin(
"intersect_tri_tri",
input_types={"v0": vec3, "v1": vec3, "v2": vec3, "u0": vec3, "u1": vec3, "u2": vec3},
value_type=int,
group="Geometry",
doc="""Tests for intersection between two triangles (v0, v1, v2) and (u0, u1, u2) using Moller's method.
Returns > 0 if triangles intersect.""",
)
add_builtin(
"mesh_get",
input_types={"id": uint64},
value_type=Mesh,
missing_grad=True,
group="Geometry",
doc="""Retrieves the mesh given its index.""",
)
add_builtin(
"mesh_eval_face_normal",
input_types={"id": uint64, "face": int},
value_type=vec3,
group="Geometry",
doc="""Evaluates the face normal the mesh given a face index.""",
)
add_builtin(
"mesh_get_point",
input_types={"id": uint64, "index": int},
value_type=vec3,
group="Geometry",
doc="""Returns the point of the mesh given a index.""",
)
add_builtin(
"mesh_get_velocity",
input_types={"id": uint64, "index": int},
value_type=vec3,
group="Geometry",
doc="""Returns the velocity of the mesh given a index.""",
)
add_builtin(
"mesh_get_index",
input_types={"id": uint64, "index": int},
value_type=int,
group="Geometry",
doc="""Returns the point-index of the mesh given a face-vertex index.""",
)
add_builtin(
"closest_point_edge_edge",
input_types={"p1": vec3, "q1": vec3, "p2": vec3, "q2": vec3, "epsilon": float},
value_type=vec3,
group="Geometry",
doc="""Finds the closest points between two edges.
Returns barycentric weights to the points on each edge, as well as the closest distance between the edges.
:param p1: First point of first edge
:param q1: Second point of first edge
:param p2: First point of second edge
:param q2: Second point of second edge
:param epsilon: Zero tolerance for determining if points in an edge are degenerate.
:param out: vec3 output containing (s,t,d), where `s` in [0,1] is the barycentric weight for the first edge, `t` is the barycentric weight for the second edge, and `d` is the distance between the two edges at these two closest points.""",
)
# ---------------------------------
# Ranges
add_builtin("range", input_types={"end": int}, value_type=range_t, group="Utility", export=False, hidden=True)
add_builtin(
"range", input_types={"start": int, "end": int}, value_type=range_t, group="Utility", export=False, hidden=True
)
add_builtin(
"range",
input_types={"start": int, "end": int, "step": int},
value_type=range_t,
group="Utility",
export=False,
hidden=True,
)
# ---------------------------------
# Iterators
add_builtin("iter_next", input_types={"range": range_t}, value_type=int, group="Utility", hidden=True)
add_builtin("iter_next", input_types={"query": hash_grid_query_t}, value_type=int, group="Utility", hidden=True)
add_builtin("iter_next", input_types={"query": mesh_query_aabb_t}, value_type=int, group="Utility", hidden=True)
# ---------------------------------
# Volumes
_volume_supported_value_types = {
int32,
int64,
uint32,
float32,
float64,
vec3f,
vec3d,
vec4f,
vec4d,
}
def volume_value_func(arg_types, kwds, templates):
try:
dtype = kwds["dtype"]
except KeyError as err:
raise RuntimeError(
"'dtype' keyword argument must be specified when calling generic volume lookup or sampling functions"
) from err
if dtype not in _volume_supported_value_types:
raise RuntimeError(f"Unsupported volume type '{type_repr(dtype)}'")
templates.append(dtype)
return dtype
add_builtin(
"volume_sample",
input_types={"id": uint64, "uvw": vec3, "sampling_mode": int, "dtype": Any},
value_func=volume_value_func,
export=False,
group="Volumes",
doc="""Sample the volume of type `dtype` given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`""",
)
def check_volume_value_grad_compatibility(dtype, grad_dtype):
if type_is_vector(dtype):
expected = matrix(shape=(type_length(dtype), 3), dtype=type_scalar_type(dtype))
else:
expected = vector(length=3, dtype=dtype)
if not types_equal(grad_dtype, expected):
raise RuntimeError(f"Incompatible gradient type, expected {type_repr(expected)}, got {type_repr(grad_dtype)}")
def volume_sample_grad_value_func(arg_types, kwds, templates):
dtype = volume_value_func(arg_types, kwds, templates)
if len(arg_types) < 4:
raise RuntimeError("'volume_sample_grad' requires 4 positional arguments")
grad_type = arg_types[3]
check_volume_value_grad_compatibility(dtype, grad_type)
return dtype
add_builtin(
"volume_sample_grad",
input_types={"id": uint64, "uvw": vec3, "sampling_mode": int, "grad": Any, "dtype": Any},
value_func=volume_sample_grad_value_func,
export=False,
group="Volumes",
doc="""Sample the volume given by ``id`` and its gradient at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`""",
)
add_builtin(
"volume_lookup",
input_types={"id": uint64, "i": int, "j": int, "k": int, "dtype": Any},
value_type=int,
value_func=volume_value_func,
export=False,
group="Volumes",
doc="""Returns the value of voxel with coordinates ``i``, ``j``, ``k`` for a volume of type type `dtype`.
If the voxel at this index does not exist, this function returns the background value.""",
)
def volume_store_value_func(arg_types, kwds, templates):
if len(arg_types) < 4:
raise RuntimeError("'volume_store' requires 5 positional arguments")
dtype = arg_types[4]
if dtype not in _volume_supported_value_types:
raise RuntimeError(f"Unsupported volume type '{type_repr(dtype)}'")
return None
add_builtin(
"volume_store",
value_func=volume_store_value_func,
input_types={"id": uint64, "i": int, "j": int, "k": int, "value": Any},
export=False,
group="Volumes",
doc="""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``.""",
)
add_builtin(
"volume_sample_f",
input_types={"id": uint64, "uvw": vec3, "sampling_mode": int},
value_type=float,
group="Volumes",
doc="""Sample the volume given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`""",
)
add_builtin(
"volume_sample_grad_f",
input_types={"id": uint64, "uvw": vec3, "sampling_mode": int, "grad": vec3},
value_type=float,
group="Volumes",
doc="""Sample the volume and its gradient given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`""",
)
add_builtin(
"volume_lookup_f",
input_types={"id": uint64, "i": int, "j": int, "k": int},
value_type=float,
group="Volumes",
doc="""Returns the value of voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns the background value""",
)
add_builtin(
"volume_store_f",
input_types={"id": uint64, "i": int, "j": int, "k": int, "value": float},
group="Volumes",
doc="""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``.""",
)
add_builtin(
"volume_sample_v",
input_types={"id": uint64, "uvw": vec3, "sampling_mode": int},
value_type=vec3,
group="Volumes",
doc="""Sample the vector volume given by ``id`` at the volume local-space point ``uvw``.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR.`""",
)
add_builtin(
"volume_lookup_v",
input_types={"id": uint64, "i": int, "j": int, "k": int},
value_type=vec3,
group="Volumes",
doc="""Returns the vector value of voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns the background value.""",
)
add_builtin(
"volume_store_v",
input_types={"id": uint64, "i": int, "j": int, "k": int, "value": vec3},
group="Volumes",
doc="""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``.""",
)
add_builtin(
"volume_sample_i",
input_types={"id": uint64, "uvw": vec3},
value_type=int,
group="Volumes",
doc="""Sample the :class:`int32` volume given by ``id`` at the volume local-space point ``uvw``. """,
)
add_builtin(
"volume_lookup_i",
input_types={"id": uint64, "i": int, "j": int, "k": int},
value_type=int,
group="Volumes",
doc="""Returns the :class:`int32` value of voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns the background value.""",
)
add_builtin(
"volume_store_i",
input_types={"id": uint64, "i": int, "j": int, "k": int, "value": int},
group="Volumes",
doc="""Store ``value`` at the voxel with coordinates ``i``, ``j``, ``k``.""",
)
def volume_sample_index_value_func(arg_types, kwds, templates):
if len(arg_types) != 5:
raise RuntimeError("'volume_sample_index' requires 5 positional arguments")
dtype = arg_types[3].dtype
if not types_equal(dtype, arg_types[4]):
raise RuntimeError("The 'voxel_data' array and the 'background' value must have the same dtype")
return dtype
add_builtin(
"volume_sample_index",
input_types={"id": uint64, "uvw": vec3, "sampling_mode": int, "voxel_data": array(dtype=Any), "background": Any},
value_func=volume_sample_index_value_func,
export=False,
group="Volumes",
doc="""Sample the volume given by ``id`` at the volume local-space point ``uvw``.
Values for allocated voxels are read from the ``voxel_data`` array, and `background` is used as the value of non-existing voxels.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR`.
This function is available for both index grids and classical volumes.
""",
)
def volume_sample_grad_index_value_func(arg_types, kwds, templates):
if len(arg_types) != 6:
raise RuntimeError("'volume_sample_grad_index' requires 6 positional arguments")
dtype = arg_types[3].dtype
if not types_equal(dtype, arg_types[4]):
raise RuntimeError("The 'voxel_data' array and the 'background' value must have the same dtype")
grad_type = arg_types[5]
check_volume_value_grad_compatibility(dtype, grad_type)
return dtype
add_builtin(
"volume_sample_grad_index",
input_types={
"id": uint64,
"uvw": vec3,
"sampling_mode": int,
"voxel_data": array(dtype=Any),
"background": Any,
"grad": Any,
},
value_func=volume_sample_grad_index_value_func,
export=False,
group="Volumes",
doc="""Sample the volume given by ``id`` and its gradient at the volume local-space point ``uvw``.
Values for allocated voxels are read from the ``voxel_data`` array, and `background` is used as the value of non-existing voxels.
Interpolation should be :attr:`warp.Volume.CLOSEST` or :attr:`wp.Volume.LINEAR`.
This function is available for both index grids and classical volumes.
""",
)
add_builtin(
"volume_lookup_index",
input_types={"id": uint64, "i": int, "j": int, "k": int},
value_type=int32,
group="Volumes",
doc="""Returns the index associated to the voxel with coordinates ``i``, ``j``, ``k``.
If the voxel at this index does not exist, this function returns -1.
This function is available for both index grids and classical volumes.
""",
)
add_builtin(
"volume_index_to_world",
input_types={"id": uint64, "uvw": vec3},
value_type=vec3,
group="Volumes",
doc="""Transform a point ``uvw`` defined in volume index space to world space given the volume's intrinsic affine transformation.""",
)
add_builtin(
"volume_world_to_index",
input_types={"id": uint64, "xyz": vec3},
value_type=vec3,
group="Volumes",
doc="""Transform a point ``xyz`` defined in volume world space to the volume's index space given the volume's intrinsic affine transformation.""",
)
add_builtin(
"volume_index_to_world_dir",
input_types={"id": uint64, "uvw": vec3},
value_type=vec3,
group="Volumes",
doc="""Transform a direction ``uvw`` defined in volume index space to world space given the volume's intrinsic affine transformation.""",
)
add_builtin(
"volume_world_to_index_dir",
input_types={"id": uint64, "xyz": vec3},
value_type=vec3,
group="Volumes",
doc="""Transform a direction ``xyz`` defined in volume world space to the volume's index space given the volume's intrinsic affine transformation.""",
)
# ---------------------------------
# Random
add_builtin(
"rand_init",
input_types={"seed": int},
value_type=uint32,
group="Random",
doc="Initialize a new random number generator given a user-defined seed. Returns a 32-bit integer representing the RNG state.",
)
add_builtin(
"rand_init",
input_types={"seed": int, "offset": int},
value_type=uint32,
group="Random",
doc="""Initialize a new random number generator given a user-defined seed and an offset.
This alternative constructor can be useful in parallel programs, where a kernel as a whole should share a seed,
but each thread should generate uncorrelated values. In this case usage should be ``r = rand_init(seed, tid)``""",
)
add_builtin(
"randi",
input_types={"state": uint32},
value_type=int,
group="Random",
doc="Return a random integer in the range [0, 2^32).",
)
add_builtin(
"randi",
input_types={"state": uint32, "min": int, "max": int},
value_type=int,
group="Random",
doc="Return a random integer between [min, max).",
)
add_builtin(
"randf",
input_types={"state": uint32},
value_type=float,
group="Random",
doc="Return a random float between [0.0, 1.0).",
)
add_builtin(
"randf",
input_types={"state": uint32, "min": float, "max": float},
value_type=float,
group="Random",
doc="Return a random float between [min, max).",
)
add_builtin(
"randn", input_types={"state": uint32}, value_type=float, group="Random", doc="Sample a normal distribution."
)
add_builtin(
"sample_cdf",
input_types={"state": uint32, "cdf": array(dtype=float)},
value_type=int,
group="Random",
doc="Inverse-transform sample a cumulative distribution function.",
)
add_builtin(
"sample_triangle",
input_types={"state": uint32},
value_type=vec2,
group="Random",
doc="Uniformly sample a triangle. Returns sample barycentric coordinates.",
)
add_builtin(
"sample_unit_ring",
input_types={"state": uint32},
value_type=vec2,
group="Random",
doc="Uniformly sample a ring in the xy plane.",
)
add_builtin(
"sample_unit_disk",
input_types={"state": uint32},
value_type=vec2,
group="Random",
doc="Uniformly sample a disk in the xy plane.",
)
add_builtin(
"sample_unit_sphere_surface",
input_types={"state": uint32},
value_type=vec3,
group="Random",
doc="Uniformly sample a unit sphere surface.",
)
add_builtin(
"sample_unit_sphere",
input_types={"state": uint32},
value_type=vec3,
group="Random",
doc="Uniformly sample a unit sphere.",
)
add_builtin(
"sample_unit_hemisphere_surface",
input_types={"state": uint32},
value_type=vec3,
group="Random",
doc="Uniformly sample a unit hemisphere surface.",
)
add_builtin(
"sample_unit_hemisphere",
input_types={"state": uint32},
value_type=vec3,
group="Random",
doc="Uniformly sample a unit hemisphere.",
)
add_builtin(
"sample_unit_square",
input_types={"state": uint32},
value_type=vec2,
group="Random",
doc="Uniformly sample a unit square.",
)
add_builtin(
"sample_unit_cube",
input_types={"state": uint32},
value_type=vec3,
group="Random",
doc="Uniformly sample a unit cube.",
)
add_builtin(
"poisson",
input_types={"state": uint32, "lam": float},
value_type=uint32,
group="Random",
doc="""Generate a random sample from a Poisson distribution.
:param state: RNG state
:param lam: The expected value of the distribution""",
)
add_builtin(
"noise",
input_types={"state": uint32, "x": float},
value_type=float,
group="Random",
doc="Non-periodic Perlin-style noise in 1D.",
)
add_builtin(
"noise",
input_types={"state": uint32, "xy": vec2},
value_type=float,
group="Random",
doc="Non-periodic Perlin-style noise in 2D.",
)
add_builtin(
"noise",
input_types={"state": uint32, "xyz": vec3},
value_type=float,
group="Random",
doc="Non-periodic Perlin-style noise in 3D.",
)
add_builtin(
"noise",
input_types={"state": uint32, "xyzt": vec4},
value_type=float,
group="Random",
doc="Non-periodic Perlin-style noise in 4D.",
)
add_builtin(
"pnoise",
input_types={"state": uint32, "x": float, "px": int},
value_type=float,
group="Random",
doc="Periodic Perlin-style noise in 1D.",
)
add_builtin(
"pnoise",
input_types={"state": uint32, "xy": vec2, "px": int, "py": int},
value_type=float,
group="Random",
doc="Periodic Perlin-style noise in 2D.",
)
add_builtin(
"pnoise",
input_types={"state": uint32, "xyz": vec3, "px": int, "py": int, "pz": int},
value_type=float,
group="Random",
doc="Periodic Perlin-style noise in 3D.",
)
add_builtin(
"pnoise",
input_types={"state": uint32, "xyzt": vec4, "px": int, "py": int, "pz": int, "pt": int},
value_type=float,
group="Random",
doc="Periodic Perlin-style noise in 4D.",
)
add_builtin(
"curlnoise",
input_types={"state": uint32, "xy": vec2, "octaves": uint32, "lacunarity": float, "gain": float},
defaults={"octaves": 1, "lacunarity": 2.0, "gain": 0.5},
value_type=vec2,
group="Random",
doc="Divergence-free vector field based on the gradient of a Perlin noise function.",
missing_grad=True,
)
add_builtin(
"curlnoise",
input_types={"state": uint32, "xyz": vec3, "octaves": uint32, "lacunarity": float, "gain": float},
defaults={"octaves": 1, "lacunarity": 2.0, "gain": 0.5},
value_type=vec3,
group="Random",
doc="Divergence-free vector field based on the curl of three Perlin noise functions.",
missing_grad=True,
)
add_builtin(
"curlnoise",
input_types={"state": uint32, "xyzt": vec4, "octaves": uint32, "lacunarity": float, "gain": float},
defaults={"octaves": 1, "lacunarity": 2.0, "gain": 0.5},
value_type=vec3,
group="Random",
doc="Divergence-free vector field based on the curl of three Perlin noise functions.",
missing_grad=True,
)
# note printf calls directly to global CRT printf (no wp:: namespace prefix)
add_builtin(
"printf",
input_types={},
namespace="",
variadic=True,
group="Utility",
doc="Allows printing formatted strings using C-style format specifiers.",
)
add_builtin("print", input_types={"value": Any}, doc="Print variable to stdout", export=False, group="Utility")
add_builtin(
"breakpoint",
input_types={},
doc="Debugger breakpoint",
export=False,
group="Utility",
namespace="",
native_func="__debugbreak",
)
# helpers
add_builtin(
"tid",
input_types={},
value_type=int,
export=False,
group="Utility",
doc="""Return the current thread index for a 1D kernel launch.
Note that this is the *global* index of the thread in the range [0, dim)
where dim is the parameter passed to kernel launch.
This function may not be called from user-defined Warp functions.""",
namespace="",
native_func="builtin_tid1d",
)
add_builtin(
"tid",
input_types={},
value_type=[int, int],
group="Utility",
doc="""Return the current thread indices for a 2D kernel launch.
Use ``i,j = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid.
This function may not be called from user-defined Warp functions.""",
namespace="",
native_func="builtin_tid2d",
)
add_builtin(
"tid",
input_types={},
value_type=[int, int, int],
group="Utility",
doc="""Return the current thread indices for a 3D kernel launch.
Use ``i,j,k = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid.
This function may not be called from user-defined Warp functions.""",
namespace="",
native_func="builtin_tid3d",
)
add_builtin(
"tid",
input_types={},
value_type=[int, int, int, int],
group="Utility",
doc="""Return the current thread indices for a 4D kernel launch.
Use ``i,j,k,l = wp.tid()`` syntax to retrieve the coordinates inside the kernel thread grid.
This function may not be called from user-defined Warp functions.""",
namespace="",
native_func="builtin_tid4d",
)
add_builtin(
"copy",
input_types={"value": Any},
value_func=lambda arg_types, kwds, _: arg_types[0],
hidden=True,
export=False,
group="Utility",
)
add_builtin("assign", variadic=True, hidden=True, export=False, group="Utility")
add_builtin(
"select",
input_types={"cond": builtins.bool, "arg1": Any, "arg2": Any},
value_func=lambda arg_types, kwds, _: arg_types[1],
doc="Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``",
group="Utility",
)
for t in int_types:
add_builtin(
"select",
input_types={"cond": t, "arg1": Any, "arg2": Any},
value_func=lambda arg_types, kwds, _: arg_types[1],
doc="Select between two arguments, if ``cond`` is ``False`` then return ``arg1``, otherwise return ``arg2``",
group="Utility",
)
add_builtin(
"select",
input_types={"arr": array(dtype=Any), "arg1": Any, "arg2": Any},
value_func=lambda arg_types, kwds, _: arg_types[1],
doc="Select between two arguments, if ``arr`` is null then return ``arg1``, otherwise return ``arg2``",
group="Utility",
)
# does argument checking and type propagation for address()
def address_value_func(arg_types, kwds, _):
if not is_array(arg_types[0]):
raise RuntimeError("load() argument 0 must be an array")
num_indices = len(arg_types) - 1
num_dims = arg_types[0].ndim
if num_indices < num_dims:
raise RuntimeError(
"Num indices < num dimensions for array load, this is a codegen error, should have generated a view instead"
)
if num_indices > num_dims:
raise RuntimeError(
f"Num indices > num dimensions for array load, received {num_indices}, but array only has {num_dims}"
)
# check index types
for t in arg_types[1:]:
if not type_is_int(t):
raise RuntimeError(f"address() index arguments must be of integer type, got index of type {t}")
return Reference(arg_types[0].dtype)
# does argument checking and type propagation for view()
def view_value_func(arg_types, kwds, _):
if not is_array(arg_types[0]):
raise RuntimeError("view() argument 0 must be an array")
# check array dim big enough to support view
num_indices = len(arg_types) - 1
num_dims = arg_types[0].ndim
if num_indices >= num_dims:
raise RuntimeError(
f"Trying to create an array view with {num_indices} indices, but the array only has {num_dims} dimension(s). Ensure that the argument type on the function or kernel specifies the expected number of dimensions, e.g.: def func(param: wp.array3d(dtype=float):"
)
# check index types
for t in arg_types[1:]:
if not type_is_int(t):
raise RuntimeError(f"view() index arguments must be of integer type, got index of type {t}")
# create an array view with leading dimensions removed
dtype = arg_types[0].dtype
ndim = num_dims - num_indices
if isinstance(arg_types[0], (fabricarray, indexedfabricarray)):
# fabric array of arrays: return array attribute as a regular array
return array(dtype=dtype, ndim=ndim)
else:
return type(arg_types[0])(dtype=dtype, ndim=ndim)
# does argument checking and type propagation for array_store()
def array_store_value_func(arg_types, kwds, _):
# check target type
if not is_array(arg_types[0]):
raise RuntimeError("array_store() argument 0 must be an array")
num_indices = len(arg_types[1:-1])
num_dims = arg_types[0].ndim
# if this happens we should have generated a view instead of a load during code gen
if num_indices < num_dims:
raise RuntimeError("Num indices < num dimensions for array store")
if num_indices > num_dims:
raise RuntimeError(
f"Num indices > num dimensions for array store, received {num_indices}, but array only has {num_dims}"
)
# check index types
for t in arg_types[1:-1]:
if not type_is_int(t):
raise RuntimeError(f"array_store() index arguments must be of integer type, got index of type {t}")
# check value type
if not types_equal(arg_types[-1], arg_types[0].dtype):
raise RuntimeError(
f"array_store() value argument type ({arg_types[2]}) must be of the same type as the array ({arg_types[0].dtype})"
)
return None
# does argument checking for store()
def store_value_func(arg_types, kwds, _):
# we already stripped the Reference from the argument type prior to this call
if not types_equal(arg_types[0], arg_types[1]):
raise RuntimeError(f"store() value argument type ({arg_types[1]}) must be of the same type as the reference")
return None
# does type propagation for load()
def load_value_func(arg_types, kwds, _):
# we already stripped the Reference from the argument type prior to this call
return arg_types[0]
add_builtin("address", variadic=True, hidden=True, value_func=address_value_func, group="Utility")
add_builtin("view", variadic=True, hidden=True, value_func=view_value_func, group="Utility")
add_builtin(
"array_store", variadic=True, hidden=True, value_func=array_store_value_func, skip_replay=True, group="Utility"
)
add_builtin(
"store",
input_types={"address": Reference, "value": Any},
hidden=True,
value_func=store_value_func,
skip_replay=True,
group="Utility",
)
add_builtin(
"load",
input_types={"address": Reference},
hidden=True,
value_func=load_value_func,
group="Utility",
)
def atomic_op_value_func(arg_types, kwds, _):
# check target type
if not is_array(arg_types[0]):
raise RuntimeError("atomic() operation argument 0 must be an array")
num_indices = len(arg_types[1:-1])
num_dims = arg_types[0].ndim
# if this happens we should have generated a view instead of a load during code gen
if num_indices < num_dims:
raise RuntimeError("Num indices < num dimensions for atomic array operation")
if num_indices > num_dims:
raise RuntimeError(
f"Num indices > num dimensions for atomic array operation, received {num_indices}, but array only has {num_dims}"
)
# check index types
for t in arg_types[1:-1]:
if not type_is_int(t):
raise RuntimeError(f"atomic() operation index arguments must be of integer type, got index of type {t}")
if not types_equal(arg_types[-1], arg_types[0].dtype):
raise RuntimeError(
f"atomic() value argument ({arg_types[-1]}) must be of the same type as the array ({arg_types[0].dtype})"
)
return arg_types[0].dtype
for array_type in array_types:
# don't list indexed array operations explicitly in docs
hidden = array_type == indexedarray
add_builtin(
"atomic_add",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically add ``value`` onto ``a[i]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_add",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically add ``value`` onto ``a[i,j]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_add",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically add ``value`` onto ``a[i,j,k]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_add",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "l": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically add ``value`` onto ``a[i,j,k,l]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_sub",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically subtract ``value`` onto ``a[i]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_sub",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically subtract ``value`` onto ``a[i,j]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_sub",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically subtract ``value`` onto ``a[i,j,k]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_sub",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "l": int, "value": Any},
value_func=atomic_op_value_func,
doc="Atomically subtract ``value`` onto ``a[i,j,k,l]``.",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_min",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the minimum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_min",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the minimum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_min",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the minimum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_min",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "l": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the minimum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_max",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the maximum of ``value`` and ``a[i]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_max",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the maximum of ``value`` and ``a[i,j]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_max",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the maximum of ``value`` and ``a[i,j,k]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
add_builtin(
"atomic_max",
hidden=hidden,
input_types={"a": array_type(dtype=Any), "i": int, "j": int, "k": int, "l": int, "value": Any},
value_func=atomic_op_value_func,
doc="""Compute the maximum of ``value`` and ``a[i,j,k,l]`` and atomically update the array.
.. note:: The operation is only atomic on a per-component basis for vectors and matrices.""",
group="Utility",
skip_replay=True,
)
# used to index into builtin types, i.e.: y = vec3[1]
def index_value_func(arg_types, kwds, _):
return arg_types[0]._wp_scalar_type_
add_builtin(
"extract",
input_types={"a": vector(length=Any, dtype=Scalar), "i": int},
value_func=index_value_func,
hidden=True,
group="Utility",
)
add_builtin(
"extract",
input_types={"a": quaternion(dtype=Scalar), "i": int},
value_func=index_value_func,
hidden=True,
group="Utility",
)
add_builtin(
"extract",
input_types={"a": matrix(shape=(Any, Any), dtype=Scalar), "i": int},
value_func=lambda arg_types, kwds, _: vector(length=arg_types[0]._shape_[1], dtype=arg_types[0]._wp_scalar_type_),
hidden=True,
group="Utility",
)
add_builtin(
"extract",
input_types={"a": matrix(shape=(Any, Any), dtype=Scalar), "i": int, "j": int},
value_func=index_value_func,
hidden=True,
group="Utility",
)
add_builtin(
"extract",
input_types={"a": transformation(dtype=Scalar), "i": int},
value_func=index_value_func,
hidden=True,
group="Utility",
)
add_builtin("extract", input_types={"s": shape_t, "i": int}, value_type=int, hidden=True, group="Utility")
def vector_indexref_element_value_func(arg_types, kwds, _):
vec_type = arg_types[0]
# index_type = arg_types[1]
value_type = vec_type._wp_scalar_type_
return Reference(value_type)
# implements &vector[index]
add_builtin(
"index",
input_types={"a": vector(length=Any, dtype=Scalar), "i": int},
value_func=vector_indexref_element_value_func,
hidden=True,
group="Utility",
skip_replay=True,
)
# implements &(*vector)[index]
add_builtin(
"indexref",
input_types={"a": Reference, "i": int},
value_func=vector_indexref_element_value_func,
hidden=True,
group="Utility",
skip_replay=True,
)
def matrix_indexref_element_value_func(arg_types, kwds, _):
mat_type = arg_types[0]
# row_type = arg_types[1]
# col_type = arg_types[2]
value_type = mat_type._wp_scalar_type_
return Reference(value_type)
def matrix_indexref_row_value_func(arg_types, kwds, _):
mat_type = arg_types[0]
row_type = mat_type._wp_row_type_
# value_type = arg_types[2]
return Reference(row_type)
# implements matrix[i] = row
add_builtin(
"index",
input_types={"a": matrix(shape=(Any, Any), dtype=Scalar), "i": int},
value_func=matrix_indexref_row_value_func,
hidden=True,
group="Utility",
skip_replay=True,
)
# implements matrix[i,j] = scalar
add_builtin(
"index",
input_types={"a": matrix(shape=(Any, Any), dtype=Scalar), "i": int, "j": int},
value_func=matrix_indexref_element_value_func,
hidden=True,
group="Utility",
skip_replay=True,
)
for t in scalar_types + vector_types + (bool,):
if "vec" in t.__name__ or "mat" in t.__name__:
continue
add_builtin(
"expect_eq",
input_types={"arg1": t, "arg2": t},
value_type=None,
doc="Prints an error to stdout if ``arg1`` and ``arg2`` are not equal",
group="Utility",
hidden=True,
)
def expect_eq_val_func(arg_types, kwds, _):
if not types_equal(arg_types[0], arg_types[1]):
raise RuntimeError("Can't test equality for objects with different types")
return None
add_builtin(
"expect_eq",
input_types={"arg1": vector(length=Any, dtype=Scalar), "arg2": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=expect_eq_val_func,
doc="Prints an error to stdout if ``arg1`` and ``arg2`` are not equal",
group="Utility",
hidden=True,
)
add_builtin(
"expect_neq",
input_types={"arg1": vector(length=Any, dtype=Scalar), "arg2": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=expect_eq_val_func,
doc="Prints an error to stdout if ``arg1`` and ``arg2`` are equal",
group="Utility",
hidden=True,
)
add_builtin(
"expect_eq",
input_types={"arg1": matrix(shape=(Any, Any), dtype=Scalar), "arg2": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=expect_eq_val_func,
doc="Prints an error to stdout if ``arg1`` and ``arg2`` are not equal",
group="Utility",
hidden=True,
)
add_builtin(
"expect_neq",
input_types={"arg1": matrix(shape=(Any, Any), dtype=Scalar), "arg2": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=expect_eq_val_func,
doc="Prints an error to stdout if ``arg1`` and ``arg2`` are equal",
group="Utility",
hidden=True,
)
add_builtin(
"lerp",
input_types={"a": Float, "b": Float, "t": Float},
value_func=sametype_value_func(Float),
doc="Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``",
group="Utility",
)
add_builtin(
"smoothstep",
input_types={"edge0": Float, "edge1": Float, "x": Float},
value_func=sametype_value_func(Float),
doc="""Smoothly interpolate between two values ``edge0`` and ``edge1`` using a factor ``x``,
and return a result between 0 and 1 using a cubic Hermite interpolation after clamping.""",
group="Utility",
)
def lerp_constraint(arg_types):
return types_equal(arg_types[0], arg_types[1])
def lerp_value_func(default):
def fn(arg_types, kwds, _):
if arg_types is None:
return default
scalar_type = arg_types[-1]
if not lerp_constraint(arg_types):
raise RuntimeError("Can't lerp between objects with different types")
if arg_types[0]._wp_scalar_type_ != scalar_type:
raise RuntimeError("'t' parameter must have the same scalar type as objects you're lerping between")
return arg_types[0]
return fn
add_builtin(
"lerp",
input_types={"a": vector(length=Any, dtype=Float), "b": vector(length=Any, dtype=Float), "t": Float},
constraint=lerp_constraint,
value_func=lerp_value_func(vector(length=Any, dtype=Float)),
doc="Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``",
group="Utility",
)
add_builtin(
"lerp",
input_types={"a": matrix(shape=(Any, Any), dtype=Float), "b": matrix(shape=(Any, Any), dtype=Float), "t": Float},
constraint=lerp_constraint,
value_func=lerp_value_func(matrix(shape=(Any, Any), dtype=Float)),
doc="Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``",
group="Utility",
)
add_builtin(
"lerp",
input_types={"a": quaternion(dtype=Float), "b": quaternion(dtype=Float), "t": Float},
value_func=lerp_value_func(quaternion(dtype=Float)),
doc="Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``",
group="Utility",
)
add_builtin(
"lerp",
input_types={"a": transformation(dtype=Float), "b": transformation(dtype=Float), "t": Float},
value_func=lerp_value_func(transformation(dtype=Float)),
doc="Linearly interpolate two values ``a`` and ``b`` using factor ``t``, computed as ``a*(1-t) + b*t``",
group="Utility",
)
# fuzzy compare for float values
add_builtin(
"expect_near",
input_types={"arg1": Float, "arg2": Float, "tolerance": Float},
defaults={"tolerance": 1.0e-6},
value_type=None,
doc="Prints an error to stdout if ``arg1`` and ``arg2`` are not closer than tolerance in magnitude",
group="Utility",
)
add_builtin(
"expect_near",
input_types={"arg1": vec3, "arg2": vec3, "tolerance": float},
value_type=None,
doc="Prints an error to stdout if any element of ``arg1`` and ``arg2`` are not closer than tolerance in magnitude",
group="Utility",
)
# ---------------------------------
# Algorithms
add_builtin(
"lower_bound",
input_types={"arr": array(dtype=Scalar), "value": Scalar},
value_type=int,
doc="Search a sorted array ``arr`` for the closest element greater than or equal to ``value``.",
)
add_builtin(
"lower_bound",
input_types={"arr": array(dtype=Scalar), "arr_begin": int, "arr_end": int, "value": Scalar},
value_type=int,
doc="Search a sorted array ``arr`` in the range [arr_begin, arr_end) for the closest element greater than or equal to ``value``.",
)
# ---------------------------------
# Operators
add_builtin("add", input_types={"x": Scalar, "y": Scalar}, value_func=sametype_value_func(Scalar), group="Operators")
add_builtin(
"add",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"add",
input_types={"x": quaternion(dtype=Scalar), "y": quaternion(dtype=Scalar)},
value_func=sametype_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"add",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"add",
input_types={"x": transformation(dtype=Scalar), "y": transformation(dtype=Scalar)},
value_func=sametype_value_func(transformation(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin("sub", input_types={"x": Scalar, "y": Scalar}, value_func=sametype_value_func(Scalar), group="Operators")
add_builtin(
"sub",
input_types={"x": vector(length=Any, dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"sub",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=sametypes,
value_func=sametype_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"sub",
input_types={"x": quaternion(dtype=Scalar), "y": quaternion(dtype=Scalar)},
value_func=sametype_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"sub",
input_types={"x": transformation(dtype=Scalar), "y": transformation(dtype=Scalar)},
value_func=sametype_value_func(transformation(dtype=Scalar)),
doc="",
group="Operators",
)
# bitwise operators
add_builtin("bit_and", input_types={"x": Int, "y": Int}, value_func=sametype_value_func(Int))
add_builtin("bit_or", input_types={"x": Int, "y": Int}, value_func=sametype_value_func(Int))
add_builtin("bit_xor", input_types={"x": Int, "y": Int}, value_func=sametype_value_func(Int))
add_builtin("lshift", input_types={"x": Int, "y": Int}, value_func=sametype_value_func(Int))
add_builtin("rshift", input_types={"x": Int, "y": Int}, value_func=sametype_value_func(Int))
add_builtin("invert", input_types={"x": Int}, value_func=sametype_value_func(Int))
def scalar_mul_value_func(default):
def fn(arg_types, kwds, _):
if arg_types is None:
return default
scalar = [t for t in arg_types if t in scalar_types][0]
compound = [t for t in arg_types if t not in scalar_types][0]
if scalar != compound._wp_scalar_type_:
raise RuntimeError("Object and coefficient must have the same scalar type when multiplying by scalar")
return compound
return fn
def mul_matvec_constraint(arg_types):
return arg_types[0]._shape_[1] == arg_types[1]._length_
def mul_matvec_value_func(arg_types, kwds, _):
if arg_types is None:
return vector(length=Any, dtype=Scalar)
if arg_types[0]._wp_scalar_type_ != arg_types[1]._wp_scalar_type_:
raise RuntimeError(
f"Can't multiply matrix and vector with different types {arg_types[0]._wp_scalar_type_}, {arg_types[1]._wp_scalar_type_}"
)
if not mul_matmat_constraint(arg_types):
raise RuntimeError(
f"Can't multiply matrix of shape {arg_types[0]._shape_} and vector with length {arg_types[1]._length_}"
)
return vector(length=arg_types[0]._shape_[0], dtype=arg_types[0]._wp_scalar_type_)
def mul_vecmat_constraint(arg_types):
return arg_types[1]._shape_[0] == arg_types[0]._length_
def mul_vecmat_value_func(arg_types, kwds, _):
if arg_types is None:
return vector(length=Any, dtype=Scalar)
if arg_types[1]._wp_scalar_type_ != arg_types[0]._wp_scalar_type_:
raise RuntimeError(
f"Can't multiply vector and matrix with different types {arg_types[1]._wp_scalar_type_}, {arg_types[0]._wp_scalar_type_}"
)
if not mul_vecmat_constraint(arg_types):
raise RuntimeError(
f"Can't multiply vector with length {arg_types[0]._length_} and matrix of shape {arg_types[1]._shape_}"
)
return vector(length=arg_types[1]._shape_[1], dtype=arg_types[1]._wp_scalar_type_)
def mul_matmat_constraint(arg_types):
return arg_types[0]._shape_[1] == arg_types[1]._shape_[0]
def mul_matmat_value_func(arg_types, kwds, _):
if arg_types is None:
return matrix(length=Any, dtype=Scalar)
if arg_types[0]._wp_scalar_type_ != arg_types[1]._wp_scalar_type_:
raise RuntimeError(
f"Can't multiply matrices with different types {arg_types[0]._wp_scalar_type_}, {arg_types[1]._wp_scalar_type_}"
)
if not mul_matmat_constraint(arg_types):
raise RuntimeError(f"Can't multiply matrix of shapes {arg_types[0]._shape_} and {arg_types[1]._shape_}")
return matrix(shape=(arg_types[0]._shape_[0], arg_types[1]._shape_[1]), dtype=arg_types[0]._wp_scalar_type_)
add_builtin("mul", input_types={"x": Scalar, "y": Scalar}, value_func=sametype_value_func(Scalar), group="Operators")
add_builtin(
"mul",
input_types={"x": vector(length=Any, dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": Scalar, "y": vector(length=Any, dtype=Scalar)},
value_func=scalar_mul_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": quaternion(dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": Scalar, "y": quaternion(dtype=Scalar)},
value_func=scalar_mul_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": quaternion(dtype=Scalar), "y": quaternion(dtype=Scalar)},
value_func=sametype_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": Scalar, "y": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=scalar_mul_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": vector(length=Any, dtype=Scalar)},
constraint=mul_matvec_constraint,
value_func=mul_matvec_value_func,
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": vector(length=Any, dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=mul_vecmat_constraint,
value_func=mul_vecmat_value_func,
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": matrix(shape=(Any, Any), dtype=Scalar)},
constraint=mul_matmat_constraint,
value_func=mul_matmat_value_func,
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": transformation(dtype=Scalar), "y": transformation(dtype=Scalar)},
value_func=sametype_value_func(transformation(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": Scalar, "y": transformation(dtype=Scalar)},
value_func=scalar_mul_value_func(transformation(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"mul",
input_types={"x": transformation(dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(transformation(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin("mod", input_types={"x": Scalar, "y": Scalar}, value_func=sametype_value_func(Scalar), group="Operators")
add_builtin(
"div",
input_types={"x": Scalar, "y": Scalar},
value_func=sametype_value_func(Scalar),
doc="",
group="Operators",
require_original_output_arg=True,
)
add_builtin(
"div",
input_types={"x": vector(length=Any, dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"div",
input_types={"x": Scalar, "y": vector(length=Any, dtype=Scalar)},
value_func=scalar_mul_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"div",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"div",
input_types={"x": Scalar, "y": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=scalar_mul_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"div",
input_types={"x": quaternion(dtype=Scalar), "y": Scalar},
value_func=scalar_mul_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"div",
input_types={"x": Scalar, "y": quaternion(dtype=Scalar)},
value_func=scalar_mul_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"floordiv",
input_types={"x": Scalar, "y": Scalar},
value_func=sametype_value_func(Scalar),
doc="",
group="Operators",
)
add_builtin("pos", input_types={"x": Scalar}, value_func=sametype_value_func(Scalar), group="Operators")
add_builtin(
"pos",
input_types={"x": vector(length=Any, dtype=Scalar)},
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"pos",
input_types={"x": quaternion(dtype=Scalar)},
value_func=sametype_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"pos",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=sametype_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin("neg", input_types={"x": Scalar}, value_func=sametype_value_func(Scalar), group="Operators")
add_builtin(
"neg",
input_types={"x": vector(length=Any, dtype=Scalar)},
value_func=sametype_value_func(vector(length=Any, dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"neg",
input_types={"x": quaternion(dtype=Scalar)},
value_func=sametype_value_func(quaternion(dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin(
"neg",
input_types={"x": matrix(shape=(Any, Any), dtype=Scalar)},
value_func=sametype_value_func(matrix(shape=(Any, Any), dtype=Scalar)),
doc="",
group="Operators",
)
add_builtin("unot", input_types={"b": builtins.bool}, value_type=builtins.bool, doc="", group="Operators")
for t in int_types:
add_builtin("unot", input_types={"b": t}, value_type=builtins.bool, doc="", group="Operators")
add_builtin("unot", input_types={"a": array(dtype=Any)}, value_type=builtins.bool, doc="", group="Operators")
| 122,322 | Python | 32.113969 | 269 | 0.630475 |
NVIDIA/warp/warp/constants.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 math
from warp.types import constant
__all__ = [
"E",
"e",
"INF",
"inf",
"LOG2E",
"log2e",
"LOG10E",
"log10e",
"LN2",
"ln2",
"LN10",
"ln10",
"NAN",
"nan",
"PHI",
"phi",
"PI",
"pi",
"HALF_PI",
"half_pi",
"TAU",
"tau",
]
E = e = constant(2.71828182845904523536) # e
LOG2E = log2e = constant(1.44269504088896340736) # log2(e)
LOG10E = log10e = constant(0.43429448190325182765) # log10(e)
LN2 = ln2 = constant(0.69314718055994530942) # ln(2)
LN10 = ln10 = constant(2.30258509299404568402) # ln(10)
PHI = phi = constant(1.61803398874989484820) # golden constant
PI = pi = constant(3.14159265358979323846) # pi
HALF_PI = half_pi = constant(1.57079632679489661923) # half pi
TAU = tau = constant(6.28318530717958647692) # 2 * pi
INF = inf = constant(math.inf)
NAN = nan = constant(float("nan"))
| 1,321 | Python | 25.439999 | 76 | 0.664648 |
NVIDIA/warp/warp/sparse.py | from typing import Any, Generic, Optional, Tuple, TypeVar, Union
import warp as wp
import warp.types
import warp.utils
from warp.types import Array, Cols, Rows, Scalar, Vector
# typing hints
_BlockType = TypeVar("BlockType")
class _MatrixBlockType(Generic[Rows, Cols, Scalar]):
pass
class _ScalarBlockType(Generic[Scalar]):
pass
BlockType = Union[_MatrixBlockType[Rows, Cols, Scalar], _ScalarBlockType[Scalar]]
_struct_cache = {}
class BsrMatrix(Generic[_BlockType]):
"""Untyped base class for BSR and CSR matrices.
Should not be constructed directly but through functions such as :func:`bsr_zeros`.
Attributes:
nrow (int): Number of rows of blocks
ncol (int): Number of columns of blocks
nnz (int): Number of non-zero blocks: must be equal to ``offsets[nrow-1]``, cached on host for convenience
offsets (Array[int]): Array of size at least ``1 + nrows`` such that the start and end indices of the blocks of row ``r`` are ``offsets[r]`` and ``offsets[r+1]``, respectively.
columns (Array[int]): Array of size at least equal to ``nnz`` containing block column indices
values (Array[BlockType]): Array of size at least equal to ``nnz`` containing block values
"""
@property
def scalar_type(self) -> Scalar:
"""Scalar type for individual block coefficients. For CSR matrices, this is the same as the block type"""
return warp.types.type_scalar_type(self.values.dtype)
@property
def block_shape(self) -> Tuple[int, int]:
"""Shape of the individual blocks"""
return getattr(self.values.dtype, "_shape_", (1, 1))
@property
def block_size(self) -> int:
"""Size of the individual blocks, i.e. number of rows per block times number of columns per block"""
return warp.types.type_length(self.values.dtype)
@property
def shape(self) -> Tuple[int, int]:
"""Shape of the matrix, i.e. number of rows/columns of blocks times number of rows/columns per block"""
block_shape = self.block_shape
return (self.nrow * block_shape[0], self.ncol * block_shape[1])
@property
def dtype(self) -> type:
"""Data type for individual block values"""
return self.values.dtype
@property
def device(self) -> wp.context.Device:
"""Device on which offsets, columns and values are allocated -- assumed to be the same for all three arrays"""
return self.values.device
def bsr_matrix_t(dtype: BlockType):
dtype = wp.types.type_to_warp(dtype)
if not warp.types.type_is_matrix(dtype) and dtype not in warp.types.scalar_types:
raise ValueError(
f"BsrMatrix block type must be either warp matrix or scalar; got {warp.types.type_repr(dtype)}"
)
class BsrMatrixTyped(BsrMatrix):
nrow: int
"""Number of rows of blocks"""
ncol: int
"""Number of columns of blocks"""
nnz: int
"""Number of non-zero blocks: equal to offsets[-1], cached on host for convenience"""
offsets: wp.array(dtype=int)
"""Array of size at least 1 + nrows"""
columns: wp.array(dtype=int)
"""Array of size at least equal to nnz"""
values: wp.array(dtype=dtype)
module = wp.get_module(BsrMatrix.__module__)
if hasattr(dtype, "_shape_"):
type_str = f"{warp.types.type_scalar_type(dtype).__name__}_{dtype._shape_[0]}_{dtype._shape_[1]}"
else:
type_str = dtype.__name__
key = f"{BsrMatrix.__qualname__}_{type_str}"
if key not in _struct_cache:
_struct_cache[key] = wp.codegen.Struct(
cls=BsrMatrixTyped,
key=key,
module=module,
)
return _struct_cache[key]
def bsr_zeros(
rows_of_blocks: int,
cols_of_blocks: int,
block_type: BlockType,
device: wp.context.Devicelike = None,
) -> BsrMatrix:
"""
Constructs and returns an empty BSR or CSR matrix with the given shape
Args:
bsr: The BSR or CSR matrix to set to zero
rows_of_blocks: Number of rows of blocks
cols_of_blocks: Number of columns of blocks
block_type: Type of individual blocks. For CSR matrices, this should be a scalar type;
for BSR matrices, this should be a matrix type (e.g. from :func:`warp.mat`)
device: Device on which to allocate the matrix arrays
"""
bsr = bsr_matrix_t(block_type)()
bsr.nrow = int(rows_of_blocks)
bsr.ncol = int(cols_of_blocks)
bsr.nnz = 0
bsr.columns = wp.empty(shape=(0,), dtype=int, device=device)
bsr.values = wp.empty(shape=(0,), dtype=block_type, device=device)
bsr.offsets = wp.zeros(shape=(bsr.nrow + 1,), dtype=int, device=device)
return bsr
def _bsr_ensure_fits(bsr: BsrMatrix, nrow: int = None, nnz: int = None):
if nrow is None:
nrow = bsr.nrow
if nnz is None:
nnz = bsr.nnz
if bsr.offsets.size < nrow + 1:
bsr.offsets = wp.empty(shape=(nrow + 1,), dtype=int, device=bsr.offsets.device)
if bsr.columns.size < nnz:
bsr.columns = wp.empty(shape=(nnz,), dtype=int, device=bsr.columns.device)
if bsr.values.size < nnz:
bsr.values = wp.empty(shape=(nnz,), dtype=bsr.values.dtype, device=bsr.values.device)
def bsr_set_zero(
bsr: BsrMatrix,
rows_of_blocks: Optional[int] = None,
cols_of_blocks: Optional[int] = None,
):
"""
Sets a BSR matrix to zero, possibly changing its size
Args:
bsr: The BSR or CSR matrix to set to zero
rows_of_blocks: If not ``None``, the new number of rows of blocks
cols_of_blocks: If not ``None``, the new number of columns of blocks
"""
if rows_of_blocks is not None:
bsr.nrow = int(rows_of_blocks)
if cols_of_blocks is not None:
bsr.ncol = int(cols_of_blocks)
bsr.nnz = 0
_bsr_ensure_fits(bsr)
bsr.offsets.zero_()
def bsr_set_from_triplets(
dest: BsrMatrix[BlockType[Rows, Cols, Scalar]],
rows: "Array[int]",
columns: "Array[int]",
values: "Array[Union[Scalar, BlockType[Rows, Cols, Scalar]]]",
):
"""
Fills a BSR matrix with values defined by coordinate-oriented (COO) triplets, discarding existing blocks.
The first dimension of the three input arrays must match, and determines the number of non-zeros in the constructed matrix.
Args:
dest: Sparse matrix to populate
rows: Row index for each non-zero
columns: Columns index for each non-zero
values: Block values for each non-zero. Must be either a one-dimensional array with data type identical
to the `dest` matrix's block type, or a 3d array with data type equal to the `dest` matrix's scalar type.
"""
if values.device != columns.device or values.device != rows.device or values.device != dest.values.device:
raise ValueError("All arguments must reside on the same device")
if values.shape[0] != rows.shape[0] or values.shape[0] != columns.shape[0]:
raise ValueError("All triplet arrays must have the same length")
# Accept either array1d(dtype) or contiguous array3d(scalar_type) as values
if values.ndim == 1:
if values.dtype != dest.values.dtype:
raise ValueError("Values array type must correspond to that of dest matrix")
elif values.ndim == 3:
if values.shape[1:] != dest.block_shape:
raise ValueError(
f"Last two dimensions in values array ({values.shape[1:]}) should correspond to matrix block shape {(dest.block_shape)})"
)
if warp.types.type_scalar_type(values.dtype) != dest.scalar_type:
raise ValueError("Scalar type of values array should correspond to that of matrix")
if not values.is_contiguous:
raise ValueError("Multi-dimensional values array should be contiguous")
else:
raise ValueError("Number of dimension for values array should be 1 or 3")
nnz = rows.shape[0]
if nnz == 0:
bsr_set_zero(dest)
return
# Increase dest array sizes if needed
_bsr_ensure_fits(dest, nnz=nnz)
device = dest.values.device
scalar_type = dest.scalar_type
from warp.context import runtime
if device.is_cpu:
if scalar_type == wp.float32:
native_func = runtime.core.bsr_matrix_from_triplets_float_host
elif scalar_type == wp.float64:
native_func = runtime.core.bsr_matrix_from_triplets_double_host
else:
if scalar_type == wp.float32:
native_func = runtime.core.bsr_matrix_from_triplets_float_device
elif scalar_type == wp.float64:
native_func = runtime.core.bsr_matrix_from_triplets_double_device
if not native_func:
raise NotImplementedError(f"bsr_from_triplets not implemented for scalar type {scalar_type}")
dest.nnz = native_func(
dest.block_shape[0],
dest.block_shape[1],
dest.nrow,
nnz,
rows.ptr,
columns.ptr,
values.ptr,
dest.offsets.ptr,
dest.columns.ptr,
dest.values.ptr,
)
def bsr_assign(
dest: BsrMatrix[BlockType[Rows, Cols, Scalar]],
src: BsrMatrix[BlockType[Rows, Cols, Any]],
):
"""Copies the content of the `src` matrix to `dest`, casting the block values if the two matrices use distinct scalar types."""
if dest.values.device != src.values.device:
raise ValueError("Source and destination matrices must reside on the same device")
if dest.block_shape != src.block_shape:
raise ValueError("Source and destination matrices must have the same block shape")
dest.nrow = src.nrow
dest.ncol = src.ncol
dest.nnz = src.nnz
_bsr_ensure_fits(dest)
wp.copy(dest=dest.offsets, src=src.offsets, count=src.nrow + 1)
if src.nnz > 0:
wp.copy(dest=dest.columns, src=src.columns, count=src.nnz)
warp.utils.array_cast(out_array=dest.values, in_array=src.values, count=src.nnz)
def bsr_copy(A: BsrMatrix, scalar_type: Optional[Scalar] = None):
"""Returns a copy of matrix ``A``, possibly changing its scalar type.
Args:
scalar_type: If provided, the returned matrix will use this scalar type instead of the one from `A`.
"""
if scalar_type is None:
block_type = A.values.dtype
elif A.block_shape == (1, 1):
block_type = scalar_type
else:
block_type = wp.types.matrix(shape=A.block_shape, dtype=scalar_type)
copy = bsr_zeros(
rows_of_blocks=A.nrow,
cols_of_blocks=A.ncol,
block_type=block_type,
device=A.values.device,
)
bsr_assign(dest=copy, src=A)
return copy
def bsr_set_transpose(
dest: BsrMatrix[BlockType[Cols, Rows, Scalar]],
src: BsrMatrix[BlockType[Rows, Cols, Scalar]],
):
"""Assigns the transposed matrix `src` to matrix `dest`"""
if dest.values.device != src.values.device:
raise ValueError("All arguments must reside on the same device")
if dest.scalar_type != src.scalar_type:
raise ValueError("All arguments must have the same scalar type")
transpose_block_shape = src.block_shape[::-1]
if dest.block_shape != transpose_block_shape:
raise ValueError(f"Destination block shape must be {transpose_block_shape}")
dest.nrow = src.ncol
dest.ncol = src.nrow
dest.nnz = src.nnz
if src.nnz == 0:
return
# Increase dest array sizes if needed
_bsr_ensure_fits(dest)
from warp.context import runtime
if dest.values.device.is_cpu:
if dest.scalar_type == wp.float32:
native_func = runtime.core.bsr_transpose_float_host
elif dest.scalar_type == wp.float64:
native_func = runtime.core.bsr_transpose_double_host
else:
if dest.scalar_type == wp.float32:
native_func = runtime.core.bsr_transpose_float_device
elif dest.scalar_type == wp.float64:
native_func = runtime.core.bsr_transpose_double_device
if not native_func:
raise NotImplementedError(f"bsr_set_transpose not implemented for scalar type {dest.scalar_type}")
native_func(
src.block_shape[0],
src.block_shape[1],
src.nrow,
src.ncol,
src.nnz,
src.offsets.ptr,
src.columns.ptr,
src.values.ptr,
dest.offsets.ptr,
dest.columns.ptr,
dest.values.ptr,
)
def bsr_transposed(A: BsrMatrix):
"""Returns a copy of the transposed matrix `A`"""
if A.block_shape == (1, 1):
block_type = A.values.dtype
else:
block_type = wp.types.matrix(shape=A.block_shape[::-1], dtype=A.scalar_type)
transposed = bsr_zeros(
rows_of_blocks=A.ncol,
cols_of_blocks=A.nrow,
block_type=block_type,
device=A.values.device,
)
bsr_set_transpose(dest=transposed, src=A)
return transposed
@wp.kernel
def _bsr_get_diag_kernel(
A_offsets: wp.array(dtype=int),
A_columns: wp.array(dtype=int),
A_values: wp.array(dtype=Any),
out: wp.array(dtype=Any),
):
row = wp.tid()
beg = A_offsets[row]
end = A_offsets[row + 1]
diag = wp.lower_bound(A_columns, beg, end, row)
if diag < end:
if A_columns[diag] == row:
out[row] = A_values[diag]
def bsr_get_diag(A: BsrMatrix[_BlockType], out: "Optional[Array[BlockType]]" = None) -> "Array[BlockType]":
"""Returns the array of blocks that constitute the diagonal of a sparse matrix.
Args:
A: the sparse matrix from which to extract the diagonal
out: if provided, the array into which to store the diagonal blocks
"""
dim = min(A.nrow, A.ncol)
if out is None:
out = wp.zeros(shape=(dim,), dtype=A.values.dtype, device=A.values.device)
else:
if out.dtype != A.values.dtype:
raise ValueError(f"Output array must have type {A.values.dtype}")
if out.device != A.values.device:
raise ValueError(f"Output array must reside on device {A.values.device}")
if out.shape[0] < dim:
raise ValueError(f"Output array must be of length at least {dim}")
wp.launch(
kernel=_bsr_get_diag_kernel,
dim=dim,
device=A.values.device,
inputs=[A.offsets, A.columns, A.values, out],
)
return out
@wp.kernel
def _bsr_set_diag_kernel(
diag: wp.array(dtype=Any),
A_offsets: wp.array(dtype=int),
A_columns: wp.array(dtype=int),
A_values: wp.array(dtype=Any),
):
row = wp.tid()
A_offsets[row + 1] = row + 1
A_columns[row] = row
A_values[row] = diag[row]
if row == 0:
A_offsets[0] = 0
@wp.kernel
def _bsr_set_diag_constant_kernel(
diag_value: Any,
A_offsets: wp.array(dtype=int),
A_columns: wp.array(dtype=int),
A_values: wp.array(dtype=Any),
):
row = wp.tid()
A_offsets[row + 1] = row + 1
A_columns[row] = row
A_values[row] = diag_value
if row == 0:
A_offsets[0] = 0
def bsr_set_diag(
A: BsrMatrix[BlockType],
diag: "Union[BlockType, Array[BlockType]]",
rows_of_blocks: Optional[int] = None,
cols_of_blocks: Optional[int] = None,
):
"""Sets `A` as a block-diagonal matrix
Args:
A: the sparse matrix to modify
diag: Either a warp array of type ``A.values.dtype``, in which case each element will define one block of the diagonal,
or a constant value of type ``A.values.dtype``, in which case it will get assigned to all diagonal blocks.
rows_of_blocks: If not ``None``, the new number of rows of blocks
cols_of_blocks: If not ``None``, the new number of columns of blocks
The shape of the matrix will be defined one of the following, in that order:
- `rows_of_blocks` and `cols_of_blocks`, if provided. If only one is given, the second is assumed equal.
- the first dimension of `diag`, if `diag` is an array
- the current dimensions of `A` otherwise
"""
if rows_of_blocks is None and cols_of_blocks is not None:
rows_of_blocks = cols_of_blocks
if cols_of_blocks is None and rows_of_blocks is not None:
cols_of_blocks = rows_of_blocks
if warp.types.is_array(diag):
if rows_of_blocks is None:
rows_of_blocks = diag.shape[0]
cols_of_blocks = diag.shape[0]
if rows_of_blocks is not None:
A.nrow = rows_of_blocks
A.ncol = cols_of_blocks
A.nnz = min(A.nrow, A.ncol)
_bsr_ensure_fits(A)
if warp.types.is_array(diag):
wp.launch(
kernel=_bsr_set_diag_kernel,
dim=A.nnz,
device=A.values.device,
inputs=[diag, A.offsets, A.columns, A.values],
)
else:
if not warp.types.type_is_value(type(diag)):
# Cast to launchable type
diag = A.values.dtype(diag)
wp.launch(
kernel=_bsr_set_diag_constant_kernel,
dim=A.nnz,
device=A.values.device,
inputs=[diag, A.offsets, A.columns, A.values],
)
def bsr_diag(
diag: "Union[BlockType, Array[BlockType]]",
rows_of_blocks: Optional[int] = None,
cols_of_blocks: Optional[int] = None,
) -> BsrMatrix["BlockType"]:
"""Creates and returns a block-diagonal BSR matrix from an given block value or array of block values.
Args:
diag: Either a warp array of type ``A.values.dtype``, in which case each element will define one block of the diagonal,
or a constant value of type ``A.values.dtype``, in which case it will get assigned to all diagonal blocks.
rows_of_blocks: If not ``None``, the new number of rows of blocks
cols_of_blocks: If not ``None``, the new number of columns of blocks
The shape of the matrix will be defined one of the following, in that order:
- `rows_of_blocks` and `cols_of_blocks`, if provided. If only one is given, the second is assumed equal.
- the first dimension of `diag`, if `diag` is an array
"""
if rows_of_blocks is None and cols_of_blocks is not None:
rows_of_blocks = cols_of_blocks
if cols_of_blocks is None and rows_of_blocks is not None:
cols_of_blocks = rows_of_blocks
if warp.types.is_array(diag):
if rows_of_blocks is None:
rows_of_blocks = diag.shape[0]
cols_of_blocks = diag.shape[0]
A = bsr_zeros(
rows_of_blocks,
cols_of_blocks,
block_type=diag.dtype,
device=diag.device,
)
else:
if rows_of_blocks is None:
raise ValueError(
"rows_of_blocks and/or cols_of_blocks must be provided for constructing a diagonal matrix with uniform diagonal"
)
block_type = type(diag)
if not warp.types.type_is_matrix(block_type) and len(getattr(diag, "shape", ())) == 2:
block_type = wp.mat(shape=diag.shape, dtype=diag.dtype)
A = bsr_zeros(
rows_of_blocks,
cols_of_blocks,
block_type=block_type,
)
bsr_set_diag(A, diag)
return A
def bsr_set_identity(A: BsrMatrix, rows_of_blocks: Optional[int] = None):
"""Sets `A` as the identity matrix
Args:
A: the sparse matrix to modify
rows_of_blocks: if provided, the matrix will be resized as a square matrix with `rows_of_blocks` rows and columns.
"""
if A.block_shape == (1, 1):
identity = A.scalar_type(1.0)
else:
from numpy import eye
identity = eye(A.block_shape[0])
bsr_set_diag(A, diag=identity, rows_of_blocks=rows_of_blocks, cols_of_blocks=rows_of_blocks)
def bsr_identity(
rows_of_blocks: int,
block_type: BlockType[Rows, Rows, Scalar],
device: wp.context.Devicelike = None,
) -> BsrMatrix[BlockType[Rows, Rows, Scalar]]:
"""Creates and returns a square identity matrix.
Args:
rows_of_blocks: Number of rows and columns of blocks in the created matrix.
block_type: Block type for the newly created matrix -- must be square
device: Device onto which to allocate the data arrays
"""
A = bsr_zeros(
rows_of_blocks=rows_of_blocks,
cols_of_blocks=rows_of_blocks,
block_type=block_type,
device=device,
)
bsr_set_identity(A)
return A
@wp.kernel
def _bsr_scale_kernel(
alpha: Any,
values: wp.array(dtype=Any),
):
values[wp.tid()] = alpha * values[wp.tid()]
def bsr_scale(x: BsrMatrix, alpha: Scalar) -> BsrMatrix:
"""
Performs the operation ``x := alpha * x`` on BSR matrix `x` and returns `x`
"""
if alpha != 1.0 and x.nnz > 0:
if alpha == 0.0:
bsr_set_zero(x)
else:
if not isinstance(alpha, x.scalar_type):
alpha = x.scalar_type(alpha)
wp.launch(
kernel=_bsr_scale_kernel,
dim=x.nnz,
device=x.values.device,
inputs=[alpha, x.values],
)
return x
@wp.kernel
def _bsr_get_block_row(dest_offset: int, bsr_offsets: wp.array(dtype=int), rows: wp.array(dtype=int)):
i = wp.tid()
row = wp.lower_bound(bsr_offsets, i + 1) - 1
rows[dest_offset + i] = row
@wp.kernel
def _bsr_axpy_add_block(
src_offset: int,
scale: Any,
rows: wp.array(dtype=int),
cols: wp.array(dtype=int),
dst_offsets: wp.array(dtype=int),
dst_columns: wp.array(dtype=int),
src_values: wp.array(dtype=Any),
dst_values: wp.array(dtype=Any),
):
i = wp.tid()
row = rows[i + src_offset]
col = cols[i + src_offset]
beg = dst_offsets[row]
end = dst_offsets[row + 1]
block = wp.lower_bound(dst_columns, beg, end, col)
dst_values[block] = dst_values[block] + scale * src_values[i]
class bsr_axpy_work_arrays:
"""Opaque structure for persisting :func:`bsr_axpy` temporary work buffers across calls"""
def __init__(self):
self._reset(None)
def _reset(self, device):
self.device = device
self._sum_rows = None
self._sum_cols = None
self._old_y_values = None
self._old_x_values = None
def _allocate(self, device, y: BsrMatrix, sum_nnz: int):
if self.device != device:
self._reset(device)
if self._sum_rows is None or self._sum_rows.size < sum_nnz:
self._sum_rows = wp.empty(shape=(sum_nnz), dtype=int, device=self.device)
if self._sum_cols is None or self._sum_cols.size < sum_nnz:
self._sum_cols = wp.empty(shape=(sum_nnz), dtype=int, device=self.device)
if self._old_y_values is None or self._old_y_values.size < y.nnz:
self._old_y_values = wp.empty(shape=(y.nnz), dtype=y.values.dtype, device=self.device)
def bsr_axpy(
x: BsrMatrix[BlockType[Rows, Cols, Scalar]],
y: Optional[BsrMatrix[BlockType[Rows, Cols, Scalar]]] = None,
alpha: Scalar = 1.0,
beta: Scalar = 1.0,
work_arrays: Optional[bsr_axpy_work_arrays] = None,
) -> BsrMatrix[BlockType[Rows, Cols, Scalar]]:
"""
Performs the sparse matrix addition ``y := alpha * X + beta * y`` on BSR matrices `x` and `y` and returns `y`.
The `x` and `y` matrices are allowed to alias.
Args:
x: Read-only right-hand-side.
y: Mutable left-hand-side. If `y` is not provided, it will be allocated and treated as zero.
alpha: Uniform scaling factor for `x`
beta: Uniform scaling factor for `y`
work_arrays: In most cases this function will require the use of temporary storage; this storage can be reused across calls by passing an instance of :class:`bsr_axpy_work_arrays` in `work_arrays`.
"""
if y is None:
# If not output matrix is provided, allocate it for convenience
y = bsr_zeros(x.nrow, x.ncol, block_type=x.values.dtype, device=x.values.device)
beta = 0.0
# Handle easy cases first
if beta == 0.0 or y.nnz == 0:
bsr_assign(src=x, dest=y)
return bsr_scale(y, alpha=alpha)
if alpha == 0.0 or x.nnz == 0:
return bsr_scale(y, alpha=beta)
if not isinstance(alpha, y.scalar_type):
alpha = y.scalar_type(alpha)
if not isinstance(beta, y.scalar_type):
beta = y.scalar_type(beta)
if x == y:
# Aliasing case
return bsr_scale(y, alpha=alpha.value + beta.value)
# General case
if x.values.device != y.values.device:
raise ValueError("All arguments must reside on the same device")
if x.scalar_type != y.scalar_type or x.block_shape != y.block_shape:
raise ValueError("Matrices must have the same block type")
if x.nrow != y.nrow or x.ncol != y.ncol:
raise ValueError("Matrices must have the same number of rows and columns")
if work_arrays is None:
work_arrays = bsr_axpy_work_arrays()
sum_nnz = x.nnz + y.nnz
device = y.values.device
work_arrays._allocate(device, y, sum_nnz)
wp.copy(work_arrays._sum_cols, y.columns, 0, 0, y.nnz)
wp.launch(
kernel=_bsr_get_block_row,
device=device,
dim=y.nnz,
inputs=[0, y.offsets, work_arrays._sum_rows],
)
wp.copy(work_arrays._sum_cols, x.columns, y.nnz, 0, x.nnz)
wp.launch(
kernel=_bsr_get_block_row,
device=device,
dim=x.nnz,
inputs=[y.nnz, x.offsets, work_arrays._sum_rows],
)
# Save old y values before overwriting matrix
wp.copy(dest=work_arrays._old_y_values, src=y.values, count=y.nnz)
# Increase dest array sizes if needed
if y.columns.shape[0] < sum_nnz:
y.columns = wp.empty(shape=(sum_nnz,), dtype=int, device=device)
from warp.context import runtime
if device.is_cpu:
native_func = runtime.core.bsr_matrix_from_triplets_float_host
else:
native_func = runtime.core.bsr_matrix_from_triplets_float_device
old_y_nnz = y.nnz
y.nnz = native_func(
y.block_shape[0],
y.block_shape[1],
y.nrow,
sum_nnz,
work_arrays._sum_rows.ptr,
work_arrays._sum_cols.ptr,
0,
y.offsets.ptr,
y.columns.ptr,
0,
)
_bsr_ensure_fits(y)
y.values.zero_()
wp.launch(
kernel=_bsr_axpy_add_block,
device=device,
dim=old_y_nnz,
inputs=[
0,
beta,
work_arrays._sum_rows,
work_arrays._sum_cols,
y.offsets,
y.columns,
work_arrays._old_y_values,
y.values,
],
)
wp.launch(
kernel=_bsr_axpy_add_block,
device=device,
dim=x.nnz,
inputs=[
old_y_nnz,
alpha,
work_arrays._sum_rows,
work_arrays._sum_cols,
y.offsets,
y.columns,
x.values,
y.values,
],
)
return y
@wp.kernel
def _bsr_mm_count_coeffs(
z_nnz: int,
x_offsets: wp.array(dtype=int),
x_columns: wp.array(dtype=int),
y_offsets: wp.array(dtype=int),
counts: wp.array(dtype=int),
):
row = wp.tid()
count = int(0)
x_beg = x_offsets[row]
x_end = x_offsets[row + 1]
for x_block in range(x_beg, x_end):
x_col = x_columns[x_block]
count += y_offsets[x_col + 1] - y_offsets[x_col]
counts[row + 1] = count
if row == 0:
counts[0] = z_nnz
@wp.kernel
def _bsr_mm_list_coeffs(
x_offsets: wp.array(dtype=int),
x_columns: wp.array(dtype=int),
y_offsets: wp.array(dtype=int),
y_columns: wp.array(dtype=int),
mm_offsets: wp.array(dtype=int),
mm_rows: wp.array(dtype=int),
mm_cols: wp.array(dtype=int),
):
row = wp.tid()
mm_block = mm_offsets[row]
x_beg = x_offsets[row]
x_end = x_offsets[row + 1]
for x_block in range(x_beg, x_end):
x_col = x_columns[x_block]
y_beg = y_offsets[x_col]
y_end = y_offsets[x_col + 1]
for y_block in range(y_beg, y_end):
mm_cols[mm_block] = y_columns[y_block]
mm_rows[mm_block] = row
mm_block += 1
@wp.kernel
def _bsr_mm_compute_values(
alpha: Any,
x_offsets: wp.array(dtype=int),
x_columns: wp.array(dtype=int),
x_values: wp.array(dtype=Any),
y_offsets: wp.array(dtype=int),
y_columns: wp.array(dtype=int),
y_values: wp.array(dtype=Any),
mm_offsets: wp.array(dtype=int),
mm_cols: wp.array(dtype=int),
mm_values: wp.array(dtype=Any),
):
mm_block = wp.tid()
row = wp.lower_bound(mm_offsets, mm_block + 1) - 1
col = mm_cols[mm_block]
mm_val = mm_values.dtype(type(alpha)(0.0))
x_beg = x_offsets[row]
x_end = x_offsets[row + 1]
for x_block in range(x_beg, x_end):
x_col = x_columns[x_block]
y_beg = y_offsets[x_col]
y_end = y_offsets[x_col + 1]
y_block = wp.lower_bound(y_columns, y_beg, y_end, col)
if y_block < y_end and y_columns[y_block] == col:
mm_val += x_values[x_block] * y_values[y_block]
mm_values[mm_block] += alpha * mm_val
class bsr_mm_work_arrays:
"""Opaque structure for persisting :func:`bsr_mm` temporary work buffers across calls"""
def __init__(self):
self._reset(None)
def _reset(self, device):
self.device = device
self._pinned_count_buffer = None
self._mm_row_counts = None
self._mm_rows = None
self._mm_cols = None
self._old_z_values = None
self._old_z_offsets = None
self._old_z_columns = None
def _allocate_stage_1(self, device, z: BsrMatrix, copied_z_nnz: int, z_aliasing: bool):
if self.device != device:
self._reset(device)
# Allocations that do not depend on any computation
if self.device.is_cuda:
if self._pinned_count_buffer is None:
self._pinned_count_buffer = wp.empty(shape=(1,), dtype=int, pinned=True, device="cpu")
if self._mm_row_counts is None or self._mm_row_counts.size < z.nrow + 1:
self._mm_row_counts = wp.empty(shape=(z.nrow + 1,), dtype=int, device=self.device)
if copied_z_nnz > 0:
if self._old_z_values is None or self._old_z_values.size < copied_z_nnz:
self._old_z_values = wp.empty(shape=(copied_z_nnz,), dtype=z.values.dtype, device=self.device)
if z_aliasing:
if self._old_z_columns is None or self._old_z_columns.size < z.nnz:
self._old_z_columns = wp.empty(shape=(z.nnz,), dtype=z.columns.dtype, device=self.device)
if self._old_z_offsets is None or self._old_z_offsets.size < z.nrow + 1:
self._old_z_offsets = wp.empty(shape=(z.nrow + 1,), dtype=z.offsets.dtype, device=self.device)
def _allocate_stage_2(self, mm_nnz: int):
# Allocations that depend on unmerged nnz estimate
if self._mm_rows is None or self._mm_rows.size < mm_nnz:
self._mm_rows = wp.empty(shape=(mm_nnz,), dtype=int, device=self.device)
if self._mm_cols is None or self._mm_cols.size < mm_nnz:
self._mm_cols = wp.empty(shape=(mm_nnz,), dtype=int, device=self.device)
def bsr_mm(
x: BsrMatrix[BlockType[Rows, Any, Scalar]],
y: BsrMatrix[BlockType[Any, Cols, Scalar]],
z: Optional[BsrMatrix[BlockType[Rows, Cols, Scalar]]] = None,
alpha: Scalar = 1.0,
beta: Scalar = 0.0,
work_arrays: Optional[bsr_mm_work_arrays] = None,
) -> BsrMatrix[BlockType[Rows, Cols, Scalar]]:
"""
Performs the sparse matrix-matrix multiplication ``z := alpha * x * y + beta * z`` on BSR matrices `x`, `y` and `z`, and returns `z`.
The `x`, `y` and `z` matrices are allowed to alias.
If the matrix `z` is not provided as input, it will be allocated and treated as zero.
Args:
x: Read-only left factor of the matrix-matrix product.
y: Read-only right factor of the matrix-matrix product.
z: Mutable left-hand-side. If `z` is not provided, it will be allocated and treated as zero.
alpha: Uniform scaling factor for the ``x * y`` product
beta: Uniform scaling factor for `z`
work_arrays: In most cases this function will require the use of temporary storage; this storage can be reused across calls by passing an instance of :class:`bsr_mm_work_arrays` in `work_arrays`.
"""
if z is None:
# If not output matrix is provided, allocate it for convenience
z_block_shape = (x.block_shape[0], y.block_shape[1])
if z_block_shape == (1, 1):
z_block_type = x.scalar_type
else:
z_block_type = wp.types.matrix(shape=z_block_shape, dtype=x.scalar_type)
z = bsr_zeros(x.nrow, y.ncol, block_type=z_block_type, device=x.values.device)
beta = 0.0
if x.values.device != y.values.device or x.values.device != z.values.device:
raise ValueError("All arguments must reside on the same device")
if x.scalar_type != y.scalar_type or x.scalar_type != z.scalar_type:
raise ValueError("Matrices must have the same scalar type")
if (
x.block_shape[0] != z.block_shape[0]
or y.block_shape[1] != z.block_shape[1]
or x.block_shape[1] != y.block_shape[0]
):
raise ValueError("Incompatible block sizes for matrix multiplication")
if x.nrow != z.nrow or z.ncol != y.ncol or x.ncol != y.nrow:
raise ValueError("Incompatible number of rows/columns for matrix multiplication")
device = z.values.device
if alpha == 0.0 or x.nnz == 0 or y.nnz == 0:
# Easy case
return bsr_scale(z, beta)
if not isinstance(alpha, z.scalar_type):
alpha = z.scalar_type(alpha)
if not isinstance(beta, z.scalar_type):
beta = z.scalar_type(beta)
if work_arrays is None:
work_arrays = bsr_mm_work_arrays()
z_aliasing = z == x or z == y
copied_z_nnz = z.nnz if beta != 0.0 or z_aliasing else 0
work_arrays._allocate_stage_1(device, z, copied_z_nnz, z_aliasing)
# Prefix sum of number of (unmerged) mm blocks per row
wp.launch(
kernel=_bsr_mm_count_coeffs,
device=device,
dim=z.nrow,
inputs=[
copied_z_nnz,
x.offsets,
x.columns,
y.offsets,
work_arrays._mm_row_counts,
],
)
warp.utils.array_scan(work_arrays._mm_row_counts, work_arrays._mm_row_counts)
# Get back total counts on host
if device.is_cuda:
wp.copy(
dest=work_arrays._pinned_count_buffer,
src=work_arrays._mm_row_counts,
src_offset=z.nrow,
count=1,
)
wp.synchronize_stream(wp.get_stream(device))
mm_nnz = int(work_arrays._pinned_count_buffer.numpy()[0])
else:
mm_nnz = int(work_arrays._mm_row_counts.numpy()[z.nrow])
work_arrays._allocate_stage_2(mm_nnz)
# If z has a non-zero scale, save current data before overwriting it
if copied_z_nnz > 0:
# Copy z row and column indices
wp.copy(dest=work_arrays._mm_cols, src=z.columns, count=copied_z_nnz)
wp.launch(
kernel=_bsr_get_block_row,
device=device,
dim=copied_z_nnz,
inputs=[0, z.offsets, work_arrays._mm_rows],
)
# Save current z values in temporary buffer
wp.copy(src=z.values, dest=work_arrays._old_z_values, count=copied_z_nnz)
if z_aliasing:
# If z is aliasing with x or y, need to save topology as well
wp.copy(src=z.columns, dest=work_arrays._old_z_columns, count=copied_z_nnz)
wp.copy(src=z.offsets, dest=work_arrays._old_z_offsets, count=z.nrow + 1)
# Fill unmerged mm blocks rows and columns
wp.launch(
kernel=_bsr_mm_list_coeffs,
device=device,
dim=z.nrow,
inputs=[
x.offsets,
x.columns,
y.offsets,
y.columns,
work_arrays._mm_row_counts,
work_arrays._mm_rows,
work_arrays._mm_cols,
],
)
# Increase dest array size if needed
if z.columns.shape[0] < mm_nnz:
z.columns = wp.empty(shape=(mm_nnz,), dtype=int, device=device)
from warp.context import runtime
if device.is_cpu:
native_func = runtime.core.bsr_matrix_from_triplets_float_host
else:
native_func = runtime.core.bsr_matrix_from_triplets_float_device
z.nnz = native_func(
z.block_shape[0],
z.block_shape[1],
z.nrow,
mm_nnz,
work_arrays._mm_rows.ptr,
work_arrays._mm_cols.ptr,
0,
z.offsets.ptr,
z.columns.ptr,
0,
)
_bsr_ensure_fits(z)
z.values.zero_()
if copied_z_nnz > 0:
# Add back original z values
wp.launch(
kernel=_bsr_axpy_add_block,
device=device,
dim=copied_z_nnz,
inputs=[
0,
beta,
work_arrays._mm_rows,
work_arrays._mm_cols,
z.offsets,
z.columns,
work_arrays._old_z_values,
z.values,
],
)
# Add mm blocks to z values
if (warp.types.type_is_matrix(x.values.dtype) or warp.types.type_is_matrix(y.values.dtype)) and not (
warp.types.type_is_matrix(z.values.dtype)
):
# Result block type is scalar, but operands are matrices
# Cast result to (1x1) matrix to perform multiplication
mm_values = z.values.view(wp.types.matrix(shape=(1, 1), dtype=z.scalar_type))
else:
mm_values = z.values
wp.launch(
kernel=_bsr_mm_compute_values,
device=device,
dim=z.nnz,
inputs=[
alpha,
work_arrays._old_z_offsets if x == z else x.offsets,
work_arrays._old_z_columns if x == z else x.columns,
work_arrays._old_z_values if x == z else x.values,
work_arrays._old_z_offsets if y == z else y.offsets,
work_arrays._old_z_columns if y == z else y.columns,
work_arrays._old_z_values if y == z else y.values,
z.offsets,
z.columns,
mm_values,
],
)
return z
@wp.kernel
def _bsr_mv_kernel(
alpha: Any,
A_offsets: wp.array(dtype=int),
A_columns: wp.array(dtype=int),
A_values: wp.array(dtype=Any),
x: wp.array(dtype=Any),
beta: Any,
y: wp.array(dtype=Any),
):
row = wp.tid()
# zero-initialize with type of y elements
scalar_zero = type(alpha)(0)
v = y.dtype(scalar_zero)
if alpha != scalar_zero:
beg = A_offsets[row]
end = A_offsets[row + 1]
for block in range(beg, end):
v += A_values[block] * x[A_columns[block]]
v *= alpha
if beta != scalar_zero:
v += beta * y[row]
y[row] = v
def bsr_mv(
A: BsrMatrix[BlockType[Rows, Cols, Scalar]],
x: "Array[Vector[Cols, Scalar] | Scalar]",
y: Optional["Array[Vector[Rows, Scalar] | Scalar]"] = None,
alpha: Scalar = 1.0,
beta: Scalar = 0.0,
work_buffer: Optional["Array[Vector[Rows, Scalar] | Scalar]"] = None,
) -> "Array[Vector[Rows, Scalar] | Scalar]":
"""
Performs the sparse matrix-vector product ``y := alpha * A * x + beta * y`` and returns `y`.
The `x` and `y` vectors are allowed to alias.
Args:
A: Read-only, left matrix factor of the matrix-vector product.
x: Read-only, right vector factor of the matrix-vector product.
y: Mutable left-hand-side. If `y` is not provided, it will be allocated and treated as zero.
alpha: Uniform scaling factor for `x`. If zero, `x` will not be read and may be left uninitialized.
beta: Uniform scaling factor for `y`. If zero, `y` will not be read and may be left uninitialized.
work_buffer: Temporary storage is required if and only if `x` and `y` are the same vector. If provided the `work_buffer` array
will be used for this purpose, otherwise a temporary allocation will be performed.
"""
if y is None:
# If no output array is provided, allocate one for convenience
y_vec_len = A.block_shape[0]
y_dtype = A.scalar_type if y_vec_len == 1 else wp.vec(length=y_vec_len, dtype=A.scalar_type)
y = wp.empty(shape=(A.nrow,), device=A.values.device, dtype=y_dtype)
y.zero_()
beta = 0.0
if not isinstance(alpha, A.scalar_type):
alpha = A.scalar_type(alpha)
if not isinstance(beta, A.scalar_type):
beta = A.scalar_type(beta)
if A.values.device != x.device or A.values.device != y.device:
raise ValueError("A, x and y must reside on the same device")
if x.shape[0] != A.ncol:
raise ValueError("Number of columns of A must match number of rows of x")
if y.shape[0] != A.nrow:
raise ValueError("Number of rows of A must match number of rows of y")
if x == y:
# Aliasing case, need temporary storage
if work_buffer is None:
work_buffer = wp.empty_like(y)
elif work_buffer.size < y.size:
raise ValueError(f"Work buffer size is insufficient, needs to be at least {y.size}")
elif not wp.types.types_equal(work_buffer.dtype, y.dtype):
raise ValueError(f"Work buffer must have same data type as y, {wp.types.type_repr(y.dtype)}")
# Save old y values before overwriting vector
wp.copy(dest=work_buffer, src=y, count=y.size)
x = work_buffer
# Promote scalar vectors to length-1 vecs and conversely
if warp.types.type_is_matrix(A.values.dtype):
if A.block_shape[0] == 1:
if y.dtype == A.scalar_type:
y = y.view(dtype=wp.vec(length=1, dtype=A.scalar_type))
if A.block_shape[1] == 1:
if x.dtype == A.scalar_type:
x = x.view(dtype=wp.vec(length=1, dtype=A.scalar_type))
else:
if A.block_shape[0] == 1:
if y.dtype != A.scalar_type:
y = y.view(dtype=A.scalar_type)
if A.block_shape[1] == 1:
if x.dtype != A.scalar_type:
x = x.view(dtype=A.scalar_type)
wp.launch(
kernel=_bsr_mv_kernel,
device=A.values.device,
dim=A.nrow,
inputs=[alpha, A.offsets, A.columns, A.values, x, beta, y],
)
return y
| 42,356 | Python | 31.834884 | 205 | 0.603645 |
NVIDIA/warp/warp/tape.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 collections import defaultdict, namedtuple
from typing import Dict, List
import warp as wp
class Tape:
"""
Record kernel launches within a Tape scope to enable automatic differentiation.
Gradients can be computed after the operations have been recorded on the tape via
``tape.backward()``.
Example
-------
.. code-block:: python
tape = wp.Tape()
# forward pass
with tape:
wp.launch(kernel=compute1, inputs=[a, b], device="cuda")
wp.launch(kernel=compute2, inputs=[c, d], device="cuda")
wp.launch(kernel=loss, inputs=[d, l], device="cuda")
# reverse pass
tape.backward(l)
Gradients can be accessed via the ``tape.gradients`` dictionary, e.g.:
.. code-block:: python
print(tape.gradients[a])
"""
def __init__(self):
self.gradients = {}
self.const_gradients = set()
self.launches = []
self.scopes = []
self.loss = None
def __enter__(self):
if wp.context.runtime.tape is not None:
raise RuntimeError("Warp: Error, entering a tape while one is already active")
wp.context.runtime.tape = self
return self
def __exit__(self, exc_type, exc_value, traceback):
if wp.context.runtime.tape is None:
raise RuntimeError("Warp: Error, ended tape capture, but tape not present")
wp.context.runtime.tape = None
# adj_outputs is a mapping from output tensor -> adjoint of the output
# after running backward the gradients of tensors may be retrieved by:
#
# adj_tensor = tape.gradients[tensor]
#
def backward(self, loss: wp.array = None, grads: dict = None):
"""
Evaluate the backward pass of the recorded operations on the tape.
A single-element array ``loss`` or a dictionary of arrays ``grads``
can be provided to assign the incoming gradients for the reverse-mode
automatic differentiation pass.
Args:
loss (wp.array): A single-element array that holds the loss function value whose gradient is to be computed
grads (dict): A dictionary of arrays that map from Warp arrays to their incoming gradients
"""
# if scalar loss is specified then initialize
# a 'seed' array for it, with gradient of one
if loss:
if loss.size > 1 or wp.types.type_length(loss.dtype) > 1:
raise RuntimeError("Can only return gradients for scalar loss functions.")
if not loss.requires_grad:
raise RuntimeError(
"Scalar loss arrays should have requires_grad=True set before calling Tape.backward()"
)
# set the seed grad to 1.0
loss.grad.fill_(1.0)
# simply apply dict grads to objects
# this is just for backward compat. with
# existing code before we added wp.array.grad attribute
if grads:
for a, g in grads.items():
if a.grad is None:
a.grad = g
else:
# ensure we can capture this backward pass in a CUDA graph
a.grad.assign(g)
self.const_gradients.add(a)
# run launches backwards
for launch in reversed(self.launches):
if callable(launch):
launch()
else:
# kernel option takes precedence over module option
kernel_enable_backward = launch[0].options.get("enable_backward")
if kernel_enable_backward is False:
msg = f"Running the tape backwards may produce incorrect gradients because recorded kernel {launch[0].key} is configured with the option 'enable_backward=False'."
wp.utils.warn(msg)
elif kernel_enable_backward is None:
module_enable_backward = launch[0].module.options.get("enable_backward")
if module_enable_backward is False:
msg = f"Running the tape backwards may produce incorrect gradients because recorded kernel {launch[0].key} is defined in a module with the option 'enable_backward=False' set."
wp.utils.warn(msg)
kernel = launch[0]
dim = launch[1]
max_blocks = launch[2]
inputs = launch[3]
outputs = launch[4]
device = launch[5]
adj_inputs = []
adj_outputs = []
# lookup adjoint inputs
for a in inputs:
adj_inputs.append(self.get_adjoint(a))
# lookup adjoint outputs, todo: only allocate outputs if necessary
for a in outputs:
adj_outputs.append(self.get_adjoint(a))
wp.launch(
kernel=kernel,
dim=dim,
inputs=inputs,
outputs=outputs,
adj_inputs=adj_inputs,
adj_outputs=adj_outputs,
device=device,
adjoint=True,
max_blocks=max_blocks,
)
# record a kernel launch on the tape
def record_launch(self, kernel, dim, max_blocks, inputs, outputs, device, metadata=None):
if metadata is None:
metadata = {}
self.launches.append([kernel, dim, max_blocks, inputs, outputs, device, metadata])
def record_func(self, backward, arrays):
"""
Records a custom function to be executed only in the backward pass.
Args:
backward (Callable): A callable Python object (can be any function) that will be executed in the backward pass.
arrays (list): A list of arrays that are used by the function for gradient tracking.
"""
self.launches.append(backward)
for a in arrays:
if isinstance(a, wp.array) and a.grad:
self.gradients[a] = a.grad
else:
raise RuntimeError(
f"Array {a} is not of type wp.array or is missing a gradient array. Set array parameter requires_grad=True during instantiation."
)
def record_scope_begin(self, scope_name, metadata=None):
"""
Begin a scope on the tape to group operations together. Scopes are only used in the visualization functions.
"""
if metadata is None:
metadata = {}
self.scopes.append((len(self.launches), scope_name, metadata))
def record_scope_end(self, remove_scope_if_empty=True):
"""
End a scope on the tape.
Args:
remove_scope_if_empty (bool): If True, the scope will be removed if no kernel launches were recorded within it.
"""
if remove_scope_if_empty and self.scopes[-1][0] == len(self.launches):
self.scopes = self.scopes[:-1]
else:
self.scopes.append((len(self.launches), None, None))
# returns the adjoint of a kernel parameter
def get_adjoint(self, a):
if not wp.types.is_array(a) and not isinstance(a, wp.codegen.StructInstance):
# if input is a simple type (e.g.: float, vec3, etc) then
# no gradient needed (we only return gradients through arrays and structs)
return a
elif wp.types.is_array(a) and a.grad:
# keep track of all gradients used by the tape (for zeroing)
# ignore the scalar loss since we don't want to clear its grad
self.gradients[a] = a.grad
return a.grad
elif isinstance(a, wp.codegen.StructInstance):
adj = a._cls()
for name, _ in a._cls.ctype._fields_:
if name.startswith("_"):
continue
if isinstance(a._cls.vars[name].type, wp.array):
arr = getattr(a, name)
if arr.grad:
grad = self.gradients[arr] = arr.grad
else:
grad = None
setattr(adj, name, grad)
else:
setattr(adj, name, getattr(a, name))
self.gradients[a] = adj
return adj
return None
def reset(self):
"""
Clear all operations recorded on the tape and zero out all gradients.
"""
self.launches = []
self.scopes = []
self.zero()
def zero(self):
"""
Zero out all gradients recorded on the tape.
"""
for a, g in self.gradients.items():
if a not in self.const_gradients:
if isinstance(a, wp.codegen.StructInstance):
for name in g._cls.vars:
if isinstance(g._cls.vars[name].type, wp.array) and g._cls.vars[name].requires_grad:
getattr(g, name).zero_()
else:
g.zero_()
def visualize(
self,
filename: str = None,
simplify_graph=True,
hide_readonly_arrays=False,
array_labels: Dict[wp.array, str] = None,
choose_longest_node_name: bool = True,
ignore_graph_scopes: bool = False,
track_inputs: List[wp.array] = None,
track_outputs: List[wp.array] = None,
track_input_names: List[str] = None,
track_output_names: List[str] = None,
graph_direction: str = "LR",
) -> str:
"""
Visualize the recorded operations on the tape as a `GraphViz diagram <https://graphviz.org/>`_.
Example
-------
.. code-block:: python
import warp as wp
tape = wp.Tape()
with tape:
# record Warp kernel launches here
wp.launch(...)
dot_code = tape.visualize("tape.dot")
This function creates a GraphViz dot file that can be rendered into an image using the GraphViz command line tool, e.g. via
.. code-block:: bash
dot -Tpng tape.dot -o tape.png
Args:
filename (str): The filename to save the visualization to (optional).
simplify_graph (bool): If True, simplify the graph by detecting repeated kernel launch sequences and summarizing them in subgraphs.
hide_readonly_arrays (bool): If True, hide arrays that are not modified by any kernel launch.
array_labels (Dict[wp.array, str]): A dictionary mapping arrays to custom labels.
choose_longest_node_name (bool): If True, the automatic name resolution will aim to find the longest name for each array in the computation graph.
ignore_graph_scopes (bool): If True, ignore the scopes recorded on the tape when visualizing the graph.
track_inputs (List[wp.array]): A list of arrays to track as inputs in the graph to ensure they are shown regardless of the `hide_readonly_arrays` setting.
track_outputs (List[wp.array]): A list of arrays to track as outputs in the graph so that they remain visible.
track_input_names (List[str]): A list of custom names for the input arrays to track in the graph (used in conjunction with `track_inputs`).
track_output_names (List[str]): A list of custom names for the output arrays to track in the graph (used in conjunction with `track_outputs`).
graph_direction (str): The direction of the graph layout (default: "LR").
Returns:
str: The dot code representing the graph.
"""
if track_output_names is None:
track_output_names = []
if track_input_names is None:
track_input_names = []
if track_outputs is None:
track_outputs = []
if track_inputs is None:
track_inputs = []
if array_labels is None:
array_labels = {}
return visualize_tape_graphviz(
self,
filename,
simplify_graph,
hide_readonly_arrays,
array_labels,
choose_longest_node_name,
ignore_graph_scopes,
track_inputs,
track_outputs,
track_input_names,
track_output_names,
graph_direction,
)
class TapeVisitor:
def emit_array_node(self, arr: wp.array, label: str, active_scope_stack: List[str], indent_level: int):
pass
def emit_kernel_launch_node(
self, kernel: wp.Kernel, kernel_launch_id: str, launch_data: dict, rendered: bool, indent_level: int
):
pass
def emit_edge_array_kernel(self, arr: wp.array, kernel_launch_id: str, kernel_input_id: int, indent_level: int):
pass
def emit_edge_kernel_array(self, kernel_launch_id: str, kernel_output_id: int, arr: wp.array, indent_level: int):
pass
def emit_edge_array_array(self, src: wp.array, dst: wp.array, indent_level: int):
pass
def emit_scope_begin(self, active_scope_id: int, active_scope_name: str, metadata: dict, indent_level: int):
pass
def emit_scope_end(self, indent_level: int):
pass
def get_struct_vars(x: wp.codegen.StructInstance):
return {varname: getattr(x, varname) for varname, _ in x._cls.ctype._fields_}
class GraphvizTapeVisitor(TapeVisitor):
def __init__(self):
self.graphviz_lines = []
self.indent_str = "\t"
self.scope_classes = {}
self.max_indent = 0
# mapping from array pointer to kernel:port ID
self.pointer_to_port = {}
# set of inserted edges between kernel:port IDs
self.edges = set()
# set of inserted array nodes
self.array_nodes = set()
@staticmethod
def sanitize(s):
return (
s.replace("\n", " ")
.replace('"', " ")
.replace("'", " ")
.replace("[", "[")
.replace("]", "]")
.replace("`", "`")
.replace(":", ":")
.replace("\\", "\\\\")
.replace("/", "/")
.replace("(", "(")
.replace(")", ")")
.replace(",", "")
.replace("{", "{")
.replace("}", "}")
.replace("<", "<")
.replace(">", ">")
)
@staticmethod
def dtype2str(dtype):
type_str = str(dtype)
if hasattr(dtype, "key"):
type_str = dtype.key
elif "'" in type_str:
type_str = type_str.split("'")[1]
return type_str
def emit_array_node(self, arr: wp.array, label: str, active_scope_stack: List[str], indent_level: int):
if arr.ptr in self.array_nodes:
return
if arr.ptr in self.pointer_to_port:
return
self.array_nodes.add(arr.ptr)
color = "lightgray"
if arr.requires_grad:
color = "#76B900"
options = [
f'label="{label}"',
"shape=ellipse",
"style=filled",
f'fillcolor="{color}"',
]
chart_indent = self.indent_str * indent_level
arr_id = f"arr{arr.ptr}"
type_str = self.dtype2str(arr.dtype)
# type_str = self.sanitize(type_str)
# class_name = "array" if not arr.requires_grad else "array_grad"
# self.graphviz_lines.append(chart_indent + f'{arr_id}(["`{label}`"]):::{class_name}')
tooltip = f"Array {label} / ptr={arr.ptr}, shape={str(arr.shape)}, dtype={type_str}, requires_grad={arr.requires_grad}"
options.append(f'tooltip="{tooltip}"')
# self.graphviz_lines.append(chart_indent + f'click {arr_id} callback "{tooltip}"')
# self.max_indent = max(self.max_indent, indent_level)
self.graphviz_lines.append(f"{chart_indent}{arr_id} [{','.join(options)}];")
def emit_kernel_launch_node(
self, kernel: wp.Kernel, kernel_launch_id: str, launch_data: dict, rendered: bool, indent_level: int
):
if not rendered:
return
chart_indent = self.indent_str * indent_level
table = []
table.append(
'<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" border="0" cellspacing="2" cellpadding="4" bgcolor="#888888" gradientangle="0">'
)
table.append(f'<TR><TD BGCOLOR="#ffffffaa" colspan="2" align="center"><b>{kernel.key}</b></TD></TR>')
num_inputs = len(launch_data["inputs"])
num_outputs = len(launch_data["outputs"])
nrows = max(num_inputs, num_outputs)
nargs = len(kernel.adj.args)
for i in range(nrows):
row = []
if i < num_inputs:
arg = kernel.adj.args[i]
port_id = f"in_{i}"
if isinstance(arg.type, wp.array):
tooltip = f"array: dtype={self.dtype2str(arg.type.dtype)}"
else:
tooltip = f"dtype={self.sanitize(self.dtype2str(arg.type))}"
row.append(
f'<TD PORT="{port_id}" BGCOLOR="#BBBBBB" align="left" title="{tooltip}"><font color="black">{arg.label}</font></TD>'
)
launch_data["inputs"][i]
# if var is not None and isinstance(var, wp.array):
# self.pointer_to_port[var.ptr] = f"{kernel_launch_id}:{port_id}"
else:
row.append('<TD BORDER="0"></TD>')
# if i >= nargs - 1:
# row.append('<TD></TD>')
# table.append(f'<TR>{row[0]}{row[1]}</TR>')
# break
if i < num_outputs and i + num_inputs < nargs:
arg = kernel.adj.args[i + num_inputs].label
port_id = f"out_{i}"
row.append(
f'<TD PORT="{port_id}" BGCOLOR="#BBBBBB" align="right"><font color="black">{arg}</font></TD>'
)
launch_data["outputs"][i]
# if var is not None and isinstance(var, wp.array):
# self.pointer_to_port[var.ptr] = f"{kernel_launch_id}:{port_id}"
else:
row.append('<TD BORDER="0"></TD>')
table.append(f"<TR>{row[0]}{row[1]}</TR>")
table.append("</TABLE>")
label = f"{chart_indent}\n".join(table)
node_attrs = f"label=<{label}>"
if "caller" in launch_data:
caller = launch_data["caller"]
node_attrs += f",tooltip=\"{self.sanitize(caller['file'])}:{caller['lineno']} ({caller['func']})\""
self.graphviz_lines.append(f"{chart_indent}{kernel_launch_id} [{node_attrs}];")
def emit_edge_array_kernel(self, arr_ptr: int, kernel_launch_id: str, kernel_input_id: int, indent_level: int):
chart_indent = self.indent_str * indent_level
if arr_ptr in self.pointer_to_port:
arr_id = self.pointer_to_port[arr_ptr]
elif arr_ptr in self.array_nodes:
arr_id = f"arr{arr_ptr}"
else:
return
target_id = f"{kernel_launch_id}:in_{kernel_input_id}"
if (arr_id, target_id) in self.edges:
return
self.edges.add((arr_id, target_id))
self.graphviz_lines.append(f"{chart_indent}{arr_id} -> {target_id}")
def emit_edge_kernel_array(self, kernel_launch_id: str, kernel_output_id: int, arr_ptr: int, indent_level: int):
chart_indent = self.indent_str * indent_level
if arr_ptr in self.pointer_to_port:
arr_id = self.pointer_to_port[arr_ptr]
elif arr_ptr in self.array_nodes:
arr_id = f"arr{arr_ptr}"
else:
return
source_id = f"{kernel_launch_id}:out_{kernel_output_id}"
if (source_id, arr_id) in self.edges:
return
self.edges.add((source_id, arr_id))
self.graphviz_lines.append(f"{chart_indent}{source_id} -> {arr_id};")
def emit_edge_array_array(self, src: wp.array, dst: wp.array, indent_level: int):
chart_indent = self.indent_str * indent_level
src_id = f"arr{src.ptr}"
dst_id = f"arr{dst.ptr}"
if (src_id, dst_id) in self.edges:
return
self.edges.add((src_id, dst_id))
self.graphviz_lines.append(f'{chart_indent}{src_id} -> {dst_id} [color="#0072B9",constraint=false];')
def emit_scope_begin(self, active_scope_id: int, active_scope_name: str, metadata: dict, indent_level: int):
chart_indent = self.indent_str * indent_level
scope_key = f"cluster{active_scope_id}"
scope_class = metadata.get("type", "scope")
self.graphviz_lines.append(f"{chart_indent}subgraph {scope_key} {{")
chart_indent += self.indent_str
self.graphviz_lines.append(f'{chart_indent}style="rounded,filled";')
if scope_class == "scope":
self.graphviz_lines.append(f'{chart_indent}fillcolor="#76B90022";')
self.graphviz_lines.append(f'{chart_indent}pencolor="#76B900";')
else:
self.graphviz_lines.append(f'{chart_indent}fillcolor="#0072B922";')
self.graphviz_lines.append(f'{chart_indent}pencolor="#0072B9";')
self.graphviz_lines.append(f"{chart_indent}label=<<b>{active_scope_name}</b>>;\n")
def emit_scope_end(self, indent_level: int):
chart_indent = self.indent_str * indent_level
self.graphviz_lines.append(f"{chart_indent}}};\n")
class ArrayStatsVisitor(TapeVisitor):
ArrayState = namedtuple("ArrayState", ["mean", "std", "min", "max"])
def __init__(self):
self.array_names = {}
self.launch_data = {}
self.launches = []
self.array_value_stats = []
self.array_grad_stats = []
def emit_array_node(self, arr: wp.array, label: str, active_scope_stack: List[str], indent_level: int):
if arr.device.is_capturing:
raise RuntimeError("Cannot record arrays while graph capturing is active.")
self.array_names[arr.ptr] = label
def emit_kernel_launch_node(
self, kernel: wp.Kernel, kernel_launch_id: str, launch_data: dict, rendered: bool, indent_level: int
):
self.launch_data[kernel_launch_id] = launch_data
self.launches.append(kernel_launch_id)
value_stats = {}
grad_stats = {}
for output in launch_data["outputs"]:
if isinstance(output, wp.array):
arr_np = output.numpy()
value_stats[output.ptr] = self.ArrayState(
mean=arr_np.mean(), std=arr_np.std(), min=arr_np.min(), max=arr_np.max()
)
for input in launch_data["inputs"]:
if isinstance(input, wp.array) and input.requires_grad and input.grad is not None:
arr_np = input.grad.numpy()
grad_stats[input.ptr] = self.ArrayState(
mean=arr_np.mean(), std=arr_np.std(), min=arr_np.min(), max=arr_np.max()
)
self.array_value_stats.append(value_stats)
self.array_grad_stats.insert(0, grad_stats)
Launch = namedtuple("Launch", ["id", "kernel", "dim", "max_blocks", "inputs", "outputs", "device", "metadata"])
RepeatedSequence = namedtuple("RepeatedSequence", ["start", "end", "repetitions"])
def visit_tape(
tape: Tape,
visitor: TapeVisitor,
simplify_graph=True,
hide_readonly_arrays=False,
array_labels: Dict[wp.array, str] = None,
choose_longest_node_name: bool = True,
ignore_graph_scopes: bool = False,
track_inputs: List[wp.array] = None,
track_outputs: List[wp.array] = None,
track_input_names: List[str] = None,
track_output_names: List[str] = None,
):
if track_output_names is None:
track_output_names = []
if track_input_names is None:
track_input_names = []
if track_outputs is None:
track_outputs = []
if track_inputs is None:
track_inputs = []
if array_labels is None:
array_labels = {}
def get_launch_id(launch):
kernel = launch[0]
suffix = ""
if len(launch) > 6:
metadata = launch[6]
# calling function helps to identify unique launches
if "caller" in metadata:
caller = metadata["caller"]
suffix = str(hash(caller["file"] + caller["func"] + str(caller["lineno"])))
return f"{kernel.module.name}.{kernel.key}{suffix}"
# exclude function calls, only consider kernel launches
kernel_launches = []
kernel_scopes = []
next_scope_id = 0
id_offset = 0
for i, launch in enumerate(tape.launches):
if isinstance(launch, list):
kernel_launches.append(launch)
else:
id_offset -= 1
while next_scope_id < len(tape.scopes) and i == tape.scopes[next_scope_id][0]:
scope = tape.scopes[next_scope_id]
# update scope launch index to account for removed function calls
new_scope = (scope[0] + id_offset, *scope[1:])
kernel_scopes.append(new_scope)
next_scope_id += 1
launch_structs = [
Launch(
id=get_launch_id(launch),
kernel=launch[0],
dim=launch[1],
max_blocks=launch[2],
inputs=launch[3],
outputs=launch[4],
device=launch[5],
metadata=launch[6] if len(launch) > 6 else {},
)
for launch in kernel_launches
]
launch_ids = [get_launch_id(launch) for launch in kernel_launches]
def get_repeating_sequences(sequence: List[str]):
# yield all consecutively repeating subsequences in descending order of length
for length in range(len(sequence) // 2 + 1, 0, -1):
for start in range(len(sequence) - length):
if sequence[start : start + length] == sequence[start + length : start + 2 * length]:
# we found a sequence that repeats at least once
candidate = RepeatedSequence(start, start + length, 2)
if length == 1:
# this repetition cannot be made up of smaller repetitions
yield candidate
# check if this sequence is made up entirely of smaller repetitions
for sl in range(1, length // 2 + 1):
# loop over subsequence lengths and check if they repeat
subseq = sequence[start : start + sl]
if all(
sequence[start + i * sl : start + (i + 1) * sl] == subseq for i in range(1, length // sl)
):
rep_count = length // sl + 1
# check whether there are more repetitions beyond the previous end
for cstart in range(start + length, len(sequence) - sl, sl):
if sequence[cstart : cstart + sl] != subseq:
break
rep_count += 1
candidate = RepeatedSequence(start, start + sl, rep_count)
yield candidate
break
def process_sequence(sequence: List[str]) -> RepeatedSequence:
# find the longest contiguous repetition in the sequence
if len(sequence) < 2:
return None
for r in get_repeating_sequences(sequence):
rlen = r.end - r.start
rseq = sequence[r.start : r.end]
# ensure that the repetitions of this subsequence immediately follow each other
candidates = defaultdict(int) # mapping from start index to number of repetitions
curr_start = r.start
i = r.end
while i + rlen <= len(sequence):
if sequence[i : i + rlen] == rseq:
candidates[curr_start] += 1
i += rlen
else:
try:
curr_start = sequence.index(rseq, i)
i = curr_start + rlen
except ValueError:
break
if len(candidates) > 0:
start, reps = max(candidates.items(), key=lambda x: x[1])
return RepeatedSequence(start, start + rlen, reps + 1)
return None
repetitions = []
def find_sequences(sequence):
# recursively find repetitions in sequence
nonlocal repetitions
if len(sequence) == 0:
return
# find LRS in current sequence
longest_rep = process_sequence(sequence)
if longest_rep is None:
return
# process sequence up until the current LRS
find_sequences(sequence[: longest_rep.start])
# process repeated sequence
rstr = sequence[longest_rep.start : longest_rep.end]
if longest_rep.repetitions >= 2:
repetitions.append(longest_rep)
find_sequences(rstr)
# process remaining sequence
rlen = longest_rep.end - longest_rep.start
reps = longest_rep.repetitions
end_idx = longest_rep.start + (reps + 1) * rlen
if end_idx < len(sequence):
find_sequences(sequence[end_idx:])
return
find_sequences(launch_ids)
wrap_around_connections = set()
# mapping from array ptr to already existing array in a repetition
array_repeated = {}
array_to_launch = defaultdict(list)
launch_to_array = defaultdict(list)
if simplify_graph:
# mappings from unique launch string to index of first occurrence and vice versa
launch_to_index = {}
index_to_launch = {}
# new arrays of launches, scopes without repetitions
launches = []
scopes = []
def find_scope_end(scope_i):
opened_scopes = 0
for i in range(scope_i, len(kernel_scopes)):
scope = kernel_scopes[i]
if scope[1] is not None:
opened_scopes += 1
else:
opened_scopes -= 1
if opened_scopes == 0:
return scope[0]
return len(kernel_scopes)
def process_launches(kernel_launches, start_i, end_i, rep_i, scope_i, skipped_i):
nonlocal \
launches, \
scopes, \
launch_to_index, \
index_to_launch, \
wrap_around_connections, \
launch_to_array, \
array_to_launch
i = start_i # index of current launch
opened_scopes = 0
while i < end_i:
launch_id = launch_ids[i]
while (
scope_i < len(kernel_scopes)
and i >= kernel_scopes[scope_i][0]
and kernel_scopes[scope_i][1] is None
):
# add any missing closing scopes before we go into a repeating sequence
scope = kernel_scopes[scope_i]
if opened_scopes >= 1:
scopes.append((scope[0] - skipped_i, *scope[1:]))
scope_i += 1
opened_scopes -= 1
# keep track of the mapping between arrays and kernel launch arguments
for arg_i, arg in enumerate(kernel_launches[i].inputs + kernel_launches[i].outputs):
if isinstance(arg, wp.array):
array_to_launch[arg.ptr].append((launch_id, arg_i))
launch_to_array[(launch_id, arg_i)].append(arg)
# handle repetitions
if rep_i < len(repetitions):
rep = repetitions[rep_i]
if i == rep.start:
rep_len = rep.end - rep.start
after_rep = rep.start + rep.repetitions * rep_len
# check if there is a scope that matches the entire repetition
skip_adding_repetition_scope = False
for scope_j in range(scope_i, len(kernel_scopes)):
scope = kernel_scopes[scope_j]
if scope[0] > rep.start:
break
if scope[0] == rep.start and scope[1] is not None:
# check if this scope also ends at the end of the repetition
scope_end = find_scope_end(scope_j)
if scope_end == after_rep:
# replace scope details
kernel_scopes[scope_j] = (
rep.start,
f"{scope[1]} (repeated {rep.repetitions}x)",
{"type": "repeated", "count": rep.repetitions},
)
skip_adding_repetition_scope = True
break
if not skip_adding_repetition_scope:
# add a new scope marking this repetition
scope_name = f"repeated {rep.repetitions}x"
scopes.append((len(launches), scope_name, {"type": "repeated", "count": rep.repetitions}))
# process repetition recursively to handle nested repetitions
process_launches(kernel_launches, rep.start, rep.end, rep_i + 1, scope_i, skipped_i)
if not skip_adding_repetition_scope:
# close the scope we just added marking this repetition
scopes.append((len(launches), None, None))
# collect all output arrays from the first iteration
output_arrays = {}
for j in range(i, i + rep_len):
launch = kernel_launches[j]
launch_id = launch_ids[j]
for k, arg in enumerate(launch.outputs):
arg_i = k + len(launch.inputs)
if isinstance(arg, wp.array):
output_arrays[arg.ptr] = arg
array_to_launch[arg.ptr].append((launch_id, arg_i))
# find out which output arrays feed back as inputs to the next iteration
# so we can add them as wrap-around connections
for j in range(i + rep_len, i + 2 * rep_len):
launch = kernel_launches[j]
launch_id = launch_ids[j]
for arg_i, arg in enumerate(launch.inputs):
if isinstance(arg, wp.array) and arg.ptr in output_arrays:
first_encountered_var = launch_to_array[(launch_id, arg_i)][0]
# print(array_to_launch[arg.ptr])
# array_to_launch[arg.ptr].append((launch_id, arg_i))
# launch_to_array[(launch_id, arg_i)].append(arg)
src_launch = array_to_launch[arg.ptr][-1]
src_arr = launch_to_array[src_launch][-1]
wrap_around_connections.add((src_arr.ptr, first_encountered_var.ptr))
# map arrays appearing as launch arguments in following repetitions to their first occurrence
skip_len = rep.repetitions * rep_len
for j in range(i + rep_len, i + skip_len):
launch = kernel_launches[j]
launch_id = launch_ids[j]
for arg_i, arg in enumerate(launch.inputs + launch.outputs):
if isinstance(arg, wp.array):
array_repeated[arg.ptr] = launch_to_array[(launch_id, arg_i)][0].ptr
# skip launches during these repetitions
i += skip_len
skipped_i += skip_len - rep_len
rep_i += 1
# skip scopes during the repetitions
while scope_i < len(kernel_scopes) and i > kernel_scopes[scope_i][0]:
scope_i += 1
continue
# add launch
launch = kernel_launches[i]
launch_id = launch_ids[i]
if launch_id not in launch_to_index:
# we encountered an unseen kernel
j = len(launch_to_index)
launch_to_index[launch_id] = j
index_to_launch[j] = launch_id
launches.append(launch)
while scope_i < len(kernel_scopes) and i >= kernel_scopes[scope_i][0]:
# add scopes encompassing the kernels we added so far
scope = kernel_scopes[scope_i]
if scope[1] is not None:
scopes.append((scope[0] - skipped_i, *scope[1:]))
opened_scopes += 1
else:
if opened_scopes >= 1:
# only add closing scope if there was an opening scope
scopes.append((scope[0] - skipped_i, *scope[1:]))
opened_scopes -= 1
scope_i += 1
i += 1
# close any remaining open scopes
for _ in range(opened_scopes):
scopes.append((end_i - skipped_i, None, None))
process_launches(launch_structs, 0, len(launch_structs), 0, 0, 0)
# end of simplify_graph
else:
launches = launch_structs
scopes = kernel_scopes
node_labels = {}
inserted_arrays = {} # mapping from array ptr to array
kernel_launch_count = defaultdict(int)
# array -> list of kernels that modify it
manipulated_nodes = defaultdict(list)
indent_level = 0
input_output_ptr = set()
for input in track_inputs:
input_output_ptr.add(input.ptr)
for output in track_outputs:
input_output_ptr.add(output.ptr)
def add_array_node(x: wp.array, name: str, active_scope_stack=None):
if active_scope_stack is None:
active_scope_stack = []
nonlocal node_labels
if x in array_labels:
name = array_labels[x]
if x.ptr in node_labels:
if x.ptr not in input_output_ptr:
# update name unless it is an input/output array
if choose_longest_node_name:
if len(name) > len(node_labels[x.ptr]):
node_labels[x.ptr] = name
else:
node_labels[x.ptr] = name
return
visitor.emit_array_node(x, name, active_scope_stack, indent_level)
node_labels[x.ptr] = name
inserted_arrays[x.ptr] = x
for i, x in enumerate(track_inputs):
if i < len(track_input_names):
name = track_input_names[i]
else:
name = f"input_{i}"
add_array_node(x, name)
for i, x in enumerate(track_outputs):
if i < len(track_output_names):
name = track_output_names[i]
else:
name = f"output_{i}"
add_array_node(x, name)
# add arrays which are output of a kernel (used to simplify the graph)
computed_nodes = set()
for output in track_outputs:
computed_nodes.add(output.ptr)
active_scope_stack = []
active_scope = None
active_scope_id = -1
active_scope_kernels = {}
if not hasattr(tape, "scopes"):
ignore_graph_scopes = True
if not ignore_graph_scopes and len(scopes) > 0:
active_scope = scopes[0]
active_scope_id = 0
for launch_id, launch in enumerate(launches):
if active_scope is not None:
if launch_id == active_scope[0]:
if active_scope[1] is None:
# end previous scope
indent_level -= 1
visitor.emit_scope_end(indent_level)
active_scope_stack = active_scope_stack[:-1]
else:
# begin new scope
active_scope_stack.append(f"scope{active_scope_id}")
visitor.emit_scope_begin(active_scope_id, active_scope[1], active_scope[2], indent_level)
indent_level += 1
# check if we are in the next scope now
while (
not ignore_graph_scopes
and active_scope_id < len(scopes) - 1
and launch_id == scopes[active_scope_id + 1][0]
):
active_scope_id += 1
active_scope = scopes[active_scope_id]
active_scope_kernels = {}
if active_scope[1] is None:
# end previous scope
indent_level -= 1
visitor.emit_scope_end(indent_level)
active_scope_stack = active_scope_stack[:-1]
else:
# begin new scope
active_scope_stack.append(f"scope{active_scope_id}")
visitor.emit_scope_begin(active_scope_id, active_scope[1], active_scope[2], indent_level)
indent_level += 1
kernel = launch.kernel
launch_data = {
"id": launch_id,
"dim": launch.dim,
"inputs": launch.inputs,
"outputs": launch.outputs,
"stack_trace": "",
"kernel_launch_count": kernel_launch_count[kernel.key],
}
launch_data.update(launch.metadata)
rendered = not hide_readonly_arrays or ignore_graph_scopes or kernel.key not in active_scope_kernels
if rendered:
active_scope_kernels[kernel.key] = launch_id
if not ignore_graph_scopes and hide_readonly_arrays:
k_id = f"kernel{active_scope_kernels[kernel.key]}"
else:
k_id = f"kernel{launch_id}"
visitor.emit_kernel_launch_node(kernel, k_id, launch_data, rendered, indent_level)
# loop over inputs and outputs to add them to the graph
input_arrays = []
for id, x in enumerate(launch.inputs):
name = kernel.adj.args[id].label
if isinstance(x, wp.array):
if x.ptr is None:
continue
# if x.ptr in array_to_launch and len(array_to_launch[x.ptr]) > 1:
# launch_arg_i = array_to_launch[x.ptr]
# actual_input = launch_to_array[launch_arg_i][0]
# visitor.emit_edge_array_kernel(actual_input.ptr, k_id, id, indent_level)
if not hide_readonly_arrays or x.ptr in computed_nodes or x.ptr in input_output_ptr:
xptr = x.ptr
if xptr in array_repeated:
xptr = array_repeated[xptr]
else:
add_array_node(x, name, active_scope_stack)
# input_arrays.append(x.ptr)
visitor.emit_edge_array_kernel(xptr, k_id, id, indent_level)
elif isinstance(x, wp.codegen.StructInstance):
for varname, var in get_struct_vars(x).items():
if isinstance(var, wp.array):
if not hide_readonly_arrays or var.ptr in computed_nodes or var.ptr in input_output_ptr:
add_array_node(var, f"{name}.{varname}", active_scope_stack)
input_arrays.append(var.ptr)
xptr = var.ptr
if xptr in array_repeated:
xptr = array_repeated[xptr]
visitor.emit_edge_array_kernel(xptr, k_id, id, indent_level)
output_arrays = []
for id, x in enumerate(launch.outputs):
name = kernel.adj.args[id + len(launch.inputs)].label
if isinstance(x, wp.array) and x.ptr is not None:
add_array_node(x, name, active_scope_stack)
output_arrays.append(x.ptr)
computed_nodes.add(x.ptr)
visitor.emit_edge_kernel_array(k_id, id, x.ptr, indent_level)
elif isinstance(x, wp.codegen.StructInstance):
for varname, var in get_struct_vars(x).items():
if isinstance(var, wp.array):
add_array_node(var, f"{name}.{varname}", active_scope_stack)
output_arrays.append(var.ptr)
computed_nodes.add(var.ptr)
visitor.emit_edge_kernel_array(k_id, id, var.ptr, indent_level)
for output_x in output_arrays:
# track how many kernels modify each array
manipulated_nodes[output_x].append(kernel.key)
kernel_launch_count[kernel.key] += 1
# close any open scopes
for _ in range(len(active_scope_stack)):
indent_level -= 1
visitor.emit_scope_end(indent_level)
# add additional edges between arrays
for src, dst in wrap_around_connections:
if src == dst or src not in inserted_arrays or dst not in inserted_arrays:
continue
visitor.emit_edge_array_array(inserted_arrays[src], inserted_arrays[dst], indent_level)
def visualize_tape_graphviz(
tape: Tape,
filename: str,
simplify_graph=True,
hide_readonly_arrays=False,
array_labels: Dict[wp.array, str] = None,
choose_longest_node_name: bool = True,
ignore_graph_scopes: bool = False,
track_inputs: List[wp.array] = None,
track_outputs: List[wp.array] = None,
track_input_names: List[str] = None,
track_output_names: List[str] = None,
graph_direction: str = "LR",
):
if track_output_names is None:
track_output_names = []
if track_input_names is None:
track_input_names = []
if track_outputs is None:
track_outputs = []
if track_inputs is None:
track_inputs = []
if array_labels is None:
array_labels = {}
visitor = GraphvizTapeVisitor()
visit_tape(
tape,
visitor,
simplify_graph,
hide_readonly_arrays,
array_labels,
choose_longest_node_name,
ignore_graph_scopes,
track_inputs,
track_outputs,
track_input_names,
track_output_names,
)
chart = "\n".join(visitor.graphviz_lines)
code = f"""digraph " " {{
graph [fontname="Helvetica,Arial,sans-serif",tooltip=" "];
node [style=rounded,shape=plaintext,fontname="Helvetica,Arial,sans-serif", margin="0.05,0.02", width=0, height=0, tooltip=" "];
edge [fontname="Helvetica,Arial,sans-serif",tooltip=" "];
rankdir={graph_direction};
{chart}
}}
"""
if filename is not None:
with open(filename, "w") as f:
f.write(code)
return code
| 47,864 | Python | 40.156492 | 199 | 0.536061 |
NVIDIA/warp/warp/__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.
# isort: skip_file
# for autocomplete on builtins
# from warp.stubs import *
from warp.types import array, array1d, array2d, array3d, array4d, constant
from warp.types import indexedarray, indexedarray1d, indexedarray2d, indexedarray3d, indexedarray4d
from warp.fabric import fabricarray, fabricarrayarray, indexedfabricarray, indexedfabricarrayarray
from warp.types import bool, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float16, float32, float64
from warp.types import vec2, vec2b, vec2ub, vec2s, vec2us, vec2i, vec2ui, vec2l, vec2ul, vec2h, vec2f, vec2d
from warp.types import vec3, vec3b, vec3ub, vec3s, vec3us, vec3i, vec3ui, vec3l, vec3ul, vec3h, vec3f, vec3d
from warp.types import vec4, vec4b, vec4ub, vec4s, vec4us, vec4i, vec4ui, vec4l, vec4ul, vec4h, vec4f, vec4d
from warp.types import mat22, mat22h, mat22f, mat22d
from warp.types import mat33, mat33h, mat33f, mat33d
from warp.types import mat44, mat44h, mat44f, mat44d
from warp.types import quat, quath, quatf, quatd
from warp.types import transform, transformh, transformf, transformd
from warp.types import spatial_vector, spatial_vectorh, spatial_vectorf, spatial_vectord
from warp.types import spatial_matrix, spatial_matrixh, spatial_matrixf, spatial_matrixd
# geometry types
from warp.types import Bvh, Mesh, HashGrid, Volume, MarchingCubes
from warp.types import bvh_query_t, hash_grid_query_t, mesh_query_aabb_t, mesh_query_point_t, mesh_query_ray_t
# device-wide gemms
from warp.types import matmul, adj_matmul, batched_matmul, adj_batched_matmul, from_ptr
# deprecated
from warp.types import vector as vec
from warp.types import matrix as mat
# numpy interop
from warp.types import dtype_from_numpy, dtype_to_numpy
from warp.context import init, func, func_grad, func_replay, func_native, kernel, struct, overload
from warp.context import is_cpu_available, is_cuda_available, is_device_available
from warp.context import get_devices, get_preferred_device
from warp.context import get_cuda_devices, get_cuda_device_count, get_cuda_device, map_cuda_device, unmap_cuda_device
from warp.context import get_device, set_device, synchronize_device
from warp.context import (
zeros,
zeros_like,
ones,
ones_like,
full,
full_like,
clone,
empty,
empty_like,
copy,
from_numpy,
launch,
synchronize,
force_load,
load_module,
)
from warp.context import set_module_options, get_module_options, get_module
from warp.context import capture_begin, capture_end, capture_launch
from warp.context import Kernel, Function, Launch
from warp.context import Stream, get_stream, set_stream, wait_stream, synchronize_stream
from warp.context import Event, record_event, wait_event, synchronize_event, get_event_elapsed_time
from warp.context import RegisteredGLBuffer
from warp.context import is_mempool_supported, is_mempool_enabled, set_mempool_enabled
from warp.context import set_mempool_release_threshold, get_mempool_release_threshold
from warp.context import is_mempool_access_supported, is_mempool_access_enabled, set_mempool_access_enabled
from warp.context import is_peer_access_supported, is_peer_access_enabled, set_peer_access_enabled
from warp.tape import Tape
from warp.utils import ScopedTimer, ScopedDevice, ScopedStream
from warp.utils import ScopedMempool, ScopedMempoolAccess, ScopedPeerAccess
from warp.utils import ScopedCapture
from warp.utils import transform_expand, quat_between_vectors
from warp.utils import TimingResult, timing_begin, timing_end, timing_print
from warp.utils import (
TIMING_KERNEL,
TIMING_KERNEL_BUILTIN,
TIMING_MEMCPY,
TIMING_MEMSET,
TIMING_GRAPH,
TIMING_ALL,
)
from warp.torch import from_torch, to_torch
from warp.torch import dtype_from_torch, dtype_to_torch
from warp.torch import device_from_torch, device_to_torch
from warp.torch import stream_from_torch, stream_to_torch
from warp.jax import from_jax, to_jax
from warp.jax import dtype_from_jax, dtype_to_jax
from warp.jax import device_from_jax, device_to_jax
from warp.dlpack import from_dlpack, to_dlpack
from warp.constants import *
from . import builtins
import warp.config
__version__ = warp.config.version
| 4,606 | Python | 41.266055 | 117 | 0.7868 |
NVIDIA/warp/warp/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 cProfile
import ctypes
import os
import sys
import time
import warnings
from typing import Any
import numpy as np
import warp as wp
import warp.context
import warp.types
warnings_seen = set()
def warp_showwarning(message, category, filename, lineno, file=None, line=None):
"""Version of warnings.showwarning that always prints to sys.stdout."""
if warp.config.verbose_warnings:
s = f"Warp {category.__name__}: {message} ({filename}:{lineno})\n"
if line is None:
try:
import linecache
line = linecache.getline(filename, lineno)
except Exception:
# When a warning is logged during Python shutdown, linecache
# and the import machinery don't work anymore
line = None
linecache = None
else:
line = line
if line:
line = line.strip()
s += " %s\n" % line
else:
# simple warning
s = f"Warp {category.__name__}: {message}\n"
sys.stdout.write(s)
def warn(message, category=None, stacklevel=1):
if (category, message) in warnings_seen:
return
with warnings.catch_warnings():
warnings.simplefilter("default") # Change the filter in this process
warnings.showwarning = warp_showwarning
warnings.warn(
message,
category,
stacklevel=stacklevel + 1, # Increment stacklevel by 1 since we are in a wrapper
)
if category is DeprecationWarning:
warnings_seen.add((category, message))
# expand a 7-vec to a tuple of arrays
def transform_expand(t):
return wp.transform(np.array(t[0:3]), np.array(t[3:7]))
@wp.func
def quat_between_vectors(a: wp.vec3, b: wp.vec3) -> wp.quat:
"""
Compute the quaternion that rotates vector a to vector b
"""
a = wp.normalize(a)
b = wp.normalize(b)
c = wp.cross(a, b)
d = wp.dot(a, b)
q = wp.quat(c[0], c[1], c[2], 1.0 + d)
return wp.normalize(q)
def array_scan(in_array, out_array, inclusive=True):
if in_array.device != out_array.device:
raise RuntimeError("Array storage devices do not match")
if in_array.size != out_array.size:
raise RuntimeError("Array storage sizes do not match")
if in_array.dtype != out_array.dtype:
raise RuntimeError("Array data types do not match")
if in_array.size == 0:
return
from warp.context import runtime
if in_array.device.is_cpu:
if in_array.dtype == wp.int32:
runtime.core.array_scan_int_host(in_array.ptr, out_array.ptr, in_array.size, inclusive)
elif in_array.dtype == wp.float32:
runtime.core.array_scan_float_host(in_array.ptr, out_array.ptr, in_array.size, inclusive)
else:
raise RuntimeError("Unsupported data type")
elif in_array.device.is_cuda:
if in_array.dtype == wp.int32:
runtime.core.array_scan_int_device(in_array.ptr, out_array.ptr, in_array.size, inclusive)
elif in_array.dtype == wp.float32:
runtime.core.array_scan_float_device(in_array.ptr, out_array.ptr, in_array.size, inclusive)
else:
raise RuntimeError("Unsupported data type")
def radix_sort_pairs(keys, values, count: int):
if keys.device != values.device:
raise RuntimeError("Array storage devices do not match")
if count == 0:
return
if keys.size < 2 * count or values.size < 2 * count:
raise RuntimeError("Array storage must be large enough to contain 2*count elements")
from warp.context import runtime
if keys.device.is_cpu:
if keys.dtype == wp.int32 and values.dtype == wp.int32:
runtime.core.radix_sort_pairs_int_host(keys.ptr, values.ptr, count)
else:
raise RuntimeError("Unsupported data type")
elif keys.device.is_cuda:
if keys.dtype == wp.int32 and values.dtype == wp.int32:
runtime.core.radix_sort_pairs_int_device(keys.ptr, values.ptr, count)
else:
raise RuntimeError("Unsupported data type")
def runlength_encode(values, run_values, run_lengths, run_count=None, value_count=None):
if run_values.device != values.device or run_lengths.device != values.device:
raise RuntimeError("Array storage devices do not match")
if value_count is None:
value_count = values.size
if run_values.size < value_count or run_lengths.size < value_count:
raise RuntimeError("Output array storage sizes must be at least equal to value_count")
if values.dtype != run_values.dtype:
raise RuntimeError("values and run_values data types do not match")
if run_lengths.dtype != wp.int32:
raise RuntimeError("run_lengths array must be of type int32")
# User can provide a device output array for storing the number of runs
# For convenience, if no such array is provided, number of runs is returned on host
if run_count is None:
if value_count == 0:
return 0
run_count = wp.empty(shape=(1,), dtype=int, device=values.device)
host_return = True
else:
if run_count.device != values.device:
raise RuntimeError("run_count storage device does not match other arrays")
if run_count.dtype != wp.int32:
raise RuntimeError("run_count array must be of type int32")
if value_count == 0:
run_count.zero_()
return 0
host_return = False
from warp.context import runtime
if values.device.is_cpu:
if values.dtype == wp.int32:
runtime.core.runlength_encode_int_host(
values.ptr, run_values.ptr, run_lengths.ptr, run_count.ptr, value_count
)
else:
raise RuntimeError("Unsupported data type")
elif values.device.is_cuda:
if values.dtype == wp.int32:
runtime.core.runlength_encode_int_device(
values.ptr, run_values.ptr, run_lengths.ptr, run_count.ptr, value_count
)
else:
raise RuntimeError("Unsupported data type")
if host_return:
return int(run_count.numpy()[0])
def array_sum(values, out=None, value_count=None, axis=None):
if value_count is None:
if axis is None:
value_count = values.size
else:
value_count = values.shape[axis]
if axis is None:
output_shape = (1,)
else:
def output_dim(ax, dim):
return 1 if ax == axis else dim
output_shape = tuple(output_dim(ax, dim) for ax, dim in enumerate(values.shape))
type_length = wp.types.type_length(values.dtype)
scalar_type = wp.types.type_scalar_type(values.dtype)
# User can provide a device output array for storing the number of runs
# For convenience, if no such array is provided, number of runs is returned on host
if out is None:
host_return = True
out = wp.empty(shape=output_shape, dtype=values.dtype, device=values.device)
else:
host_return = False
if out.device != values.device:
raise RuntimeError("out storage device should match values array")
if out.dtype != values.dtype:
raise RuntimeError(f"out array should have type {values.dtype.__name__}")
if out.shape != output_shape:
raise RuntimeError(f"out array should have shape {output_shape}")
if value_count == 0:
out.zero_()
if axis is None and host_return:
return out.numpy()[0]
return out
from warp.context import runtime
if values.device.is_cpu:
if scalar_type == wp.float32:
native_func = runtime.core.array_sum_float_host
elif scalar_type == wp.float64:
native_func = runtime.core.array_sum_double_host
else:
raise RuntimeError("Unsupported data type")
elif values.device.is_cuda:
if scalar_type == wp.float32:
native_func = runtime.core.array_sum_float_device
elif scalar_type == wp.float64:
native_func = runtime.core.array_sum_double_device
else:
raise RuntimeError("Unsupported data type")
if axis is None:
stride = wp.types.type_size_in_bytes(values.dtype)
native_func(values.ptr, out.ptr, value_count, stride, type_length)
if host_return:
return out.numpy()[0]
else:
stride = values.strides[axis]
for idx in np.ndindex(output_shape):
out_offset = sum(i * s for i, s in zip(idx, out.strides))
val_offset = sum(i * s for i, s in zip(idx, values.strides))
native_func(
values.ptr + val_offset,
out.ptr + out_offset,
value_count,
stride,
type_length,
)
if host_return:
return out
def array_inner(a, b, out=None, count=None, axis=None):
if a.size != b.size:
raise RuntimeError("Array storage sizes do not match")
if a.device != b.device:
raise RuntimeError("Array storage devices do not match")
if a.dtype != b.dtype:
raise RuntimeError("Array data types do not match")
if count is None:
if axis is None:
count = a.size
else:
count = a.shape[axis]
if axis is None:
output_shape = (1,)
else:
def output_dim(ax, dim):
return 1 if ax == axis else dim
output_shape = tuple(output_dim(ax, dim) for ax, dim in enumerate(a.shape))
type_length = wp.types.type_length(a.dtype)
scalar_type = wp.types.type_scalar_type(a.dtype)
# User can provide a device output array for storing the number of runs
# For convenience, if no such array is provided, number of runs is returned on host
if out is None:
host_return = True
out = wp.empty(shape=output_shape, dtype=scalar_type, device=a.device)
else:
host_return = False
if out.device != a.device:
raise RuntimeError("out storage device should match values array")
if out.dtype != scalar_type:
raise RuntimeError(f"out array should have type {scalar_type.__name__}")
if out.shape != output_shape:
raise RuntimeError(f"out array should have shape {output_shape}")
if count == 0:
if axis is None and host_return:
return 0.0
out.zero_()
return out
from warp.context import runtime
if a.device.is_cpu:
if scalar_type == wp.float32:
native_func = runtime.core.array_inner_float_host
elif scalar_type == wp.float64:
native_func = runtime.core.array_inner_double_host
else:
raise RuntimeError("Unsupported data type")
elif a.device.is_cuda:
if scalar_type == wp.float32:
native_func = runtime.core.array_inner_float_device
elif scalar_type == wp.float64:
native_func = runtime.core.array_inner_double_device
else:
raise RuntimeError("Unsupported data type")
if axis is None:
stride_a = wp.types.type_size_in_bytes(a.dtype)
stride_b = wp.types.type_size_in_bytes(b.dtype)
native_func(a.ptr, b.ptr, out.ptr, count, stride_a, stride_b, type_length)
if host_return:
return out.numpy()[0]
else:
stride_a = a.strides[axis]
stride_b = b.strides[axis]
for idx in np.ndindex(output_shape):
out_offset = sum(i * s for i, s in zip(idx, out.strides))
a_offset = sum(i * s for i, s in zip(idx, a.strides))
b_offset = sum(i * s for i, s in zip(idx, b.strides))
native_func(
a.ptr + a_offset,
b.ptr + b_offset,
out.ptr + out_offset,
count,
stride_a,
stride_b,
type_length,
)
if host_return:
return out
@wp.kernel
def _array_cast_kernel(
dest: Any,
src: Any,
):
i = wp.tid()
dest[i] = dest.dtype(src[i])
def array_cast(in_array, out_array, count=None):
if in_array.device != out_array.device:
raise RuntimeError("Array storage devices do not match")
in_array_data_shape = getattr(in_array.dtype, "_shape_", ())
out_array_data_shape = getattr(out_array.dtype, "_shape_", ())
if in_array.ndim != out_array.ndim or in_array_data_shape != out_array_data_shape:
# Number of dimensions or data type shape do not match.
# Flatten arrays and do cast at the scalar level
in_array = in_array.flatten()
out_array = out_array.flatten()
in_array_data_length = warp.types.type_length(in_array.dtype)
out_array_data_length = warp.types.type_length(out_array.dtype)
in_array_scalar_type = wp.types.type_scalar_type(in_array.dtype)
out_array_scalar_type = wp.types.type_scalar_type(out_array.dtype)
in_array = wp.array(
data=None,
ptr=in_array.ptr,
capacity=in_array.capacity,
device=in_array.device,
dtype=in_array_scalar_type,
shape=in_array.shape[0] * in_array_data_length,
)
out_array = wp.array(
data=None,
ptr=out_array.ptr,
capacity=out_array.capacity,
device=out_array.device,
dtype=out_array_scalar_type,
shape=out_array.shape[0] * out_array_data_length,
)
if count is not None:
count *= in_array_data_length
if count is None:
count = in_array.size
if in_array.ndim == 1:
dim = count
elif count < in_array.size:
raise RuntimeError("Partial cast is not supported for arrays with more than one dimension")
else:
dim = in_array.shape
if in_array.dtype == out_array.dtype:
# Same data type, can simply copy
wp.copy(dest=out_array, src=in_array, count=count)
else:
wp.launch(kernel=_array_cast_kernel, dim=dim, inputs=[out_array, in_array], device=out_array.device)
# code snippet for invoking cProfile
# cp = cProfile.Profile()
# cp.enable()
# for i in range(1000):
# self.state = self.integrator.forward(self.model, self.state, self.sim_dt)
# cp.disable()
# cp.print_stats(sort='tottime')
# exit(0)
# helper kernels for initializing NVDB volumes from a dense array
@wp.kernel
def copy_dense_volume_to_nano_vdb_v(volume: wp.uint64, values: wp.array(dtype=wp.vec3, ndim=3)):
i, j, k = wp.tid()
wp.volume_store_v(volume, i, j, k, values[i, j, k])
@wp.kernel
def copy_dense_volume_to_nano_vdb_f(volume: wp.uint64, values: wp.array(dtype=wp.float32, ndim=3)):
i, j, k = wp.tid()
wp.volume_store_f(volume, i, j, k, values[i, j, k])
@wp.kernel
def copy_dense_volume_to_nano_vdb_i(volume: wp.uint64, values: wp.array(dtype=wp.int32, ndim=3)):
i, j, k = wp.tid()
wp.volume_store_i(volume, i, j, k, values[i, j, k])
# represent an edge between v0, v1 with connected faces f0, f1, and opposite vertex o0, and o1
# winding is such that first tri can be reconstructed as {v0, v1, o0}, and second tri as { v1, v0, o1 }
class MeshEdge:
def __init__(self, v0, v1, o0, o1, f0, f1):
self.v0 = v0 # vertex 0
self.v1 = v1 # vertex 1
self.o0 = o0 # opposite vertex 1
self.o1 = o1 # opposite vertex 2
self.f0 = f0 # index of tri1
self.f1 = f1 # index of tri2
class MeshAdjacency:
def __init__(self, indices, num_tris):
# map edges (v0, v1) to faces (f0, f1)
self.edges = {}
self.indices = indices
for index, tri in enumerate(indices):
self.add_edge(tri[0], tri[1], tri[2], index)
self.add_edge(tri[1], tri[2], tri[0], index)
self.add_edge(tri[2], tri[0], tri[1], index)
def add_edge(self, i0, i1, o, f): # index1, index2, index3, index of triangle
key = (min(i0, i1), max(i0, i1))
edge = None
if key in self.edges:
edge = self.edges[key]
if edge.f1 != -1:
print("Detected non-manifold edge")
return
else:
# update other side of the edge
edge.o1 = o
edge.f1 = f
else:
# create new edge with opposite yet to be filled
edge = MeshEdge(i0, i1, o, -1, f, -1)
self.edges[key] = edge
def mem_report(): # pragma: no cover
def _mem_report(tensors, mem_type):
"""Print the selected tensors of type
There are two major storage types in our major concern:
- GPU: tensors transferred to CUDA devices
- CPU: tensors remaining on the system memory (usually unimportant)
Args:
- tensors: the tensors of specified type
- mem_type: 'CPU' or 'GPU' in current implementation"""
total_numel = 0
total_mem = 0
visited_data = []
for tensor in tensors:
if tensor.is_sparse:
continue
# a data_ptr indicates a memory block allocated
data_ptr = tensor.storage().data_ptr()
if data_ptr in visited_data:
continue
visited_data.append(data_ptr)
numel = tensor.storage().size()
total_numel += numel
element_size = tensor.storage().element_size()
mem = numel * element_size / 1024 / 1024 # 32bit=4Byte, MByte
total_mem += mem
print("Type: %s Total Tensors: %d \tUsed Memory Space: %.2f MBytes" % (mem_type, total_numel, total_mem))
import gc
import torch
gc.collect()
LEN = 65
objects = gc.get_objects()
# print('%s\t%s\t\t\t%s' %('Element type', 'Size', 'Used MEM(MBytes)') )
tensors = [obj for obj in objects if torch.is_tensor(obj)]
cuda_tensors = [t for t in tensors if t.is_cuda]
host_tensors = [t for t in tensors if not t.is_cuda]
_mem_report(cuda_tensors, "GPU")
_mem_report(host_tensors, "CPU")
print("=" * LEN)
class ScopedDevice:
def __init__(self, device):
self.device = wp.get_device(device)
def __enter__(self):
# save the previous default device
self.saved_device = self.device.runtime.default_device
# make this the default device
self.device.runtime.default_device = self.device
# make it the current CUDA device so that device alias "cuda" will evaluate to this device
self.device.context_guard.__enter__()
return self.device
def __exit__(self, exc_type, exc_value, traceback):
# restore original CUDA context
self.device.context_guard.__exit__(exc_type, exc_value, traceback)
# restore original target device
self.device.runtime.default_device = self.saved_device
class ScopedStream:
def __init__(self, stream, sync_enter=True, sync_exit=False):
self.stream = stream
self.sync_enter = sync_enter
self.sync_exit = sync_exit
if stream is not None:
self.device = stream.device
self.device_scope = ScopedDevice(self.device)
def __enter__(self):
if self.stream is not None:
self.device_scope.__enter__()
self.saved_stream = self.device.stream
self.device.set_stream(self.stream, self.sync_enter)
return self.stream
def __exit__(self, exc_type, exc_value, traceback):
if self.stream is not None:
self.device.set_stream(self.saved_stream, self.sync_exit)
self.device_scope.__exit__(exc_type, exc_value, traceback)
TIMING_KERNEL = 1
TIMING_KERNEL_BUILTIN = 2
TIMING_MEMCPY = 4
TIMING_MEMSET = 8
TIMING_GRAPH = 16
TIMING_ALL = 0xFFFFFFFF
# timer utils
class ScopedTimer:
indent = -1
enabled = True
def __init__(
self,
name,
active=True,
print=True,
detailed=False,
dict=None,
use_nvtx=False,
color="rapids",
synchronize=False,
cuda_filter=0,
report_func=None,
skip_tape=False,
):
"""Context manager object for a timer
Parameters:
name (str): Name of timer
active (bool): Enables this timer
print (bool): At context manager exit, print elapsed time to sys.stdout
detailed (bool): Collects additional profiling data using cProfile and calls ``print_stats()`` at context exit
dict (dict): A dictionary of lists to which the elapsed time will be appended using ``name`` as a key
use_nvtx (bool): If true, timing functionality is replaced by an NVTX range
color (int or str): ARGB value (e.g. 0x00FFFF) or color name (e.g. 'cyan') associated with the NVTX range
synchronize (bool): Synchronize the CPU thread with any outstanding CUDA work to return accurate GPU timings
cuda_filter (int): Filter flags for CUDA activity timing, e.g. ``warp.TIMING_KERNEL`` or ``warp.TIMING_ALL``
report_func (Callable): A callback function to print the activity report (``wp.timing_print()`` is used by default)
skip_tape (bool): If true, the timer will not be recorded in the tape
Attributes:
elapsed (float): The duration of the ``with`` block used with this object
timing_results (list[TimingResult]): The list of activity timing results, if collection was requested using ``cuda_filter``
"""
self.name = name
self.active = active and self.enabled
self.print = print
self.detailed = detailed
self.dict = dict
self.use_nvtx = use_nvtx
self.color = color
self.synchronize = synchronize
self.skip_tape = skip_tape
self.elapsed = 0.0
self.cuda_filter = cuda_filter
self.report_func = report_func or wp.timing_print
if self.dict is not None:
if name not in self.dict:
self.dict[name] = []
def __enter__(self):
if not self.skip_tape and warp.context.runtime is not None and warp.context.runtime.tape is not None:
warp.context.runtime.tape.record_scope_begin(self.name)
if self.active:
if self.synchronize:
wp.synchronize()
if self.cuda_filter:
# begin CUDA activity collection, synchronizing if needed
timing_begin(self.cuda_filter, synchronize=not self.synchronize)
if self.detailed:
self.cp = cProfile.Profile()
self.cp.clear()
self.cp.enable()
if self.use_nvtx:
import nvtx
self.nvtx_range_id = nvtx.start_range(self.name, color=self.color)
if self.print:
ScopedTimer.indent += 1
self.start = time.perf_counter_ns()
return self
def __exit__(self, exc_type, exc_value, traceback):
if not self.skip_tape and warp.context.runtime is not None and warp.context.runtime.tape is not None:
warp.context.runtime.tape.record_scope_end()
if self.active:
if self.synchronize:
wp.synchronize()
self.elapsed = (time.perf_counter_ns() - self.start) / 1000000.0
if self.use_nvtx:
import nvtx
nvtx.end_range(self.nvtx_range_id)
if self.detailed:
self.cp.disable()
self.cp.print_stats(sort="tottime")
if self.cuda_filter:
# end CUDA activity collection, synchronizing if needed
self.timing_results = timing_end(synchronize=not self.synchronize)
else:
self.timing_results = []
if self.dict is not None:
self.dict[self.name].append(self.elapsed)
if self.print:
indent = "\t" * ScopedTimer.indent
if self.timing_results:
self.report_func(self.timing_results, indent=indent)
print()
print(f"{indent}{self.name} took {self.elapsed :.2f} ms")
ScopedTimer.indent -= 1
# Allow temporarily enabling/disabling mempool allocators
class ScopedMempool:
def __init__(self, device, enable: bool):
self.device = wp.get_device(device)
self.enable = enable
def __enter__(self):
self.saved_setting = wp.is_mempool_enabled(self.device)
wp.set_mempool_enabled(self.device, self.enable)
def __exit__(self, exc_type, exc_value, traceback):
wp.set_mempool_enabled(self.device, self.saved_setting)
# Allow temporarily enabling/disabling mempool access
class ScopedMempoolAccess:
def __init__(self, target_device, peer_device, enable: bool):
self.target_device = target_device
self.peer_device = peer_device
self.enable = enable
def __enter__(self):
self.saved_setting = wp.is_mempool_access_enabled(self.target_device, self.peer_device)
wp.set_mempool_access_enabled(self.target_device, self.peer_device, self.enable)
def __exit__(self, exc_type, exc_value, traceback):
wp.set_mempool_access_enabled(self.target_device, self.peer_device, self.saved_setting)
# Allow temporarily enabling/disabling peer access
class ScopedPeerAccess:
def __init__(self, target_device, peer_device, enable: bool):
self.target_device = target_device
self.peer_device = peer_device
self.enable = enable
def __enter__(self):
self.saved_setting = wp.is_peer_access_enabled(self.target_device, self.peer_device)
wp.set_peer_access_enabled(self.target_device, self.peer_device, self.enable)
def __exit__(self, exc_type, exc_value, traceback):
wp.set_peer_access_enabled(self.target_device, self.peer_device, self.saved_setting)
class ScopedCapture:
def __init__(self, device=None, stream=None, force_module_load=None, external=False):
self.device = device
self.stream = stream
self.force_module_load = force_module_load
self.external = external
self.active = False
self.graph = None
def __enter__(self):
try:
wp.capture_begin(
device=self.device, stream=self.stream, force_module_load=self.force_module_load, external=self.external
)
self.active = True
return self
except:
raise
def __exit__(self, exc_type, exc_value, traceback):
if self.active:
try:
self.graph = wp.capture_end(device=self.device, stream=self.stream)
finally:
self.active = False
# helper kernels for adj_matmul
@wp.kernel
def add_kernel_2d(x: wp.array2d(dtype=Any), acc: wp.array2d(dtype=Any), beta: Any):
i, j = wp.tid()
x[i, j] = x[i, j] + beta * acc[i, j]
@wp.kernel
def add_kernel_3d(x: wp.array3d(dtype=Any), acc: wp.array3d(dtype=Any), beta: Any):
i, j, k = wp.tid()
x[i, j, k] = x[i, j, k] + beta * acc[i, j, k]
# explicit instantiations of generic kernels for adj_matmul
for T in [wp.float16, wp.float32, wp.float64]:
wp.overload(add_kernel_2d, [wp.array2d(dtype=T), wp.array2d(dtype=T), T])
wp.overload(add_kernel_3d, [wp.array3d(dtype=T), wp.array3d(dtype=T), T])
def check_iommu():
"""Check if IOMMU is enabled on Linux, which can affect peer-to-peer transfers.
Returns:
A Boolean indicating whether IOMMU is configured properly for peer-to-peer transfers.
On Linux, this function attempts to determine if IOMMU is enabled and will return `False` if IOMMU is detected.
On other operating systems, it always return `True`.
"""
if sys.platform == "linux":
# On modern Linux, there should be IOMMU-related entries in the /sys file system.
# This should be more reliable than checking kernel logs like dmesg.
if os.path.isdir("/sys/class/iommu") and os.listdir("/sys/class/iommu"):
return False
if os.path.isdir("/sys/kernel/iommu_groups") and os.listdir("/sys/kernel/iommu_groups"):
return False
# HACK: disable P2P tests on misbehaving agents
disable_p2p_tests = os.getenv("WARP_DISABLE_P2P_TESTS", default="0")
if int(disable_p2p_tests):
return False
return True
else:
# doesn't matter
return True
class timing_result_t(ctypes.Structure):
"""CUDA timing struct for fetching values from C++"""
_fields_ = [
("context", ctypes.c_void_p),
("name", ctypes.c_char_p),
("filter", ctypes.c_int),
("elapsed", ctypes.c_float),
]
class TimingResult:
"""Timing result for a single activity.
Parameters:
raw_result (warp.utils.timing_result_t): The result structure obtained from C++ (internal use only)
Attributes:
device (warp.Device): The device where the activity was recorded.
name (str): The activity name.
filter (int): The type of activity (e.g., ``warp.TIMING_KERNEL``).
elapsed (float): The elapsed time in milliseconds.
"""
def __init__(self, device, name, filter, elapsed):
self.device = device
self.name = name
self.filter = filter
self.elapsed = elapsed
def timing_begin(cuda_filter=TIMING_ALL, synchronize=True):
"""Begin detailed activity timing.
Parameters:
cuda_filter (int): Filter flags for CUDA activity timing, e.g. ``warp.TIMING_KERNEL`` or ``warp.TIMING_ALL``
synchronize (bool): Whether to synchronize all CUDA devices before timing starts
"""
if synchronize:
warp.synchronize()
warp.context.runtime.core.cuda_timing_begin(cuda_filter)
def timing_end(synchronize=True):
"""End detailed activity timing.
Parameters:
synchronize (bool): Whether to synchronize all CUDA devices before timing ends
Returns:
list[TimingResult]: A list of ``TimingResult`` objects for all recorded activities.
"""
if synchronize:
warp.synchronize()
# get result count
count = warp.context.runtime.core.cuda_timing_get_result_count()
# get result array from C++
result_buffer = (timing_result_t * count)()
warp.context.runtime.core.cuda_timing_end(ctypes.byref(result_buffer), count)
# prepare Python result list
results = []
for r in result_buffer:
device = warp.context.runtime.context_map.get(r.context)
filter = r.filter
elapsed = r.elapsed
name = r.name.decode()
if filter == TIMING_KERNEL:
if name.endswith("forward"):
# strip trailing "_cuda_kernel_forward"
name = f"forward kernel {name[:-20]}"
else:
# strip trailing "_cuda_kernel_backward"
name = f"backward kernel {name[:-21]}"
elif filter == TIMING_KERNEL_BUILTIN:
if name.startswith("wp::"):
name = f"builtin kernel {name[4:]}"
else:
name = f"builtin kernel {name}"
results.append(TimingResult(device, name, filter, elapsed))
return results
def timing_print(results, indent=""):
"""Print timing results.
Parameters:
results (list[TimingResult]): List of ``TimingResult`` objects.
indent (str): Optional indentation for the output.
"""
if not results:
print("No activity")
return
class Aggregate:
def __init__(self, count=0, elapsed=0):
self.count = count
self.elapsed = elapsed
device_totals = {}
activity_totals = {}
max_name_len = len("Activity")
for r in results:
name_len = len(r.name)
max_name_len = max(max_name_len, name_len)
activity_width = max_name_len + 1
activity_dashes = "-" * activity_width
print(f"{indent}CUDA timeline:")
print(f"{indent}----------------+---------+{activity_dashes}")
print(f"{indent}Time | Device | Activity")
print(f"{indent}----------------+---------+{activity_dashes}")
for r in results:
device_agg = device_totals.get(r.device.alias)
if device_agg is None:
device_totals[r.device.alias] = Aggregate(count=1, elapsed=r.elapsed)
else:
device_agg.count += 1
device_agg.elapsed += r.elapsed
activity_agg = activity_totals.get(r.name)
if activity_agg is None:
activity_totals[r.name] = Aggregate(count=1, elapsed=r.elapsed)
else:
activity_agg.count += 1
activity_agg.elapsed += r.elapsed
print(f"{indent}{r.elapsed :12.6f} ms | {r.device.alias :7s} | {r.name}")
print()
print(f"{indent}CUDA activity summary:")
print(f"{indent}----------------+---------+{activity_dashes}")
print(f"{indent}Total time | Count | Activity")
print(f"{indent}----------------+---------+{activity_dashes}")
for name, agg in activity_totals.items():
print(f"{indent}{agg.elapsed :12.6f} ms | {agg.count :7d} | {name}")
print()
print(f"{indent}CUDA device summary:")
print(f"{indent}----------------+---------+{activity_dashes}")
print(f"{indent}Total time | Count | Device")
print(f"{indent}----------------+---------+{activity_dashes}")
for device, agg in device_totals.items():
print(f"{indent}{agg.elapsed :12.6f} ms | {agg.count :7d} | {device}")
| 34,148 | Python | 32.8444 | 135 | 0.601119 |
NVIDIA/warp/warp/jax.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 warp
def device_to_jax(warp_device: warp.context.Devicelike):
"""Return the Jax device corresponding to a Warp device.
Returns:
:class:`jax.Device`
Raises:
RuntimeError: Failed to find the corresponding Jax device.
"""
import jax
d = warp.get_device(warp_device)
if d.is_cuda:
cuda_devices = jax.devices("cuda")
if d.ordinal >= len(cuda_devices):
raise RuntimeError(f"Jax device corresponding to '{warp_device}' is not available")
return cuda_devices[d.ordinal]
else:
cpu_devices = jax.devices("cpu")
if not cpu_devices:
raise RuntimeError(f"Jax device corresponding to '{warp_device}' is not available")
return cpu_devices[0]
def device_from_jax(jax_device) -> warp.context.Device:
"""Return the Warp device corresponding to a Jax device.
Args:
jax_device (jax.Device): A Jax device descriptor.
Raises:
RuntimeError: The Jax device is neither a CPU nor GPU device.
"""
if jax_device.platform == "cpu":
return warp.get_device("cpu")
elif jax_device.platform == "gpu":
return warp.get_cuda_device(jax_device.id)
else:
raise RuntimeError(f"Unsupported Jax device platform '{jax_device.platform}'")
def dtype_to_jax(warp_dtype):
"""Return the Jax dtype corresponding to a Warp dtype.
Args:
warp_dtype: A Warp data type that has a corresponding Jax data type.
Raises:
TypeError: Unable to find a corresponding Jax data type.
"""
# initialize lookup table on first call to defer jax import
if dtype_to_jax.type_map is None:
import jax.numpy as jp
dtype_to_jax.type_map = {
warp.float16: jp.float16,
warp.float32: jp.float32,
warp.float64: jp.float64,
warp.int8: jp.int8,
warp.int16: jp.int16,
warp.int32: jp.int32,
warp.int64: jp.int64,
warp.uint8: jp.uint8,
warp.uint16: jp.uint16,
warp.uint32: jp.uint32,
warp.uint64: jp.uint64,
warp.bool: jp.bool_,
}
jax_dtype = dtype_to_jax.type_map.get(warp_dtype)
if jax_dtype is not None:
return jax_dtype
else:
raise TypeError(f"Cannot convert {warp_dtype} to a Jax type")
def dtype_from_jax(jax_dtype):
"""Return the Warp dtype corresponding to a Jax dtype.
Raises:
TypeError: Unable to find a corresponding Warp data type.
"""
# initialize lookup table on first call to defer jax import
if dtype_from_jax.type_map is None:
import jax.numpy as jp
dtype_from_jax.type_map = {
# Jax scalar types
jp.float16: warp.float16,
jp.float32: warp.float32,
jp.float64: warp.float64,
jp.int8: warp.int8,
jp.int16: warp.int16,
jp.int32: warp.int32,
jp.int64: warp.int64,
jp.uint8: warp.uint8,
jp.uint16: warp.uint16,
jp.uint32: warp.uint32,
jp.uint64: warp.uint64,
jp.bool_: warp.bool,
# Jax dtype objects
jp.dtype(jp.float16): warp.float16,
jp.dtype(jp.float32): warp.float32,
jp.dtype(jp.float64): warp.float64,
jp.dtype(jp.int8): warp.int8,
jp.dtype(jp.int16): warp.int16,
jp.dtype(jp.int32): warp.int32,
jp.dtype(jp.int64): warp.int64,
jp.dtype(jp.uint8): warp.uint8,
jp.dtype(jp.uint16): warp.uint16,
jp.dtype(jp.uint32): warp.uint32,
jp.dtype(jp.uint64): warp.uint64,
jp.dtype(jp.bool_): warp.bool,
}
wp_dtype = dtype_from_jax.type_map.get(jax_dtype)
if wp_dtype is not None:
return wp_dtype
else:
raise TypeError(f"Cannot convert {jax_dtype} to a Warp type")
# lookup tables initialized when needed
dtype_from_jax.type_map = None
dtype_to_jax.type_map = None
def to_jax(warp_array):
"""
Convert a Warp array to a Jax array without copying the data.
Args:
warp_array (warp.array): The Warp array to convert.
Returns:
jax.Array: The converted Jax array.
"""
import jax.dlpack
return jax.dlpack.from_dlpack(warp.to_dlpack(warp_array))
def from_jax(jax_array, dtype=None) -> warp.array:
"""Convert a Jax array to a Warp array without copying the data.
Args:
jax_array (jax.Array): The Jax array to convert.
dtype (optional): The target data type of the resulting Warp array. Defaults to the Jax array's data type mapped to a Warp data type.
Returns:
warp.array: The converted Warp array.
"""
import jax.dlpack
return warp.from_dlpack(jax.dlpack.to_dlpack(jax_array), dtype=dtype)
| 5,280 | Python | 30.622754 | 141 | 0.621402 |
NVIDIA/warp/warp/jax_experimental.py | # Copyright (c) 2024 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 ctypes
import jax
import warp as wp
from warp.context import type_str
from warp.types import array_t, launch_bounds_t, strides_from_shape
_jax_warp_p = None
# Holder for the custom callback to keep it alive.
_cc_callback = None
_registered_kernels = [None]
_registered_kernel_to_id = {}
def jax_kernel(wp_kernel):
"""Create a Jax primitive from a Warp kernel.
NOTE: This is an experimental feature under development.
Current limitations:
- All kernel arguments must be arrays.
- Kernel launch dimensions are inferred from the shape of the first argument.
- Input arguments are followed by output arguments in the Warp kernel definition.
- There must be at least one input argument and at least one output argument.
- Output shapes must match the launch dimensions (i.e., output shapes must match the shape of the first argument).
- All arrays must be contiguous.
- Only the CUDA backend is supported.
"""
if _jax_warp_p is None:
# Create and register the primitive
_create_jax_warp_primitive()
if wp_kernel not in _registered_kernel_to_id:
id = len(_registered_kernels)
_registered_kernels.append(wp_kernel)
_registered_kernel_to_id[wp_kernel] = id
else:
id = _registered_kernel_to_id[wp_kernel]
def bind(*args):
return _jax_warp_p.bind(*args, kernel=id)
return bind
def _warp_custom_callback(stream, buffers, opaque, opaque_len):
# The descriptor is the form
# <kernel-id>|<launch-dims>|<arg-dims-list>
# Example: 42|16,32|16,32;100;16,32
kernel_id_str, dim_str, args_str = opaque.decode().split("|")
# Get the kernel from the registry.
kernel_id = int(kernel_id_str)
kernel = _registered_kernels[kernel_id]
# Parse launch dimensions.
dims = [int(d) for d in dim_str.split(",")]
bounds = launch_bounds_t(dims)
# Parse arguments.
arg_strings = args_str.split(";")
num_args = len(arg_strings)
assert num_args == len(kernel.adj.args), "Incorrect number of arguments"
# First param is the launch bounds.
kernel_params = (ctypes.c_void_p * (1 + num_args))()
kernel_params[0] = ctypes.addressof(bounds)
# Parse array descriptors.
args = []
for i in range(num_args):
dtype = kernel.adj.args[i].type.dtype
shape = [int(d) for d in arg_strings[i].split(",")]
strides = strides_from_shape(shape, dtype)
arr = array_t(buffers[i], 0, len(shape), shape, strides)
args.append(arr) # keep a reference
arg_ptr = ctypes.addressof(arr)
kernel_params[i + 1] = arg_ptr
# Get current device.
device = wp.device_from_jax(_get_jax_device())
# Get kernel hooks.
# Note: module was loaded during jit lowering.
hooks = kernel.module.get_kernel_hooks(kernel, device)
assert hooks.forward, "Failed to find kernel entry point"
# Launch the kernel.
wp.context.runtime.core.cuda_launch_kernel(device.context, hooks.forward, bounds.size, 0, kernel_params, stream)
# TODO: is there a simpler way of getting the Jax "current" device?
def _get_jax_device():
# check if jax.default_device() context manager is active
device = jax.config.jax_default_device
# if default device is not set, use first device
if device is None:
device = jax.devices()[0]
return device
def _create_jax_warp_primitive():
from functools import reduce
import jax
from jax._src.interpreters import batching
from jax.interpreters import mlir
from jax.interpreters.mlir import ir
from jaxlib.hlo_helpers import custom_call
global _jax_warp_p
global _cc_callback
# Create and register the primitive.
# TODO add default implementation that calls the kernel via warp.
_jax_warp_p = jax.core.Primitive("jax_warp")
_jax_warp_p.multiple_results = True
# TODO Just launch the kernel directly, but make sure the argument
# shapes are massaged the same way as below so that vmap works.
def impl(*args):
raise Exception("Not implemented")
_jax_warp_p.def_impl(impl)
# Auto-batching. Make sure all the arguments are fully broadcasted
# so that Warp is not confused about dimensions.
def vectorized_multi_batcher(args, dims, **params):
# Figure out the number of outputs.
wp_kernel = _registered_kernels[params["kernel"]]
output_count = len(wp_kernel.adj.args) - len(args)
shape, dim = next((a.shape, d) for a, d in zip(args, dims) if d is not None)
size = shape[dim]
args = [batching.bdim_at_front(a, d, size) if len(a.shape) else a for a, d in zip(args, dims)]
# Create the batched primitive.
return _jax_warp_p.bind(*args, **params), [dims[0]] * output_count
batching.primitive_batchers[_jax_warp_p] = vectorized_multi_batcher
def get_vecmat_shape(warp_type):
if hasattr(warp_type.dtype, "_shape_"):
return warp_type.dtype._shape_
return []
def strip_vecmat_dimensions(warp_arg, actual_shape):
shape = get_vecmat_shape(warp_arg.type)
for i, s in enumerate(reversed(shape)):
item = actual_shape[-i - 1]
if s != item:
raise Exception(f"The vector/matrix shape for argument {warp_arg.label} does not match")
return actual_shape[: len(actual_shape) - len(shape)]
def collapse_into_leading_dimension(warp_arg, actual_shape):
if len(actual_shape) < warp_arg.type.ndim:
raise Exception(f"Argument {warp_arg.label} has too few non-matrix/vector dimensions")
index_rest = len(actual_shape) - warp_arg.type.ndim + 1
leading_size = reduce(lambda x, y: x * y, actual_shape[:index_rest])
return [leading_size] + actual_shape[index_rest:]
# Infer array dimensions from input type.
def infer_dimensions(warp_arg, actual_shape):
actual_shape = strip_vecmat_dimensions(warp_arg, actual_shape)
return collapse_into_leading_dimension(warp_arg, actual_shape)
def base_type_to_jax(warp_dtype):
if hasattr(warp_dtype, "_wp_scalar_type_"):
return wp.dtype_to_jax(warp_dtype._wp_scalar_type_)
return wp.dtype_to_jax(warp_dtype)
def base_type_to_jax_ir(warp_dtype):
warp_to_jax_dict = {
wp.float16: ir.F16Type.get(),
wp.float32: ir.F32Type.get(),
wp.float64: ir.F64Type.get(),
wp.int8: ir.IntegerType.get_signless(8),
wp.int16: ir.IntegerType.get_signless(16),
wp.int32: ir.IntegerType.get_signless(32),
wp.int64: ir.IntegerType.get_signless(64),
wp.uint8: ir.IntegerType.get_unsigned(8),
wp.uint16: ir.IntegerType.get_unsigned(16),
wp.uint32: ir.IntegerType.get_unsigned(32),
wp.uint64: ir.IntegerType.get_unsigned(64),
}
if hasattr(warp_dtype, "_wp_scalar_type_"):
warp_dtype = warp_dtype._wp_scalar_type_
jax_dtype = warp_to_jax_dict.get(warp_dtype)
if jax_dtype is None:
raise TypeError(f"Invalid or unsupported data type: {warp_dtype}")
return jax_dtype
def base_type_is_compatible(warp_type, jax_ir_type):
jax_ir_to_warp = {
"f16": wp.float16,
"f32": wp.float32,
"f64": wp.float64,
"i8": wp.int8,
"i16": wp.int16,
"i32": wp.int32,
"i64": wp.int64,
"ui8": wp.uint8,
"ui16": wp.uint16,
"ui32": wp.uint32,
"ui64": wp.uint64,
}
expected_warp_type = jax_ir_to_warp.get(str(jax_ir_type))
if expected_warp_type is not None:
if hasattr(warp_type, "_wp_scalar_type_"):
return warp_type._wp_scalar_type_ == expected_warp_type
else:
return warp_type == expected_warp_type
else:
raise TypeError(f"Invalid or unsupported data type: {jax_ir_type}")
# Abstract evaluation.
def jax_warp_abstract(*args, kernel=None):
wp_kernel = _registered_kernels[kernel]
# All the extra arguments to the warp kernel are outputs.
warp_outputs = [o.type for o in wp_kernel.adj.args[len(args) :]]
# TODO. Let's just use the first input dimension to infer the output's dimensions.
dims = strip_vecmat_dimensions(wp_kernel.adj.args[0], list(args[0].shape))
jax_outputs = []
for o in warp_outputs:
shape = list(dims) + list(get_vecmat_shape(o))
dtype = base_type_to_jax(o.dtype)
jax_outputs.append(jax.core.ShapedArray(shape, dtype))
return jax_outputs
_jax_warp_p.def_abstract_eval(jax_warp_abstract)
# Lowering to MLIR.
# Create python-land custom call target.
CCALLFUNC = ctypes.CFUNCTYPE(
ctypes.c_voidp, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p), ctypes.c_char_p, ctypes.c_size_t
)
_cc_callback = CCALLFUNC(_warp_custom_callback)
ccall_address = ctypes.cast(_cc_callback, ctypes.c_void_p)
# Put the custom call into a capsule, as required by XLA.
PyCapsule_Destructor = ctypes.CFUNCTYPE(None, ctypes.py_object)
PyCapsule_New = ctypes.pythonapi.PyCapsule_New
PyCapsule_New.restype = ctypes.py_object
PyCapsule_New.argtypes = (ctypes.c_void_p, ctypes.c_char_p, PyCapsule_Destructor)
capsule = PyCapsule_New(ccall_address.value, b"xla._CUSTOM_CALL_TARGET", PyCapsule_Destructor(0))
# Register the callback in XLA.
jax.lib.xla_client.register_custom_call_target("warp_call", capsule, platform="gpu")
def default_layout(shape):
return range(len(shape) - 1, -1, -1)
def warp_call_lowering(ctx, *args, kernel=None):
if not kernel:
raise Exception("Unknown kernel id " + str(kernel))
wp_kernel = _registered_kernels[kernel]
# TODO This may not be necessary, but it is perhaps better not to be
# mucking with kernel loading while already running the workload.
module = wp_kernel.module
device = wp.device_from_jax(_get_jax_device())
if not module.load(device):
raise Exception("Could not load kernel on device")
# Infer dimensions from the first input.
warp_arg0 = wp_kernel.adj.args[0]
actual_shape0 = ir.RankedTensorType(args[0].type).shape
dims = strip_vecmat_dimensions(warp_arg0, actual_shape0)
warp_dims = collapse_into_leading_dimension(warp_arg0, dims)
# Figure out the types and shapes of the input arrays.
arg_strings = []
operand_layouts = []
for actual, warg in zip(args, wp_kernel.adj.args):
wtype = warg.type
rtt = ir.RankedTensorType(actual.type)
if not isinstance(wtype, wp.array):
raise Exception("Only contiguous arrays are supported for Jax kernel arguments")
if not base_type_is_compatible(wtype.dtype, rtt.element_type):
raise TypeError(
f"Incompatible data type for argument '{warg.label}', expected {type_str(wtype.dtype)}, got {rtt.element_type}"
)
# Infer array dimension (by removing the vector/matrix dimensions and
# collapsing the initial dimensions).
shape = infer_dimensions(warg, rtt.shape)
if len(shape) != wtype.ndim:
raise TypeError(f"Incompatible array dimensionality for argument '{warg.label}'")
arg_strings.append(",".join([str(d) for d in shape]))
operand_layouts.append(default_layout(rtt.shape))
# Figure out the types and shapes of the output arrays.
result_types = []
result_layouts = []
for warg in wp_kernel.adj.args[len(args) :]:
wtype = warg.type
if not isinstance(wtype, wp.array):
raise Exception("Only contiguous arrays are supported for Jax kernel arguments")
# Infer dimensions from the first input.
arg_strings.append(",".join([str(d) for d in warp_dims]))
result_shape = list(dims) + list(get_vecmat_shape(wtype))
result_types.append(ir.RankedTensorType.get(result_shape, base_type_to_jax_ir(wtype.dtype)))
result_layouts.append(default_layout(result_shape))
# Build opaque descriptor for callback.
shape_str = ",".join([str(d) for d in warp_dims])
args_str = ";".join(arg_strings)
descriptor = f"{kernel}|{shape_str}|{args_str}"
out = custom_call(
b"warp_call",
result_types=result_types,
operands=args,
backend_config=descriptor.encode("utf-8"),
operand_layouts=operand_layouts,
result_layouts=result_layouts,
).results
return out
mlir.register_lowering(
_jax_warp_p,
warp_call_lowering,
platform="gpu",
)
| 13,400 | Python | 38.18421 | 131 | 0.635224 |
NVIDIA/warp/warp/torch.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import ctypes
import numpy
import warp
# return the warp device corresponding to a torch device
def device_from_torch(torch_device) -> warp.context.Device:
"""Return the Warp device corresponding to a Torch device."""
return warp.get_device(str(torch_device))
def device_to_torch(warp_device: warp.context.Devicelike) -> str:
"""Return the Torch device string corresponding to a Warp device.
Args:
warp_device: An identifier that can be resolved to a :class:`warp.context.Device`.
Raises:
RuntimeError: The Warp device is not compatible with PyTorch.
"""
device = warp.get_device(warp_device)
if device.is_cpu or device.is_primary:
return str(device)
elif device.is_cuda and device.is_uva:
# it's not a primary context, but torch can access the data ptr directly thanks to UVA
return f"cuda:{device.ordinal}"
raise RuntimeError(f"Warp device {device} is not compatible with torch")
def dtype_to_torch(warp_dtype):
"""Return the Torch dtype corresponding to a Warp dtype.
Args:
warp_dtype: A Warp data type that has a corresponding ``torch.dtype``.
``warp.uint16``, ``warp.uint32``, and ``warp.uint64`` are mapped
to the signed integer ``torch.dtype`` of the same width.
Raises:
TypeError: Unable to find a corresponding PyTorch data type.
"""
# initialize lookup table on first call to defer torch import
if dtype_to_torch.type_map is None:
import torch
dtype_to_torch.type_map = {
warp.float16: torch.float16,
warp.float32: torch.float32,
warp.float64: torch.float64,
warp.int8: torch.int8,
warp.int16: torch.int16,
warp.int32: torch.int32,
warp.int64: torch.int64,
warp.uint8: torch.uint8,
# torch doesn't support unsigned ints bigger than 8 bits
warp.uint16: torch.int16,
warp.uint32: torch.int32,
warp.uint64: torch.int64,
warp.bool: torch.bool,
}
torch_dtype = dtype_to_torch.type_map.get(warp_dtype)
if torch_dtype is not None:
return torch_dtype
else:
raise TypeError(f"Cannot convert {warp_dtype} to a Torch type")
def dtype_from_torch(torch_dtype):
"""Return the Warp dtype corresponding to a Torch dtype.
Args:
torch_dtype: A ``torch.dtype`` that has a corresponding Warp data type.
Currently ``torch.bfloat16``, ``torch.complex64``, and
``torch.complex128`` are not supported.
Raises:
TypeError: Unable to find a corresponding Warp data type.
"""
# initialize lookup table on first call to defer torch import
if dtype_from_torch.type_map is None:
import torch
dtype_from_torch.type_map = {
torch.float16: warp.float16,
torch.float32: warp.float32,
torch.float64: warp.float64,
torch.int8: warp.int8,
torch.int16: warp.int16,
torch.int32: warp.int32,
torch.int64: warp.int64,
torch.uint8: warp.uint8,
torch.bool: warp.bool,
# currently unsupported by Warp
# torch.bfloat16:
# torch.complex64:
# torch.complex128:
}
warp_dtype = dtype_from_torch.type_map.get(torch_dtype)
if warp_dtype is not None:
return warp_dtype
else:
raise TypeError(f"Cannot convert {torch_dtype} to a Warp type")
def dtype_is_compatible(torch_dtype, warp_dtype) -> bool:
"""Evaluates whether the given torch dtype is compatible with the given Warp dtype."""
# initialize lookup table on first call to defer torch import
if dtype_is_compatible.compatible_sets is None:
import torch
dtype_is_compatible.compatible_sets = {
torch.float64: {warp.float64},
torch.float32: {warp.float32},
torch.float16: {warp.float16},
# allow aliasing integer tensors as signed or unsigned integer arrays
torch.int64: {warp.int64, warp.uint64},
torch.int32: {warp.int32, warp.uint32},
torch.int16: {warp.int16, warp.uint16},
torch.int8: {warp.int8, warp.uint8},
torch.uint8: {warp.uint8, warp.int8},
torch.bool: {warp.bool, warp.uint8, warp.int8},
# currently unsupported by Warp
# torch.bfloat16:
# torch.complex64:
# torch.complex128:
}
compatible_set = dtype_is_compatible.compatible_sets.get(torch_dtype)
if compatible_set is not None:
if warp_dtype in compatible_set:
return True
# check if it's a vector or matrix type
if hasattr(warp_dtype, "_wp_scalar_type_"):
return warp_dtype._wp_scalar_type_ in compatible_set
return False
# lookup tables initialized when needed
dtype_from_torch.type_map = None
dtype_to_torch.type_map = None
dtype_is_compatible.compatible_sets = None
# wrap a torch tensor to a wp array, data is not copied
def from_torch(t, dtype=None, requires_grad=None, grad=None):
"""Convert a Torch tensor to a Warp array without copying the data.
Args:
t (torch.Tensor): The torch tensor to wrap.
dtype (warp.dtype, optional): The target data type of the resulting Warp array. Defaults to the tensor value type mapped to a Warp array value type.
requires_grad (bool, optional): Whether the resulting array should wrap the tensor's gradient, if it exists (the grad tensor will be allocated otherwise). Defaults to the tensor's `requires_grad` value.
Returns:
warp.array: The wrapped array.
"""
if dtype is None:
dtype = dtype_from_torch(t.dtype)
elif not dtype_is_compatible(t.dtype, dtype):
raise RuntimeError(f"Cannot convert Torch type {t.dtype} to Warp type {dtype}")
# get size of underlying data type to compute strides
ctype_size = ctypes.sizeof(dtype._type_)
shape = tuple(t.shape)
strides = tuple(s * ctype_size for s in t.stride())
device = device_from_torch(t.device)
# if target is a vector or matrix type
# then check if trailing dimensions match
# the target type and update the shape
if hasattr(dtype, "_shape_"):
dtype_shape = dtype._shape_
dtype_dims = len(dtype._shape_)
if dtype_dims > len(shape) or dtype_shape != shape[-dtype_dims:]:
raise RuntimeError(
f"Could not convert Torch tensor with shape {shape} to Warp array with dtype={dtype}, ensure that source inner shape is {dtype_shape}"
)
# ensure the inner strides are contiguous
stride = ctype_size
for i in range(dtype_dims):
if strides[-i - 1] != stride:
raise RuntimeError(
f"Could not convert Torch tensor with shape {shape} to Warp array with dtype={dtype}, because the source inner strides are not contiguous"
)
stride *= dtype_shape[-i - 1]
shape = tuple(shape[:-dtype_dims]) or (1,)
strides = tuple(strides[:-dtype_dims]) or (ctype_size,)
requires_grad = t.requires_grad if requires_grad is None else requires_grad
if grad is not None:
if not isinstance(grad, warp.array):
import torch
if isinstance(grad, torch.Tensor):
grad = from_torch(grad, dtype=dtype)
else:
raise ValueError(f"Invalid gradient type: {type(grad)}")
elif requires_grad:
# wrap the tensor gradient, allocate if necessary
if t.grad is None:
# allocate a zero-filled gradient if it doesn't exist
# Note: we use Warp to allocate the shared gradient with compatible strides
grad = warp.zeros(dtype=dtype, shape=shape, strides=strides, device=device)
t.grad = to_torch(grad, requires_grad=False)
else:
# TODO: this will fail if the strides are incompatible
grad = from_torch(t.grad, dtype=dtype)
a = warp.array(
ptr=t.data_ptr(),
dtype=dtype,
shape=shape,
strides=strides,
device=device,
copy=False,
grad=grad,
requires_grad=requires_grad,
)
# save a reference to the source tensor, otherwise it will be deallocated
a._tensor = t
return a
def to_torch(a, requires_grad=None):
"""
Convert a Warp array to a Torch tensor without copying the data.
Args:
a (warp.array): The Warp array to convert.
requires_grad (bool, optional): Whether the resulting tensor should convert the array's gradient, if it exists, to a grad tensor. Defaults to the array's `requires_grad` value.
Returns:
torch.Tensor: The converted tensor.
"""
import torch
if requires_grad is None:
requires_grad = a.requires_grad
# Torch does not support structured arrays
if isinstance(a.dtype, warp.codegen.Struct):
raise RuntimeError("Cannot convert structured Warp arrays to Torch.")
if a.device.is_cpu:
# Torch has an issue wrapping CPU objects
# that support the __array_interface__ protocol
# in this case we need to workaround by going
# to an ndarray first, see https://pearu.github.io/array_interface_pytorch.html
t = torch.as_tensor(numpy.asarray(a))
t.requires_grad = requires_grad
if requires_grad and a.requires_grad:
t.grad = torch.as_tensor(numpy.asarray(a.grad))
return t
elif a.device.is_cuda:
# Torch does support the __cuda_array_interface__
# correctly, but we must be sure to maintain a reference
# to the owning object to prevent memory allocs going out of scope
t = torch.as_tensor(a, device=device_to_torch(a.device))
t.requires_grad = requires_grad
if requires_grad and a.requires_grad:
t.grad = torch.as_tensor(a.grad, device=device_to_torch(a.device))
return t
else:
raise RuntimeError("Unsupported device")
def stream_from_torch(stream_or_device=None):
"""Convert from a Torch CUDA stream to a Warp CUDA stream."""
import torch
if isinstance(stream_or_device, torch.cuda.Stream):
stream = stream_or_device
else:
# assume arg is a torch device
stream = torch.cuda.current_stream(stream_or_device)
device = device_from_torch(stream.device)
warp_stream = warp.Stream(device, cuda_stream=stream.cuda_stream)
# save a reference to the source stream, otherwise it may be destroyed
warp_stream._torch_stream = stream
return warp_stream
def stream_to_torch(stream_or_device=None):
"""Convert from a Warp CUDA stream to a Torch CUDA stream."""
import torch
if isinstance(stream_or_device, warp.Stream):
stream = stream_or_device
else:
# assume arg is a warp device
stream = warp.get_device(stream_or_device).stream
device = device_to_torch(stream.device)
torch_stream = torch.cuda.ExternalStream(stream.cuda_stream, device=device)
# save a reference to the source stream, otherwise it may be destroyed
torch_stream._warp_stream = stream
return torch_stream
| 11,760 | Python | 35.524845 | 210 | 0.642772 |
NVIDIA/warp/warp/context.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 ast
import builtins
import ctypes
import functools
import hashlib
import inspect
import io
import itertools
import operator
import os
import platform
import sys
import types
from copy import copy as shallowcopy
from pathlib import Path
from struct import pack as struct_pack
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union
import numpy as np
import warp
import warp.build
import warp.codegen
import warp.config
# represents either a built-in or user-defined function
def create_value_func(type):
def value_func(args, kwds, templates):
return type
return value_func
def get_function_args(func):
"""Ensures that all function arguments are annotated and returns a dictionary mapping from argument name to its type."""
argspec = inspect.getfullargspec(func)
# use source-level argument annotations
if len(argspec.annotations) < len(argspec.args):
raise RuntimeError(f"Incomplete argument annotations on function {func.__qualname__}")
return argspec.annotations
complex_type_hints = (Any, Callable, Tuple)
sequence_types = (list, tuple)
class Function:
def __init__(
self,
func,
key,
namespace,
input_types=None,
value_type=None,
value_func=None,
template_func=None,
module=None,
variadic=False,
initializer_list_func=None,
export=False,
doc="",
group="",
hidden=False,
skip_replay=False,
missing_grad=False,
generic=False,
native_func=None,
defaults=None,
custom_replay_func=None,
native_snippet=None,
adj_native_snippet=None,
replay_snippet=None,
skip_forward_codegen=False,
skip_reverse_codegen=False,
custom_reverse_num_input_args=-1,
custom_reverse_mode=False,
overloaded_annotations=None,
code_transformers=None,
skip_adding_overload=False,
require_original_output_arg=False,
):
if code_transformers is None:
code_transformers = []
self.func = func # points to Python function decorated with @wp.func, may be None for builtins
self.key = key
self.namespace = namespace
self.value_type = value_type
self.value_func = value_func # a function that takes a list of args and a list of templates and returns the value type, e.g.: load(array, index) returns the type of value being loaded
self.template_func = template_func
self.input_types = {}
self.export = export
self.doc = doc
self.group = group
self.module = module
self.variadic = variadic # function can take arbitrary number of inputs, e.g.: printf()
self.defaults = defaults
# Function instance for a custom implementation of the replay pass
self.custom_replay_func = custom_replay_func
self.native_snippet = native_snippet
self.adj_native_snippet = adj_native_snippet
self.replay_snippet = replay_snippet
self.custom_grad_func = None
self.require_original_output_arg = require_original_output_arg
if initializer_list_func is None:
self.initializer_list_func = lambda x, y: False
else:
self.initializer_list_func = (
initializer_list_func # True if the arguments should be emitted as an initializer list in the c++ code
)
self.hidden = hidden # function will not be listed in docs
self.skip_replay = (
skip_replay # whether or not operation will be performed during the forward replay in the backward pass
)
self.missing_grad = missing_grad # whether or not builtin is missing a corresponding adjoint
self.generic = generic
# allow registering builtin functions with a different name in Python from the native code
if native_func is None:
self.native_func = key
else:
self.native_func = native_func
if func:
# user-defined function
# generic and concrete overload lookups by type signature
self.user_templates = {}
self.user_overloads = {}
# user defined (Python) function
self.adj = warp.codegen.Adjoint(
func,
is_user_function=True,
skip_forward_codegen=skip_forward_codegen,
skip_reverse_codegen=skip_reverse_codegen,
custom_reverse_num_input_args=custom_reverse_num_input_args,
custom_reverse_mode=custom_reverse_mode,
overload_annotations=overloaded_annotations,
transformers=code_transformers,
)
# record input types
for name, type in self.adj.arg_types.items():
if name == "return":
self.value_func = create_value_func(type)
else:
self.input_types[name] = type
else:
# builtin function
# embedded linked list of all overloads
# the builtin_functions dictionary holds
# the list head for a given key (func name)
self.overloads = []
# builtin (native) function, canonicalize argument types
for k, v in input_types.items():
self.input_types[k] = warp.types.type_to_warp(v)
# cache mangled name
if self.export and self.is_simple():
self.mangled_name = self.mangle()
else:
self.mangled_name = None
if not skip_adding_overload:
self.add_overload(self)
# add to current module
if module:
module.register_function(self, skip_adding_overload)
def __call__(self, *args, **kwargs):
# handles calling a builtin (native) function
# as if it was a Python function, i.e.: from
# within the CPython interpreter rather than
# from within a kernel (experimental).
if self.is_builtin() and self.mangled_name:
# For each of this function's existing overloads, we attempt to pack
# the given arguments into the C types expected by the corresponding
# parameters, and we rinse and repeat until we get a match.
for overload in self.overloads:
if overload.generic:
continue
success, return_value = call_builtin(overload, *args)
if success:
return return_value
# overload resolution or call failed
raise RuntimeError(
f"Couldn't find a function '{self.key}' compatible with "
f"the arguments '{', '.join(type(x).__name__ for x in args)}'"
)
if hasattr(self, "user_overloads") and len(self.user_overloads):
# user-defined function with overloads
if len(kwargs):
raise RuntimeError(
f"Error calling function '{self.key}', keyword arguments are not supported for user-defined overloads."
)
# try and find a matching overload
for overload in self.user_overloads.values():
if len(overload.input_types) != len(args):
continue
template_types = list(overload.input_types.values())
arg_names = list(overload.input_types.keys())
try:
# attempt to unify argument types with function template types
warp.types.infer_argument_types(args, template_types, arg_names)
return overload.func(*args)
except Exception:
continue
raise RuntimeError(f"Error calling function '{self.key}', no overload found for arguments {args}")
# user-defined function with no overloads
if self.func is None:
raise RuntimeError(f"Error calling function '{self.key}', function is undefined")
# this function has no overloads, call it like a plain Python function
return self.func(*args, **kwargs)
def is_builtin(self):
return self.func is None
def is_simple(self):
if self.variadic:
return False
# only export simple types that don't use arrays
for v in self.input_types.values():
if isinstance(v, warp.array) or v in complex_type_hints:
return False
if type(self.value_type) in sequence_types:
return False
return True
def mangle(self):
# builds a mangled name for the C-exported
# function, e.g.: builtin_normalize_vec3()
name = "builtin_" + self.key
types = []
for t in self.input_types.values():
types.append(t.__name__)
return "_".join([name, *types])
def add_overload(self, f):
if self.is_builtin():
# todo: note that it is an error to add two functions
# with the exact same signature as this would cause compile
# errors during compile time. We should check here if there
# is a previously created function with the same signature
self.overloads.append(f)
# make sure variadic overloads appear last so non variadic
# ones are matched first:
self.overloads.sort(key=operator.attrgetter("variadic"))
else:
# get function signature based on the input types
sig = warp.types.get_signature(
f.input_types.values(), func_name=f.key, arg_names=list(f.input_types.keys())
)
# check if generic
if warp.types.is_generic_signature(sig):
if sig in self.user_templates:
raise RuntimeError(
f"Duplicate generic function overload {self.key} with arguments {f.input_types.values()}"
)
self.user_templates[sig] = f
else:
if sig in self.user_overloads:
raise RuntimeError(
f"Duplicate function overload {self.key} with arguments {f.input_types.values()}"
)
self.user_overloads[sig] = f
def get_overload(self, arg_types):
assert not self.is_builtin()
sig = warp.types.get_signature(arg_types, func_name=self.key)
f = self.user_overloads.get(sig)
if f is not None:
return f
else:
for f in self.user_templates.values():
if len(f.input_types) != len(arg_types):
continue
# try to match the given types to the function template types
template_types = list(f.input_types.values())
args_matched = True
for i in range(len(arg_types)):
if not warp.types.type_matches_template(arg_types[i], template_types[i]):
args_matched = False
break
if args_matched:
# instantiate this function with the specified argument types
arg_names = f.input_types.keys()
overload_annotations = dict(zip(arg_names, arg_types))
ovl = shallowcopy(f)
ovl.adj = warp.codegen.Adjoint(f.func, overload_annotations)
ovl.input_types = overload_annotations
ovl.value_func = None
self.user_overloads[sig] = ovl
return ovl
# failed to find overload
return None
def __repr__(self):
inputs_str = ", ".join([f"{k}: {warp.types.type_repr(v)}" for k, v in self.input_types.items()])
return f"<Function {self.key}({inputs_str})>"
def call_builtin(func: Function, *params) -> Tuple[bool, Any]:
uses_non_warp_array_type = False
warp.context.init()
# Retrieve the built-in function from Warp's dll.
c_func = getattr(warp.context.runtime.core, func.mangled_name)
# Try gathering the parameters that the function expects and pack them
# into their corresponding C types.
c_params = []
for i, (_, arg_type) in enumerate(func.input_types.items()):
param = params[i]
try:
iter(param)
except TypeError:
is_array = False
else:
is_array = True
if is_array:
if not issubclass(arg_type, ctypes.Array):
return (False, None)
# The argument expects a built-in Warp type like a vector or a matrix.
c_param = None
if isinstance(param, ctypes.Array):
# The given parameter is also a built-in Warp type, so we only need
# to make sure that it matches with the argument.
if not warp.types.types_equal(type(param), arg_type):
return (False, None)
if isinstance(param, arg_type):
c_param = param
else:
# Cast the value to its argument type to make sure that it
# can be assigned to the field of the `Param` struct.
# This could error otherwise when, for example, the field type
# is set to `vec3i` while the value is of type `vector(length=3, dtype=int)`,
# even though both types are semantically identical.
c_param = arg_type(param)
else:
# Flatten the parameter values into a flat 1-D array.
arr = []
ndim = 1
stack = [(0, param)]
while stack:
depth, elem = stack.pop(0)
try:
# If `elem` is a sequence, then it should be possible
# to add its elements to the stack for later processing.
stack.extend((depth + 1, x) for x in elem)
except TypeError:
# Since `elem` doesn't seem to be a sequence,
# we must have a leaf value that we need to add to our
# resulting array.
arr.append(elem)
ndim = max(depth, ndim)
assert ndim > 0
# Ensure that if the given parameter value is, say, a 2-D array,
# then we try to resolve it against a matrix argument rather than
# a vector.
if ndim > len(arg_type._shape_):
return (False, None)
elem_count = len(arr)
if elem_count != arg_type._length_:
return (False, None)
# Retrieve the element type of the sequence while ensuring
# that it's homogeneous.
elem_type = type(arr[0])
for i in range(1, elem_count):
if type(arr[i]) is not elem_type:
raise ValueError("All array elements must share the same type.")
expected_elem_type = arg_type._wp_scalar_type_
if not (
elem_type is expected_elem_type
or (elem_type is float and expected_elem_type is warp.types.float32)
or (elem_type is int and expected_elem_type is warp.types.int32)
or (elem_type is bool and expected_elem_type is warp.types.bool)
or (
issubclass(elem_type, np.number)
and warp.types.np_dtype_to_warp_type[np.dtype(elem_type)] is expected_elem_type
)
):
# The parameter value has a type not matching the type defined
# for the corresponding argument.
return (False, None)
if elem_type in warp.types.int_types:
# Pass the value through the expected integer type
# in order to evaluate any integer wrapping.
# For example `uint8(-1)` should result in the value `-255`.
arr = tuple(elem_type._type_(x.value).value for x in arr)
elif elem_type in warp.types.float_types:
# Extract the floating-point values.
arr = tuple(x.value for x in arr)
c_param = arg_type()
if warp.types.type_is_matrix(arg_type):
rows, cols = arg_type._shape_
for i in range(rows):
idx_start = i * cols
idx_end = idx_start + cols
c_param[i] = arr[idx_start:idx_end]
else:
c_param[:] = arr
uses_non_warp_array_type = True
c_params.append(ctypes.byref(c_param))
else:
if issubclass(arg_type, ctypes.Array):
return (False, None)
if not (
isinstance(param, arg_type)
or (type(param) is float and arg_type is warp.types.float32) # noqa: E721
or (type(param) is int and arg_type is warp.types.int32) # noqa: E721
or (type(param) is bool and arg_type is warp.types.bool) # noqa: E721
or warp.types.np_dtype_to_warp_type.get(getattr(param, "dtype", None)) is arg_type
):
return (False, None)
if type(param) in warp.types.scalar_types:
param = param.value
# try to pack as a scalar type
if arg_type == warp.types.float16:
c_params.append(arg_type._type_(warp.types.float_to_half_bits(param)))
else:
c_params.append(arg_type._type_(param))
# returns the corresponding ctype for a scalar or vector warp type
value_type = func.value_func(None, None, None)
if value_type == float:
value_ctype = ctypes.c_float
elif value_type == int:
value_ctype = ctypes.c_int32
elif value_type == bool:
value_ctype = ctypes.c_bool
elif issubclass(value_type, (ctypes.Array, ctypes.Structure)):
value_ctype = value_type
else:
# scalar type
value_ctype = value_type._type_
# construct return value (passed by address)
ret = value_ctype()
ret_addr = ctypes.c_void_p(ctypes.addressof(ret))
c_params.append(ret_addr)
# Call the built-in function from Warp's dll.
c_func(*c_params)
if uses_non_warp_array_type:
warp.utils.warn(
"Support for built-in functions called with non-Warp array types, "
"such as lists, tuples, NumPy arrays, and others, will be dropped "
"in the future. Use a Warp type such as `wp.vec`, `wp.mat`, "
"`wp.quat`, or `wp.transform`.",
DeprecationWarning,
stacklevel=3,
)
if issubclass(value_ctype, ctypes.Array) or issubclass(value_ctype, ctypes.Structure):
# return vector types as ctypes
return (True, ret)
if value_type == warp.types.float16:
return (True, warp.types.half_bits_to_float(ret.value))
# return scalar types as int/float
return (True, ret.value)
class KernelHooks:
def __init__(self, forward, backward):
self.forward = forward
self.backward = backward
# caches source and compiled entry points for a kernel (will be populated after module loads)
class Kernel:
def __init__(self, func, key=None, module=None, options=None, code_transformers=None):
self.func = func
if module is None:
self.module = get_module(func.__module__)
else:
self.module = module
if key is None:
unique_key = self.module.generate_unique_kernel_key(func.__name__)
self.key = unique_key
else:
self.key = key
self.options = {} if options is None else options
if code_transformers is None:
code_transformers = []
self.adj = warp.codegen.Adjoint(func, transformers=code_transformers)
# check if generic
self.is_generic = False
for arg_type in self.adj.arg_types.values():
if warp.types.type_is_generic(arg_type):
self.is_generic = True
break
# unique signature (used to differentiate instances of generic kernels during codegen)
self.sig = ""
# known overloads for generic kernels, indexed by type signature
self.overloads = {}
# argument indices by name
self.arg_indices = {a.label: i for i, a in enumerate(self.adj.args)}
if self.module:
self.module.register_kernel(self)
def infer_argument_types(self, args):
template_types = list(self.adj.arg_types.values())
if len(args) != len(template_types):
raise RuntimeError(f"Invalid number of arguments for kernel {self.key}")
arg_names = list(self.adj.arg_types.keys())
return warp.types.infer_argument_types(args, template_types, arg_names)
def add_overload(self, arg_types):
if len(arg_types) != len(self.adj.arg_types):
raise RuntimeError(f"Invalid number of arguments for kernel {self.key}")
# get a type signature from the given argument types
sig = warp.types.get_signature(arg_types, func_name=self.key)
ovl = self.overloads.get(sig)
if ovl is not None:
# return the existing overload matching the signature
return ovl
arg_names = list(self.adj.arg_types.keys())
template_types = list(self.adj.arg_types.values())
# make sure all argument types are concrete and match the kernel parameters
for i in range(len(arg_types)):
if not warp.types.type_matches_template(arg_types[i], template_types[i]):
if warp.types.type_is_generic(arg_types[i]):
raise TypeError(
f"Kernel {self.key} argument '{arg_names[i]}' cannot be generic, got {arg_types[i]}"
)
else:
raise TypeError(
f"Kernel {self.key} argument '{arg_names[i]}' type mismatch: expected {template_types[i]}, got {arg_types[i]}"
)
overload_annotations = dict(zip(arg_names, arg_types))
# instantiate this kernel with the given argument types
ovl = shallowcopy(self)
ovl.adj = warp.codegen.Adjoint(self.func, overload_annotations)
ovl.is_generic = False
ovl.overloads = {}
ovl.sig = sig
self.overloads[sig] = ovl
self.module.unload()
return ovl
def get_overload(self, arg_types):
sig = warp.types.get_signature(arg_types, func_name=self.key)
return self.overloads.get(sig)
def get_mangled_name(self):
if self.sig:
return f"{self.key}_{self.sig}"
else:
return self.key
# ----------------------
# decorator to register function, @func
def func(f):
name = warp.codegen.make_full_qualified_name(f)
m = get_module(f.__module__)
Function(
func=f, key=name, namespace="", module=m, value_func=None
) # value_type not known yet, will be inferred during Adjoint.build()
# use the top of the list of overloads for this key
g = m.functions[name]
# copy over the function attributes, including docstring
return functools.update_wrapper(g, f)
def func_native(snippet, adj_snippet=None, replay_snippet=None):
"""
Decorator to register native code snippet, @func_native
"""
def snippet_func(f):
name = warp.codegen.make_full_qualified_name(f)
m = get_module(f.__module__)
Function(
func=f,
key=name,
namespace="",
module=m,
native_snippet=snippet,
adj_native_snippet=adj_snippet,
replay_snippet=replay_snippet,
) # value_type not known yet, will be inferred during Adjoint.build()
g = m.functions[name]
# copy over the function attributes, including docstring
return functools.update_wrapper(g, f)
return snippet_func
def func_grad(forward_fn):
"""
Decorator to register a custom gradient function for a given forward function.
The function signature must correspond to one of the function overloads in the following way:
the first part of the input arguments are the original input variables with the same types as their
corresponding arguments in the original function, and the second part of the input arguments are the
adjoint variables of the output variables (if available) of the original function with the same types as the
output variables. The function must not return anything.
"""
def wrapper(grad_fn):
generic = any(warp.types.type_is_generic(x) for x in forward_fn.input_types.values())
if generic:
raise RuntimeError(
f"Cannot define custom grad definition for {forward_fn.key} since functions with generic input arguments are not yet supported."
)
reverse_args = {}
reverse_args.update(forward_fn.input_types)
# create temporary Adjoint instance to analyze the function signature
adj = warp.codegen.Adjoint(
grad_fn, skip_forward_codegen=True, skip_reverse_codegen=False, transformers=forward_fn.adj.transformers
)
from warp.types import types_equal
grad_args = adj.args
grad_sig = warp.types.get_signature([arg.type for arg in grad_args], func_name=forward_fn.key)
generic = any(warp.types.type_is_generic(x.type) for x in grad_args)
if generic:
raise RuntimeError(
f"Cannot define custom grad definition for {forward_fn.key} since the provided grad function has generic input arguments."
)
def match_function(f):
# check whether the function overload f matches the signature of the provided gradient function
if not hasattr(f.adj, "return_var"):
# we have to temporarily build this function to figure out its return type(s);
# note that we do not have a ModuleBuilder instance here at this wrapping stage, hence we
# have to create a dummy builder
builder = ModuleBuilder(Module("dummy", None), f.module.options)
f.adj.build(builder)
expected_args = list(f.input_types.items())
if f.adj.return_var is not None:
expected_args += [(f"adj_ret_{var.label}", var.type) for var in f.adj.return_var]
if len(grad_args) != len(expected_args):
return False
if any(not types_equal(a.type, exp_type) for a, (_, exp_type) in zip(grad_args, expected_args)):
return False
return True
def add_custom_grad(f: Function):
# register custom gradient function
f.custom_grad_func = Function(
grad_fn,
key=f.key,
namespace=f.namespace,
input_types=reverse_args,
value_func=None,
module=f.module,
template_func=f.template_func,
skip_forward_codegen=True,
custom_reverse_mode=True,
custom_reverse_num_input_args=len(f.input_types),
skip_adding_overload=False,
code_transformers=f.adj.transformers,
)
f.adj.skip_reverse_codegen = True
if hasattr(forward_fn, "user_overloads") and len(forward_fn.user_overloads):
# find matching overload for which this grad function is defined
for sig, f in forward_fn.user_overloads.items():
if not grad_sig.startswith(sig):
continue
if match_function(f):
add_custom_grad(f)
return grad_fn
raise RuntimeError(
f"No function overload found for gradient function {grad_fn.__qualname__} for function {forward_fn.key}"
)
else:
# resolve return variables
forward_fn.adj.build(None, forward_fn.module.options)
expected_args = list(forward_fn.input_types.items())
if forward_fn.adj.return_var is not None:
expected_args += [(f"adj_ret_{var.label}", var.type) for var in forward_fn.adj.return_var]
# check if the signature matches this function
if match_function(forward_fn):
add_custom_grad(forward_fn)
else:
raise RuntimeError(
f"Gradient function {grad_fn.__qualname__} for function {forward_fn.key} has an incorrect signature. The arguments must match the "
"forward function arguments plus the adjoint variables corresponding to the return variables:"
f"\n{', '.join(f'{nt[0]}: {nt[1].__name__}' for nt in expected_args)}"
)
return grad_fn
return wrapper
def func_replay(forward_fn):
"""
Decorator to register a custom replay function for a given forward function.
The replay function is the function version that is called in the forward phase of the backward pass (replay mode) and corresponds to the forward function by default.
The provided function has to match the signature of one of the original forward function overloads.
"""
def wrapper(replay_fn):
generic = any(warp.types.type_is_generic(x) for x in forward_fn.input_types.values())
if generic:
raise RuntimeError(
f"Cannot define custom replay definition for {forward_fn.key} since functions with generic input arguments are not yet supported."
)
args = get_function_args(replay_fn)
arg_types = list(args.values())
generic = any(warp.types.type_is_generic(x) for x in arg_types)
if generic:
raise RuntimeError(
f"Cannot define custom replay definition for {forward_fn.key} since the provided replay function has generic input arguments."
)
f = forward_fn.get_overload(arg_types)
if f is None:
inputs_str = ", ".join([f"{k}: {v.__name__}" for k, v in args.items()])
raise RuntimeError(
f"Could not find forward definition of function {forward_fn.key} that matches custom replay definition with arguments:\n{inputs_str}"
)
f.custom_replay_func = Function(
replay_fn,
key=f"replay_{f.key}",
namespace=f.namespace,
input_types=f.input_types,
value_func=f.value_func,
module=f.module,
template_func=f.template_func,
skip_reverse_codegen=True,
skip_adding_overload=True,
code_transformers=f.adj.transformers,
)
return replay_fn
return wrapper
# decorator to register kernel, @kernel, custom_name may be a string
# that creates a kernel with a different name from the actual function
def kernel(f=None, *, enable_backward=None):
def wrapper(f, *args, **kwargs):
options = {}
if enable_backward is not None:
options["enable_backward"] = enable_backward
m = get_module(f.__module__)
k = Kernel(
func=f,
key=warp.codegen.make_full_qualified_name(f),
module=m,
options=options,
)
k = functools.update_wrapper(k, f)
return k
if f is None:
# Arguments were passed to the decorator.
return wrapper
return wrapper(f)
# decorator to register struct, @struct
def struct(c):
m = get_module(c.__module__)
s = warp.codegen.Struct(cls=c, key=warp.codegen.make_full_qualified_name(c), module=m)
s = functools.update_wrapper(s, c)
return s
# overload a kernel with the given argument types
def overload(kernel, arg_types=None):
if isinstance(kernel, Kernel):
# handle cases where user calls us directly, e.g. wp.overload(kernel, [args...])
if not kernel.is_generic:
raise RuntimeError(f"Only generic kernels can be overloaded. Kernel {kernel.key} is not generic")
if isinstance(arg_types, list):
arg_list = arg_types
elif isinstance(arg_types, dict):
# substitute named args
arg_list = [a.type for a in kernel.adj.args]
for arg_name, arg_type in arg_types.items():
idx = kernel.arg_indices.get(arg_name)
if idx is None:
raise RuntimeError(f"Invalid argument name '{arg_name}' in overload of kernel {kernel.key}")
arg_list[idx] = arg_type
elif arg_types is None:
arg_list = []
else:
raise TypeError("Kernel overload types must be given in a list or dict")
# return new kernel overload
return kernel.add_overload(arg_list)
elif isinstance(kernel, types.FunctionType):
# handle cases where user calls us as a function decorator (@wp.overload)
# ensure this function name corresponds to a kernel
fn = kernel
module = get_module(fn.__module__)
kernel = module.kernels.get(fn.__name__)
if kernel is None:
raise RuntimeError(f"Failed to find a kernel named '{fn.__name__}' in module {fn.__module__}")
if not kernel.is_generic:
raise RuntimeError(f"Only generic kernels can be overloaded. Kernel {kernel.key} is not generic")
# ensure the function is defined without a body, only ellipsis (...), pass, or a string expression
# TODO: show we allow defining a new body for kernel overloads?
source = inspect.getsource(fn)
tree = ast.parse(source)
assert isinstance(tree, ast.Module)
assert isinstance(tree.body[0], ast.FunctionDef)
func_body = tree.body[0].body
for node in func_body:
if isinstance(node, ast.Pass):
continue
elif isinstance(node, ast.Expr) and isinstance(node.value, (ast.Str, ast.Ellipsis)):
continue
raise RuntimeError(
"Illegal statement in kernel overload definition. Only pass, ellipsis (...), comments, or docstrings are allowed"
)
# ensure all arguments are annotated
argspec = inspect.getfullargspec(fn)
if len(argspec.annotations) < len(argspec.args):
raise RuntimeError(f"Incomplete argument annotations on kernel overload {fn.__name__}")
# get type annotation list
arg_list = []
for arg_name, arg_type in argspec.annotations.items():
if arg_name != "return":
arg_list.append(arg_type)
# add new overload, but we must return the original kernel from @wp.overload decorator!
kernel.add_overload(arg_list)
return kernel
else:
raise RuntimeError("wp.overload() called with invalid argument!")
builtin_functions = {}
def get_generic_vtypes():
# get a list of existing generic vector types (includes matrices and stuff)
# so we can match arguments against them:
generic_vtypes = tuple(x for x in warp.types.vector_types if hasattr(x, "_wp_generic_type_str_"))
# deduplicate identical types:
typedict = {(t._wp_generic_type_str_, str(t._wp_type_params_)): t for t in generic_vtypes}
return tuple(typedict[k] for k in sorted(typedict.keys()))
generic_vtypes = get_generic_vtypes()
scalar_types = {}
scalar_types.update({x: x for x in warp.types.scalar_types})
scalar_types.update({x: x._wp_scalar_type_ for x in warp.types.vector_types})
def add_builtin(
key,
input_types=None,
constraint=None,
value_type=None,
value_func=None,
template_func=None,
doc="",
namespace="wp::",
variadic=False,
initializer_list_func=None,
export=True,
group="Other",
hidden=False,
skip_replay=False,
missing_grad=False,
native_func=None,
defaults=None,
require_original_output_arg=False,
):
if input_types is None:
input_types = {}
# wrap simple single-type functions with a value_func()
if value_func is None:
def value_func(args, kwds, templates):
return value_type
if initializer_list_func is None:
def initializer_list_func(args, templates):
return False
if defaults is None:
defaults = {}
# Add specialized versions of this builtin if it's generic by matching arguments against
# hard coded types. We do this so you can use hard coded warp types outside kernels:
generic = False
for x in input_types.values():
if warp.types.type_is_generic(x):
generic = True
break
if generic and export:
# collect the parent type names of all the generic arguments:
genericset = set()
for t in input_types.values():
if hasattr(t, "_wp_generic_type_hint_"):
genericset.add(t._wp_generic_type_hint_)
elif warp.types.type_is_generic_scalar(t):
genericset.add(t)
# for each of those type names, get a list of all hard coded types derived
# from them:
gtypes = []
for t in genericset:
if t is warp.types.Float:
value = warp.types.float_types
elif t == warp.types.Scalar:
value = warp.types.scalar_types
elif t == warp.types.Int:
value = warp.types.int_types
else:
value = tuple(x for x in generic_vtypes if x._wp_generic_type_hint_ == t)
gtypes.append((t, value))
# find the scalar data types supported by all the arguments by intersecting
# sets:
scalartypes = tuple({scalar_types[x] for x in v} for _, v in gtypes)
if scalartypes:
scalartypes = set.intersection(*scalartypes)
scalartypes = sorted(scalartypes, key=str)
# generate function calls for each of these scalar types:
for stype in scalartypes:
# find concrete types for this scalar type (eg if the scalar type is float32
# this dict will look something like this:
# {"vec":[wp.vec2,wp.vec3,wp.vec4], "mat":[wp.mat22,wp.mat33,wp.mat44]})
consistenttypes = {k: tuple(x for x in v if scalar_types[x] == stype) for k, v in gtypes}
# gotta try generating function calls for all combinations of these argument types
# now.
typelists = []
for param in input_types.values():
if warp.types.type_is_generic_scalar(param):
l = (stype,)
elif hasattr(param, "_wp_generic_type_hint_"):
l = tuple(
x
for x in consistenttypes[param._wp_generic_type_hint_]
if warp.types.types_equal(param, x, match_generic=True)
)
else:
l = (param,)
typelists.append(l)
for argtypes in itertools.product(*typelists):
# Some of these argument lists won't work, eg if the function is mul(), we won't be
# able to do a matrix vector multiplication for a mat22 and a vec3. The `constraint`
# function determines which combinations are valid:
if constraint:
if constraint(argtypes) is False:
continue
return_type = value_func(argtypes, {}, [])
# The return_type might just be vector_t(length=3,dtype=wp.float32), so we've got to match that
# in the list of hard coded types so it knows it's returning one of them:
if hasattr(return_type, "_wp_generic_type_hint_"):
return_type_match = tuple(
x
for x in generic_vtypes
if x._wp_generic_type_hint_ == return_type._wp_generic_type_hint_
and x._wp_type_params_ == return_type._wp_type_params_
)
if not return_type_match:
continue
return_type = return_type_match[0]
# finally we can generate a function call for these concrete types:
add_builtin(
key,
input_types=dict(zip(input_types.keys(), argtypes)),
value_type=return_type,
doc=doc,
namespace=namespace,
variadic=variadic,
initializer_list_func=initializer_list_func,
export=export,
group=group,
hidden=True,
skip_replay=skip_replay,
missing_grad=missing_grad,
require_original_output_arg=require_original_output_arg,
)
func = Function(
func=None,
key=key,
namespace=namespace,
input_types=input_types,
value_type=value_type,
value_func=value_func,
template_func=template_func,
variadic=variadic,
initializer_list_func=initializer_list_func,
export=export,
doc=doc,
group=group,
hidden=hidden,
skip_replay=skip_replay,
missing_grad=missing_grad,
generic=generic,
native_func=native_func,
defaults=defaults,
require_original_output_arg=require_original_output_arg,
)
if key in builtin_functions:
builtin_functions[key].add_overload(func)
else:
builtin_functions[key] = func
# export means the function will be added to the `warp` module namespace
# so that users can call it directly from the Python interpreter
if export:
if hasattr(warp, key):
# check that we haven't already created something at this location
# if it's just an overload stub for auto-complete then overwrite it
if getattr(warp, key).__name__ != "_overload_dummy":
raise RuntimeError(
f"Trying to register builtin function '{key}' that would overwrite existing object."
)
setattr(warp, key, func)
# global dictionary of modules
user_modules = {}
def get_module(name):
# some modules might be manually imported using `importlib` without being
# registered into `sys.modules`
parent = sys.modules.get(name, None)
parent_loader = None if parent is None else parent.__loader__
if name in user_modules:
# check if the Warp module was created using a different loader object
# if so, we assume the file has changed and we recreate the module to
# clear out old kernels / functions
if user_modules[name].loader is not parent_loader:
old_module = user_modules[name]
# Unload the old module and recursively unload all of its dependents.
# This ensures that dependent modules will be re-hashed and reloaded on next launch.
# The visited set tracks modules already visited to avoid circular references.
def unload_recursive(module, visited):
module.unload()
visited.add(module)
for d in module.dependents:
if d not in visited:
unload_recursive(d, visited)
unload_recursive(old_module, visited=set())
# clear out old kernels, funcs, struct definitions
old_module.kernels = {}
old_module.functions = {}
old_module.constants = {}
old_module.structs = {}
old_module.loader = parent_loader
return user_modules[name]
else:
# else Warp module didn't exist yet, so create a new one
user_modules[name] = warp.context.Module(name, parent_loader)
return user_modules[name]
class ModuleBuilder:
def __init__(self, module, options):
self.functions = {}
self.structs = {}
self.options = options
self.module = module
self.deferred_functions = []
# build all functions declared in the module
for func in module.functions.values():
for f in func.user_overloads.values():
self.build_function(f)
if f.custom_replay_func is not None:
self.build_function(f.custom_replay_func)
# build all kernel entry points
for kernel in module.kernels.values():
if not kernel.is_generic:
self.build_kernel(kernel)
else:
for k in kernel.overloads.values():
self.build_kernel(k)
# build all functions outside this module which are called from functions or kernels in this module
for func in self.deferred_functions:
self.build_function(func)
def build_struct_recursive(self, struct: warp.codegen.Struct):
structs = []
stack = [struct]
while stack:
s = stack.pop()
structs.append(s)
for var in s.vars.values():
if isinstance(var.type, warp.codegen.Struct):
stack.append(var.type)
elif isinstance(var.type, warp.types.array) and isinstance(var.type.dtype, warp.codegen.Struct):
stack.append(var.type.dtype)
# Build them in reverse to generate a correct dependency order.
for s in reversed(structs):
self.build_struct(s)
def build_struct(self, struct):
self.structs[struct] = None
def build_kernel(self, kernel):
kernel.adj.build(self)
if kernel.adj.return_var is not None:
if kernel.adj.return_var.ctype() != "void":
raise TypeError(f"Error, kernels can't have return values, got: {kernel.adj.return_var}")
def build_function(self, func):
if func in self.functions:
return
else:
func.adj.build(self)
# complete the function return type after we have analyzed it (inferred from return statement in ast)
if not func.value_func:
def wrap(adj):
def value_type(arg_types, kwds, templates):
if adj.return_var is None or len(adj.return_var) == 0:
return None
if len(adj.return_var) == 1:
return adj.return_var[0].type
else:
return [v.type for v in adj.return_var]
return value_type
func.value_func = wrap(func.adj)
# use dict to preserve import order
self.functions[func] = None
def codegen(self, device):
source = ""
# code-gen structs
for struct in self.structs.keys():
source += warp.codegen.codegen_struct(struct)
# code-gen all imported functions
for func in self.functions.keys():
if func.native_snippet is None:
source += warp.codegen.codegen_func(
func.adj, c_func_name=func.native_func, device=device, options=self.options
)
else:
source += warp.codegen.codegen_snippet(
func.adj,
name=func.key,
snippet=func.native_snippet,
adj_snippet=func.adj_native_snippet,
replay_snippet=func.replay_snippet,
)
for kernel in self.module.kernels.values():
# each kernel gets an entry point in the module
if not kernel.is_generic:
source += warp.codegen.codegen_kernel(kernel, device=device, options=self.options)
source += warp.codegen.codegen_module(kernel, device=device)
else:
for k in kernel.overloads.values():
source += warp.codegen.codegen_kernel(k, device=device, options=self.options)
source += warp.codegen.codegen_module(k, device=device)
# add headers
if device == "cpu":
source = warp.codegen.cpu_module_header + source
else:
source = warp.codegen.cuda_module_header + source
return source
# -----------------------------------------------------
# stores all functions and kernels for a Python module
# creates a hash of the function to use for checking
# build cache
class Module:
def __init__(self, name, loader):
self.name = name
self.loader = loader
self.kernels = {}
self.functions = {}
self.constants = {} # Any constants referenced in this module including those defined in other modules
self.structs = {}
self.cpu_module = None
self.cuda_modules = {} # module lookup by CUDA context
self.cpu_build_failed = False
self.cuda_build_failed = False
self.options = {
"max_unroll": warp.config.max_unroll,
"enable_backward": warp.config.enable_backward,
"fast_math": False,
"cuda_output": None, # supported values: "ptx", "cubin", or None (automatic)
"mode": warp.config.mode,
}
# kernel hook lookup per device
# hooks are stored with the module so they can be easily cleared when the module is reloaded.
# -> See ``Module.get_kernel_hooks()``
self.kernel_hooks = {}
# Module dependencies are determined by scanning each function
# and kernel for references to external functions and structs.
#
# When a referenced module is modified, all of its dependents need to be reloaded
# on the next launch. To detect this, a module's hash recursively includes
# all of its references.
# -> See ``Module.hash_module()``
#
# The dependency mechanism works for both static and dynamic (runtime) modifications.
# When a module is reloaded at runtime, we recursively unload all of its
# dependents, so that they will be re-hashed and reloaded on the next launch.
# -> See ``get_module()``
self.references = set() # modules whose content we depend on
self.dependents = set() # modules that depend on our content
# Since module hashing is recursive, we improve performance by caching the hash of the
# module contents (kernel source, function source, and struct source).
# After all kernels, functions, and structs are added to the module (usually at import time),
# the content hash doesn't change.
# -> See ``Module.hash_module_recursive()``
self.content_hash = None
# number of times module auto-generates kernel key for user
# used to ensure unique kernel keys
self.count = 0
def register_struct(self, struct):
self.structs[struct.key] = struct
# for a reload of module on next launch
self.unload()
def register_kernel(self, kernel):
self.kernels[kernel.key] = kernel
self.find_references(kernel.adj)
# for a reload of module on next launch
self.unload()
def register_function(self, func, skip_adding_overload=False):
if func.key not in self.functions:
self.functions[func.key] = func
else:
# Check whether the new function's signature match any that has
# already been registered. If so, then we simply override it, as
# Python would do it, otherwise we register it as a new overload.
func_existing = self.functions[func.key]
sig = warp.types.get_signature(
func.input_types.values(),
func_name=func.key,
arg_names=list(func.input_types.keys()),
)
sig_existing = warp.types.get_signature(
func_existing.input_types.values(),
func_name=func_existing.key,
arg_names=list(func_existing.input_types.keys()),
)
if sig == sig_existing:
self.functions[func.key] = func
elif not skip_adding_overload:
func_existing.add_overload(func)
self.find_references(func.adj)
# for a reload of module on next launch
self.unload()
def generate_unique_kernel_key(self, key):
unique_key = f"{key}_{self.count}"
self.count += 1
return unique_key
# collect all referenced functions / structs
# given the AST of a function or kernel
def find_references(self, adj):
def add_ref(ref):
if ref is not self:
self.references.add(ref)
ref.dependents.add(self)
# scan for function calls
for node in ast.walk(adj.tree):
if isinstance(node, ast.Call):
try:
# try to resolve the function
func, _ = adj.resolve_static_expression(node.func, eval_types=False)
# if this is a user-defined function, add a module reference
if isinstance(func, warp.context.Function) and func.module is not None:
add_ref(func.module)
except Exception:
# Lookups may fail for builtins, but that's ok.
# Lookups may also fail for functions in this module that haven't been imported yet,
# and that's ok too (not an external reference).
pass
# scan for structs
for arg in adj.args:
if isinstance(arg.type, warp.codegen.Struct) and arg.type.module is not None:
add_ref(arg.type.module)
def hash_module(self, recompute_content_hash=False):
"""Recursively compute and return a hash for the module.
If ``recompute_content_hash`` is False, each module's previously
computed ``content_hash`` will be used.
"""
def get_annotations(obj: Any) -> Mapping[str, Any]:
"""Alternative to `inspect.get_annotations()` for Python 3.9 and older."""
# See https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
if isinstance(obj, type):
return obj.__dict__.get("__annotations__", {})
return getattr(obj, "__annotations__", {})
def get_type_name(type_hint):
if isinstance(type_hint, warp.codegen.Struct):
return get_type_name(type_hint.cls)
return type_hint
def hash_recursive(module, visited):
# Hash this module, including all referenced modules recursively.
# The visited set tracks modules already visited to avoid circular references.
# check if we need to update the content hash
if not module.content_hash or recompute_content_hash:
# recompute content hash
ch = hashlib.sha256()
# Start with an empty constants dictionary in case any have been removed
module.constants = {}
# struct source
for struct in module.structs.values():
s = ",".join(
"{}: {}".format(name, get_type_name(type_hint))
for name, type_hint in get_annotations(struct.cls).items()
)
ch.update(bytes(s, "utf-8"))
# functions source
for func in module.functions.values():
s = func.adj.source
ch.update(bytes(s, "utf-8"))
if func.custom_grad_func:
s = func.custom_grad_func.adj.source
ch.update(bytes(s, "utf-8"))
if func.custom_replay_func:
s = func.custom_replay_func.adj.source
if func.replay_snippet:
s = func.replay_snippet
if func.native_snippet:
s = func.native_snippet
ch.update(bytes(s, "utf-8"))
if func.adj_native_snippet:
s = func.adj_native_snippet
ch.update(bytes(s, "utf-8"))
# cache func arg types
for arg, arg_type in func.adj.arg_types.items():
s = f"{arg}: {get_type_name(arg_type)}"
ch.update(bytes(s, "utf-8"))
# Populate constants referenced in this function
if func.adj:
module.constants.update(func.adj.get_constant_references())
# kernel source
for kernel in module.kernels.values():
ch.update(bytes(kernel.key, "utf-8"))
ch.update(bytes(kernel.adj.source, "utf-8"))
# cache kernel arg types
for arg, arg_type in kernel.adj.arg_types.items():
s = f"{arg}: {get_type_name(arg_type)}"
ch.update(bytes(s, "utf-8"))
# for generic kernels the Python source is always the same,
# but we hash the type signatures of all the overloads
if kernel.is_generic:
for sig in sorted(kernel.overloads.keys()):
ch.update(bytes(sig, "utf-8"))
# Populate constants referenced in this kernel
module.constants.update(kernel.adj.get_constant_references())
# constants referenced in this module
for constant_name, constant_value in module.constants.items():
ch.update(bytes(constant_name, "utf-8"))
# hash the constant value
if isinstance(constant_value, builtins.bool):
# This needs to come before the check for `int` since all boolean
# values are also instances of `int`.
ch.update(struct_pack("?", constant_value))
elif isinstance(constant_value, int):
ch.update(struct_pack("<q", constant_value))
elif isinstance(constant_value, float):
ch.update(struct_pack("<d", constant_value))
elif isinstance(constant_value, warp.types.float16):
# float16 is a special case
p = ctypes.pointer(ctypes.c_float(constant_value.value))
ch.update(p.contents)
elif isinstance(constant_value, tuple(warp.types.scalar_types)):
p = ctypes.pointer(constant_value._type_(constant_value.value))
ch.update(p.contents)
elif isinstance(constant_value, ctypes.Array):
ch.update(bytes(constant_value))
else:
raise RuntimeError(f"Invalid constant type: {type(constant_value)}")
module.content_hash = ch.digest()
h = hashlib.sha256()
# content hash
h.update(module.content_hash)
# configuration parameters
for k in sorted(module.options.keys()):
s = f"{k}={module.options[k]}"
h.update(bytes(s, "utf-8"))
# ensure to trigger recompilation if flags affecting kernel compilation are changed
if warp.config.verify_fp:
h.update(bytes("verify_fp", "utf-8"))
h.update(bytes(warp.config.mode, "utf-8"))
# recurse on references
visited.add(module)
sorted_deps = sorted(module.references, key=lambda m: m.name)
for dep in sorted_deps:
if dep not in visited:
dep_hash = hash_recursive(dep, visited)
h.update(dep_hash)
return h.digest()
return hash_recursive(self, visited=set())
def load(self, device) -> bool:
from warp.utils import ScopedTimer
device = get_device(device)
if device.is_cpu:
# check if already loaded
if self.cpu_module:
return True
# avoid repeated build attempts
if self.cpu_build_failed:
return False
if not warp.is_cpu_available():
raise RuntimeError("Failed to build CPU module because no CPU buildchain was found")
else:
# check if already loaded
if device.context in self.cuda_modules:
return True
# avoid repeated build attempts
if self.cuda_build_failed:
return False
if not warp.is_cuda_available():
raise RuntimeError("Failed to build CUDA module because CUDA is not available")
module_name = "wp_" + self.name
module_hash = self.hash_module()
# use a unique module path using the module short hash
module_dir = os.path.join(warp.config.kernel_cache_dir, f"{module_name}_{module_hash.hex()[:7]}")
with ScopedTimer(
f"Module {self.name} {module_hash.hex()[:7]} load on device '{device}'", active=not warp.config.quiet
):
# -----------------------------------------------------------
# determine output paths
if device.is_cpu:
output_name = "module_codegen.o"
elif device.is_cuda:
# determine whether to use PTX or CUBIN
if device.is_cubin_supported:
# get user preference specified either per module or globally
preferred_cuda_output = self.options.get("cuda_output") or warp.config.cuda_output
if preferred_cuda_output is not None:
use_ptx = preferred_cuda_output == "ptx"
else:
# determine automatically: older drivers may not be able to handle PTX generated using newer
# CUDA Toolkits, in which case we fall back on generating CUBIN modules
use_ptx = runtime.driver_version >= runtime.toolkit_version
else:
# CUBIN not an option, must use PTX (e.g. CUDA Toolkit too old)
use_ptx = True
if use_ptx:
output_arch = min(device.arch, warp.config.ptx_target_arch)
output_name = f"module_codegen.sm{output_arch}.ptx"
else:
output_arch = device.arch
output_name = f"module_codegen.sm{output_arch}.cubin"
# final object binary path
binary_path = os.path.join(module_dir, output_name)
# -----------------------------------------------------------
# check cache and build if necessary
build_dir = None
if not os.path.exists(binary_path) or not warp.config.cache_kernels:
builder = ModuleBuilder(self, self.options)
# create a temporary (process unique) dir for build outputs before moving to the binary dir
build_dir = os.path.join(
warp.config.kernel_cache_dir, f"{module_name}_{module_hash.hex()[:7]}_p{os.getpid()}"
)
# dir may exist from previous attempts / runs / archs
Path(build_dir).mkdir(parents=True, exist_ok=True)
# build CPU
if device.is_cpu:
# build
try:
cpp_path = os.path.join(build_dir, "module_codegen.cpp")
# write cpp sources
cpp_source = builder.codegen("cpu")
with open(cpp_path, "w") as cpp_file:
cpp_file.write(cpp_source)
output_path = os.path.join(build_dir, output_name)
# build object code
with ScopedTimer("Compile x86", active=warp.config.verbose):
warp.build.build_cpu(
output_path,
cpp_path,
mode=self.options["mode"],
fast_math=self.options["fast_math"],
verify_fp=warp.config.verify_fp,
)
except Exception as e:
self.cpu_build_failed = True
raise (e)
elif device.is_cuda:
# build
try:
cu_path = os.path.join(build_dir, "module_codegen.cu")
# write cuda sources
cu_source = builder.codegen("cuda")
with open(cu_path, "w") as cu_file:
cu_file.write(cu_source)
output_path = os.path.join(build_dir, output_name)
# generate PTX or CUBIN
with ScopedTimer("Compile CUDA", active=warp.config.verbose):
warp.build.build_cuda(
cu_path,
output_arch,
output_path,
config=self.options["mode"],
fast_math=self.options["fast_math"],
verify_fp=warp.config.verify_fp,
)
except Exception as e:
self.cuda_build_failed = True
raise (e)
# -----------------------------------------------------------
# update cache
try:
# Copy process-specific build directory to a process-independent location
os.rename(build_dir, module_dir)
except (OSError, FileExistsError):
# another process likely updated the module dir first
pass
if os.path.exists(module_dir) and not os.path.exists(binary_path):
# copy our output file to the destination module
# this is necessary in case different processes
# have different GPU architectures / devices
try:
os.rename(output_path, binary_path)
except (OSError, FileExistsError):
# another process likely updated the module dir first
pass
# -----------------------------------------------------------
# Load CPU or CUDA binary
if device.is_cpu:
runtime.llvm.load_obj(binary_path.encode("utf-8"), module_name.encode("utf-8"))
self.cpu_module = module_name
elif device.is_cuda:
cuda_module = warp.build.load_cuda(binary_path, device)
if cuda_module is not None:
self.cuda_modules[device.context] = cuda_module
else:
raise Exception(f"Failed to load CUDA module '{self.name}'")
if build_dir:
import shutil
# clean up build_dir used for this process regardless
shutil.rmtree(build_dir, ignore_errors=True)
return True
def unload(self):
if self.cpu_module:
runtime.llvm.unload_obj(self.cpu_module.encode("utf-8"))
self.cpu_module = None
# need to unload the CUDA module from all CUDA contexts where it is loaded
# note: we ensure that this doesn't change the current CUDA context
if self.cuda_modules:
saved_context = runtime.core.cuda_context_get_current()
for context, module in self.cuda_modules.items():
device = runtime.context_map[context]
if device.is_capturing:
raise RuntimeError(f"Failed to unload CUDA module '{self.name}' because graph capture is active")
runtime.core.cuda_unload_module(context, module)
runtime.core.cuda_context_set_current(saved_context)
self.cuda_modules = {}
# clear kernel hooks
self.kernel_hooks = {}
# clear content hash
self.content_hash = None
# lookup and cache kernel entry points based on name, called after compilation / module load
def get_kernel_hooks(self, kernel, device):
# get all hooks for this device
device_hooks = self.kernel_hooks.get(device.context)
if device_hooks is None:
self.kernel_hooks[device.context] = device_hooks = {}
# look up this kernel
hooks = device_hooks.get(kernel)
if hooks is not None:
return hooks
name = kernel.get_mangled_name()
if device.is_cpu:
func = ctypes.CFUNCTYPE(None)
forward = func(
runtime.llvm.lookup(self.cpu_module.encode("utf-8"), (name + "_cpu_forward").encode("utf-8"))
)
backward = func(
runtime.llvm.lookup(self.cpu_module.encode("utf-8"), (name + "_cpu_backward").encode("utf-8"))
)
else:
cu_module = self.cuda_modules[device.context]
forward = runtime.core.cuda_get_kernel(
device.context, cu_module, (name + "_cuda_kernel_forward").encode("utf-8")
)
backward = runtime.core.cuda_get_kernel(
device.context, cu_module, (name + "_cuda_kernel_backward").encode("utf-8")
)
hooks = KernelHooks(forward, backward)
device_hooks[kernel] = hooks
return hooks
# -------------------------------------------
# execution context
class CpuDefaultAllocator:
def __init__(self, device):
assert device.is_cpu
self.deleter = lambda ptr, size: self.free(ptr, size)
def alloc(self, size_in_bytes):
ptr = runtime.core.alloc_host(size_in_bytes)
if not ptr:
raise RuntimeError(f"Failed to allocate {size_in_bytes} bytes on device '{self.device}'")
return ptr
def free(self, ptr, size_in_bytes):
runtime.core.free_host(ptr)
class CpuPinnedAllocator:
def __init__(self, device):
assert device.is_cpu
self.deleter = lambda ptr, size: self.free(ptr, size)
def alloc(self, size_in_bytes):
ptr = runtime.core.alloc_pinned(size_in_bytes)
if not ptr:
raise RuntimeError(f"Failed to allocate {size_in_bytes} bytes on device '{self.device}'")
return ptr
def free(self, ptr, size_in_bytes):
runtime.core.free_pinned(ptr)
class CudaDefaultAllocator:
def __init__(self, device):
assert device.is_cuda
self.device = device
self.deleter = lambda ptr, size: self.free(ptr, size)
def alloc(self, size_in_bytes):
ptr = runtime.core.alloc_device_default(self.device.context, size_in_bytes)
# If the allocation fails, check if graph capture is active to raise an informative error.
# We delay the capture check to avoid overhead.
if not ptr:
reason = ""
if self.device.is_capturing:
if not self.device.is_mempool_supported:
reason = (
": "
f"Failed to allocate memory during graph capture because memory pools are not supported "
f"on device '{self.device}'. Try pre-allocating memory before capture begins."
)
elif not self.device.is_mempool_enabled:
reason = (
": "
f"Failed to allocate memory during graph capture because memory pools are not enabled "
f"on device '{self.device}'. Try calling wp.set_mempool_enabled('{self.device}', True) before capture begins."
)
raise RuntimeError(f"Failed to allocate {size_in_bytes} bytes on device '{self.device}'{reason}")
return ptr
def free(self, ptr, size_in_bytes):
runtime.core.free_device_default(self.device.context, ptr)
class CudaMempoolAllocator:
def __init__(self, device):
assert device.is_cuda
assert device.is_mempool_supported
self.device = device
self.deleter = lambda ptr, size: self.free(ptr, size)
def alloc(self, size_in_bytes):
ptr = runtime.core.alloc_device_async(self.device.context, size_in_bytes)
if not ptr:
raise RuntimeError(f"Failed to allocate {size_in_bytes} bytes on device '{self.device}'")
return ptr
def free(self, ptr, size_in_bytes):
runtime.core.free_device_async(self.device.context, ptr)
class ContextGuard:
def __init__(self, device):
self.device = device
def __enter__(self):
if self.device.is_cuda:
runtime.core.cuda_context_push_current(self.device.context)
elif is_cuda_driver_initialized():
self.saved_context = runtime.core.cuda_context_get_current()
def __exit__(self, exc_type, exc_value, traceback):
if self.device.is_cuda:
runtime.core.cuda_context_pop_current()
elif is_cuda_driver_initialized():
runtime.core.cuda_context_set_current(self.saved_context)
class Stream:
def __init__(self, device=None, **kwargs):
self.cuda_stream = None
self.owner = False
# event used internally for synchronization (cached to avoid creating temporary events)
self._cached_event = None
# we can't use get_device() if called during init, but we can use an explicit Device arg
if runtime is not None:
device = runtime.get_device(device)
elif not isinstance(device, Device):
raise RuntimeError(
"A device object is required when creating a stream before or during Warp initialization"
)
if not device.is_cuda:
raise RuntimeError(f"Device {device} is not a CUDA device")
self.device = device
# we pass cuda_stream through kwargs because cuda_stream=None is actually a valid value (CUDA default stream)
if "cuda_stream" in kwargs:
self.cuda_stream = kwargs["cuda_stream"]
device.runtime.core.cuda_stream_register(device.context, self.cuda_stream)
else:
self.cuda_stream = device.runtime.core.cuda_stream_create(device.context)
if not self.cuda_stream:
raise RuntimeError(f"Failed to create stream on device {device}")
self.owner = True
def __del__(self):
if not self.cuda_stream:
return
if self.owner:
runtime.core.cuda_stream_destroy(self.device.context, self.cuda_stream)
else:
runtime.core.cuda_stream_unregister(self.device.context, self.cuda_stream)
@property
def cached_event(self):
if self._cached_event is None:
self._cached_event = Event(self.device)
return self._cached_event
def record_event(self, event=None):
if event is None:
event = Event(self.device)
elif event.device != self.device:
raise RuntimeError(
f"Event from device {event.device} cannot be recorded on stream from device {self.device}"
)
runtime.core.cuda_event_record(event.cuda_event, self.cuda_stream)
return event
def wait_event(self, event):
runtime.core.cuda_stream_wait_event(self.cuda_stream, event.cuda_event)
def wait_stream(self, other_stream, event=None):
if event is None:
event = other_stream.cached_event
runtime.core.cuda_stream_wait_stream(self.cuda_stream, other_stream.cuda_stream, event.cuda_event)
# whether a graph capture is currently ongoing on this stream
@property
def is_capturing(self):
return bool(runtime.core.cuda_stream_is_capturing(self.cuda_stream))
class Event:
# event creation flags
class Flags:
DEFAULT = 0x0
BLOCKING_SYNC = 0x1
DISABLE_TIMING = 0x2
def __init__(self, device=None, cuda_event=None, enable_timing=False):
self.owner = False
device = get_device(device)
if not device.is_cuda:
raise RuntimeError(f"Device {device} is not a CUDA device")
self.device = device
if cuda_event is not None:
self.cuda_event = cuda_event
else:
flags = Event.Flags.DEFAULT
if not enable_timing:
flags |= Event.Flags.DISABLE_TIMING
self.cuda_event = runtime.core.cuda_event_create(device.context, flags)
if not self.cuda_event:
raise RuntimeError(f"Failed to create event on device {device}")
self.owner = True
def __del__(self):
if not self.owner:
return
runtime.core.cuda_event_destroy(self.cuda_event)
class Device:
"""A device to allocate Warp arrays and to launch kernels on.
Attributes:
ordinal: A Warp-specific integer label for the device. ``-1`` for CPU devices.
name: A string label for the device. By default, CPU devices will be named according to the processor name,
or ``"CPU"`` if the processor name cannot be determined.
arch: An integer representing the compute capability version number calculated as
``10 * major + minor``. ``0`` for CPU devices.
is_uva: A boolean indicating whether or not the device supports unified addressing.
``False`` for CPU devices.
is_cubin_supported: A boolean indicating whether or not Warp's version of NVRTC can directly
generate CUDA binary files (cubin) for this device's architecture. ``False`` for CPU devices.
is_mempool_supported: A boolean indicating whether or not the device supports using the
``cuMemAllocAsync`` and ``cuMemPool`` family of APIs for stream-ordered memory allocations. ``False`` for
CPU devices.
is_primary: A boolean indicating whether or not this device's CUDA context is also the
device's primary context.
uuid: A string representing the UUID of the CUDA device. The UUID is in the same format used by
``nvidia-smi -L``. ``None`` for CPU devices.
pci_bus_id: A string identifier for the CUDA device in the format ``[domain]:[bus]:[device]``, in which
``domain``, ``bus``, and ``device`` are all hexadecimal values. ``None`` for CPU devices.
"""
def __init__(self, runtime, alias, ordinal=-1, is_primary=False, context=None):
self.runtime = runtime
self.alias = alias
self.ordinal = ordinal
self.is_primary = is_primary
# context can be None to avoid acquiring primary contexts until the device is used
self._context = context
# if the device context is not primary, it cannot be None
if ordinal != -1 and not is_primary:
assert context is not None
# streams will be created when context is acquired
self._stream = None
self.null_stream = None
# set of streams where capture has started
self.captures = set()
self.context_guard = ContextGuard(self)
if self.ordinal == -1:
# CPU device
self.name = platform.processor() or "CPU"
self.arch = 0
self.is_uva = False
self.is_mempool_supported = False
self.is_mempool_enabled = False
self.is_cubin_supported = False
self.uuid = None
self.pci_bus_id = None
# TODO: add more device-specific dispatch functions
self.memset = runtime.core.memset_host
self.memtile = runtime.core.memtile_host
self.default_allocator = CpuDefaultAllocator(self)
self.pinned_allocator = CpuPinnedAllocator(self)
elif ordinal >= 0 and ordinal < runtime.core.cuda_device_get_count():
# CUDA device
self.name = runtime.core.cuda_device_get_name(ordinal).decode()
self.arch = runtime.core.cuda_device_get_arch(ordinal)
self.is_uva = runtime.core.cuda_device_is_uva(ordinal)
self.is_mempool_supported = runtime.core.cuda_device_is_mempool_supported(ordinal)
if warp.config.enable_mempools_at_init:
# enable if supported
self.is_mempool_enabled = self.is_mempool_supported
else:
# disable by default
self.is_mempool_enabled = False
uuid_buffer = (ctypes.c_char * 16)()
runtime.core.cuda_device_get_uuid(ordinal, uuid_buffer)
uuid_byte_str = bytes(uuid_buffer).hex()
self.uuid = f"GPU-{uuid_byte_str[0:8]}-{uuid_byte_str[8:12]}-{uuid_byte_str[12:16]}-{uuid_byte_str[16:20]}-{uuid_byte_str[20:]}"
pci_domain_id = runtime.core.cuda_device_get_pci_domain_id(ordinal)
pci_bus_id = runtime.core.cuda_device_get_pci_bus_id(ordinal)
pci_device_id = runtime.core.cuda_device_get_pci_device_id(ordinal)
# This is (mis)named to correspond to the naming of cudaDeviceGetPCIBusId
self.pci_bus_id = f"{pci_domain_id:08X}:{pci_bus_id:02X}:{pci_device_id:02X}"
self.default_allocator = CudaDefaultAllocator(self)
if self.is_mempool_supported:
self.mempool_allocator = CudaMempoolAllocator(self)
else:
self.mempool_allocator = None
# set current allocator
if self.is_mempool_enabled:
self.current_allocator = self.mempool_allocator
else:
self.current_allocator = self.default_allocator
# check whether our NVRTC can generate CUBINs for this architecture
self.is_cubin_supported = self.arch in runtime.nvrtc_supported_archs
# initialize streams unless context acquisition is postponed
if self._context is not None:
self.init_streams()
# TODO: add more device-specific dispatch functions
self.memset = lambda ptr, value, size: runtime.core.memset_device(self.context, ptr, value, size)
self.memtile = lambda ptr, src, srcsize, reps: runtime.core.memtile_device(
self.context, ptr, src, srcsize, reps
)
else:
raise RuntimeError(f"Invalid device ordinal ({ordinal})'")
def get_allocator(self, pinned=False):
if self.is_cuda:
return self.current_allocator
else:
if pinned:
return self.pinned_allocator
else:
return self.default_allocator
def init_streams(self):
# create a stream for asynchronous work
self.set_stream(Stream(self))
# CUDA default stream for some synchronous operations
self.null_stream = Stream(self, cuda_stream=None)
@property
def is_cpu(self):
"""A boolean indicating whether or not the device is a CPU device."""
return self.ordinal < 0
@property
def is_cuda(self):
"""A boolean indicating whether or not the device is a CUDA device."""
return self.ordinal >= 0
@property
def is_capturing(self):
if self.is_cuda and self.stream is not None:
# There is no CUDA API to check if graph capture was started on a device, so we
# can't tell if a capture was started by external code on a different stream.
# The best we can do is check whether a graph capture was started by Warp on this
# device and whether the current stream is capturing.
return self.captures or self.stream.is_capturing
else:
return False
@property
def context(self):
"""The context associated with the device."""
if self._context is not None:
return self._context
elif self.is_primary:
# acquire primary context on demand
prev_context = runtime.core.cuda_context_get_current()
self._context = self.runtime.core.cuda_device_get_primary_context(self.ordinal)
if self._context is None:
runtime.core.cuda_context_set_current(prev_context)
raise RuntimeError(f"Failed to acquire primary context for device {self}")
self.runtime.context_map[self._context] = self
# initialize streams
self.init_streams()
runtime.core.cuda_context_set_current(prev_context)
return self._context
@property
def has_context(self):
"""A boolean indicating whether or not the device has a CUDA context associated with it."""
return self._context is not None
@property
def stream(self):
"""The stream associated with a CUDA device.
Raises:
RuntimeError: The device is not a CUDA device.
"""
if self.context:
return self._stream
else:
raise RuntimeError(f"Device {self} is not a CUDA device")
@stream.setter
def stream(self, stream):
self.set_stream(stream)
def set_stream(self, stream, sync=True):
if self.is_cuda:
if stream.device != self:
raise RuntimeError(f"Stream from device {stream.device} cannot be used on device {self}")
self.runtime.core.cuda_context_set_stream(self.context, stream.cuda_stream, int(sync))
self._stream = stream
else:
raise RuntimeError(f"Device {self} is not a CUDA device")
@property
def has_stream(self):
"""A boolean indicating whether or not the device has a stream associated with it."""
return self._stream is not None
@property
def total_memory(self):
"""The total amount of device memory available in bytes.
This function is currently only implemented for CUDA devices. 0 will be returned if called on a CPU device.
"""
if self.is_cuda:
total_mem = ctypes.c_size_t()
self.runtime.core.cuda_device_get_memory_info(self.ordinal, None, ctypes.byref(total_mem))
return total_mem.value
else:
# TODO: cpu
return 0
@property
def free_memory(self):
"""The amount of memory on the device that is free according to the OS in bytes.
This function is currently only implemented for CUDA devices. 0 will be returned if called on a CPU device.
"""
if self.is_cuda:
free_mem = ctypes.c_size_t()
self.runtime.core.cuda_device_get_memory_info(self.ordinal, ctypes.byref(free_mem), None)
return free_mem.value
else:
# TODO: cpu
return 0
def __str__(self):
return self.alias
def __repr__(self):
return f"'{self.alias}'"
def __eq__(self, other):
if self is other:
return True
elif isinstance(other, Device):
return self.context == other.context
elif isinstance(other, str):
if other == "cuda":
return self == self.runtime.get_current_cuda_device()
else:
return other == self.alias
else:
return False
def make_current(self):
if self.context is not None:
self.runtime.core.cuda_context_set_current(self.context)
def can_access(self, other):
# TODO: this function should be redesigned in terms of (device, resource).
# - a device can access any resource on the same device
# - a CUDA device can access pinned memory on the host
# - a CUDA device can access regular allocations on a peer device if peer access is enabled
# - a CUDA device can access mempool allocations on a peer device if mempool access is enabled
other = self.runtime.get_device(other)
if self.context == other.context:
return True
else:
return False
""" Meta-type for arguments that can be resolved to a concrete Device.
"""
Devicelike = Union[Device, str, None]
class Graph:
def __init__(self, device: Device, exec: ctypes.c_void_p):
self.device = device
self.exec = exec
def __del__(self):
if not self.exec:
return
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
runtime.core.cuda_graph_destroy(self.device.context, self.exec)
class Runtime:
def __init__(self):
if sys.version_info < (3, 7):
raise RuntimeError("Warp requires Python 3.7 as a minimum")
if sys.version_info < (3, 9):
warp.utils.warn(f"Python 3.9 or newer is recommended for running Warp, detected {sys.version_info}")
bin_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "bin")
if os.name == "nt":
if sys.version_info >= (3, 8):
# Python >= 3.8 this method to add dll search paths
os.add_dll_directory(bin_path)
else:
# Python < 3.8 we add dll directory to path
os.environ["PATH"] = bin_path + os.pathsep + os.environ["PATH"]
warp_lib = os.path.join(bin_path, "warp.dll")
llvm_lib = os.path.join(bin_path, "warp-clang.dll")
elif sys.platform == "darwin":
warp_lib = os.path.join(bin_path, "libwarp.dylib")
llvm_lib = os.path.join(bin_path, "libwarp-clang.dylib")
else:
warp_lib = os.path.join(bin_path, "warp.so")
llvm_lib = os.path.join(bin_path, "warp-clang.so")
self.core = self.load_dll(warp_lib)
if os.path.exists(llvm_lib):
self.llvm = self.load_dll(llvm_lib)
# setup c-types for warp-clang.dll
self.llvm.lookup.restype = ctypes.c_uint64
else:
self.llvm = None
# setup c-types for warp.dll
try:
self.core.get_error_string.argtypes = []
self.core.get_error_string.restype = ctypes.c_char_p
self.core.set_error_output_enabled.argtypes = [ctypes.c_int]
self.core.set_error_output_enabled.restype = None
self.core.is_error_output_enabled.argtypes = []
self.core.is_error_output_enabled.restype = ctypes.c_int
self.core.alloc_host.argtypes = [ctypes.c_size_t]
self.core.alloc_host.restype = ctypes.c_void_p
self.core.alloc_pinned.argtypes = [ctypes.c_size_t]
self.core.alloc_pinned.restype = ctypes.c_void_p
self.core.alloc_device.argtypes = [ctypes.c_void_p, ctypes.c_size_t]
self.core.alloc_device.restype = ctypes.c_void_p
self.core.alloc_device_default.argtypes = [ctypes.c_void_p, ctypes.c_size_t]
self.core.alloc_device_default.restype = ctypes.c_void_p
self.core.alloc_device_async.argtypes = [ctypes.c_void_p, ctypes.c_size_t]
self.core.alloc_device_async.restype = ctypes.c_void_p
self.core.float_to_half_bits.argtypes = [ctypes.c_float]
self.core.float_to_half_bits.restype = ctypes.c_uint16
self.core.half_bits_to_float.argtypes = [ctypes.c_uint16]
self.core.half_bits_to_float.restype = ctypes.c_float
self.core.free_host.argtypes = [ctypes.c_void_p]
self.core.free_host.restype = None
self.core.free_pinned.argtypes = [ctypes.c_void_p]
self.core.free_pinned.restype = None
self.core.free_device.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.free_device.restype = None
self.core.free_device_default.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.free_device_default.restype = None
self.core.free_device_async.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.free_device_async.restype = None
self.core.memset_host.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t]
self.core.memset_host.restype = None
self.core.memset_device.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t]
self.core.memset_device.restype = None
self.core.memtile_host.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t]
self.core.memtile_host.restype = None
self.core.memtile_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_size_t,
]
self.core.memtile_device.restype = None
self.core.memcpy_h2h.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t]
self.core.memcpy_h2h.restype = ctypes.c_bool
self.core.memcpy_h2d.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p,
]
self.core.memcpy_h2d.restype = ctypes.c_bool
self.core.memcpy_d2h.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p,
]
self.core.memcpy_d2h.restype = ctypes.c_bool
self.core.memcpy_d2d.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p,
]
self.core.memcpy_d2d.restype = ctypes.c_bool
self.core.memcpy_p2p.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_void_p,
]
self.core.memcpy_p2p.restype = ctypes.c_bool
self.core.array_copy_host.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_copy_host.restype = ctypes.c_bool
self.core.array_copy_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_copy_device.restype = ctypes.c_bool
self.core.array_fill_host.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
self.core.array_fill_host.restype = None
self.core.array_fill_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_int,
]
self.core.array_fill_device.restype = None
self.core.array_sum_double_host.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_sum_float_host.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_sum_double_device.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_sum_float_device.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_inner_double_host.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_inner_float_host.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_inner_double_device.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_inner_float_device.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.array_scan_int_host.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_int, ctypes.c_bool]
self.core.array_scan_float_host.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_int, ctypes.c_bool]
self.core.array_scan_int_device.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_int, ctypes.c_bool]
self.core.array_scan_float_device.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_int, ctypes.c_bool]
self.core.radix_sort_pairs_int_host.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_int]
self.core.radix_sort_pairs_int_device.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_int]
self.core.runlength_encode_int_host.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
]
self.core.runlength_encode_int_device.argtypes = [
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_int,
]
self.core.bvh_create_host.restype = ctypes.c_uint64
self.core.bvh_create_host.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
self.core.bvh_create_device.restype = ctypes.c_uint64
self.core.bvh_create_device.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
self.core.bvh_destroy_host.argtypes = [ctypes.c_uint64]
self.core.bvh_destroy_device.argtypes = [ctypes.c_uint64]
self.core.bvh_refit_host.argtypes = [ctypes.c_uint64]
self.core.bvh_refit_device.argtypes = [ctypes.c_uint64]
self.core.mesh_create_host.restype = ctypes.c_uint64
self.core.mesh_create_host.argtypes = [
warp.types.array_t,
warp.types.array_t,
warp.types.array_t,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.mesh_create_device.restype = ctypes.c_uint64
self.core.mesh_create_device.argtypes = [
ctypes.c_void_p,
warp.types.array_t,
warp.types.array_t,
warp.types.array_t,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
]
self.core.mesh_destroy_host.argtypes = [ctypes.c_uint64]
self.core.mesh_destroy_device.argtypes = [ctypes.c_uint64]
self.core.mesh_refit_host.argtypes = [ctypes.c_uint64]
self.core.mesh_refit_device.argtypes = [ctypes.c_uint64]
self.core.hash_grid_create_host.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int]
self.core.hash_grid_create_host.restype = ctypes.c_uint64
self.core.hash_grid_destroy_host.argtypes = [ctypes.c_uint64]
self.core.hash_grid_update_host.argtypes = [ctypes.c_uint64, ctypes.c_float, ctypes.c_void_p]
self.core.hash_grid_reserve_host.argtypes = [ctypes.c_uint64, ctypes.c_int]
self.core.hash_grid_create_device.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int]
self.core.hash_grid_create_device.restype = ctypes.c_uint64
self.core.hash_grid_destroy_device.argtypes = [ctypes.c_uint64]
self.core.hash_grid_update_device.argtypes = [ctypes.c_uint64, ctypes.c_float, ctypes.c_void_p]
self.core.hash_grid_reserve_device.argtypes = [ctypes.c_uint64, ctypes.c_int]
self.core.cutlass_gemm.argtypes = [
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_float,
ctypes.c_float,
ctypes.c_bool,
ctypes.c_bool,
ctypes.c_bool,
ctypes.c_int,
]
self.core.cutlass_gemm.restype = ctypes.c_bool
self.core.volume_create_host.argtypes = [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_bool, ctypes.c_bool]
self.core.volume_create_host.restype = ctypes.c_uint64
self.core.volume_get_tiles_host.argtypes = [
ctypes.c_uint64,
ctypes.c_void_p,
]
self.core.volume_get_voxels_host.argtypes = [
ctypes.c_uint64,
ctypes.c_void_p,
]
self.core.volume_destroy_host.argtypes = [ctypes.c_uint64]
self.core.volume_create_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint64,
ctypes.c_bool,
ctypes.c_bool,
]
self.core.volume_create_device.restype = ctypes.c_uint64
self.core.volume_get_tiles_device.argtypes = [
ctypes.c_uint64,
ctypes.c_void_p,
]
self.core.volume_get_voxels_device.argtypes = [
ctypes.c_uint64,
ctypes.c_void_p,
]
self.core.volume_destroy_device.argtypes = [ctypes.c_uint64]
self.core.volume_f_from_tiles_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_bool,
]
self.core.volume_f_from_tiles_device.restype = ctypes.c_uint64
self.core.volume_v_from_tiles_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_bool,
]
self.core.volume_v_from_tiles_device.restype = ctypes.c_uint64
self.core.volume_i_from_tiles_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_float,
ctypes.c_int,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_bool,
]
self.core.volume_i_from_tiles_device.restype = ctypes.c_uint64
self.core.volume_index_from_tiles_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_bool,
]
self.core.volume_index_from_tiles_device.restype = ctypes.c_uint64
self.core.volume_from_active_voxels_device.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_float,
ctypes.c_bool,
]
self.core.volume_from_active_voxels_device.restype = ctypes.c_uint64
self.core.volume_get_buffer_info.argtypes = [
ctypes.c_uint64,
ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.c_uint64),
]
self.core.volume_get_voxel_size.argtypes = [
ctypes.c_uint64,
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_float),
ctypes.POINTER(ctypes.c_float),
]
self.core.volume_get_tile_and_voxel_count.argtypes = [
ctypes.c_uint64,
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_uint64),
]
self.core.volume_get_grid_info.argtypes = [
ctypes.c_uint64,
ctypes.POINTER(ctypes.c_uint64),
ctypes.POINTER(ctypes.c_uint32),
ctypes.POINTER(ctypes.c_uint32),
ctypes.c_float * 3,
ctypes.c_float * 9,
ctypes.c_char * 16,
]
self.core.volume_get_grid_info.restype = ctypes.c_char_p
self.core.volume_get_blind_data_count.argtypes = [
ctypes.c_uint64,
]
self.core.volume_get_blind_data_count.restype = ctypes.c_uint64
self.core.volume_get_blind_data_info.argtypes = [
ctypes.c_uint64,
ctypes.c_uint32,
ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.c_uint64),
ctypes.POINTER(ctypes.c_uint32),
ctypes.c_char * 16,
]
self.core.volume_get_blind_data_info.restype = ctypes.c_char_p
bsr_matrix_from_triplets_argtypes = [
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
]
self.core.bsr_matrix_from_triplets_float_host.argtypes = bsr_matrix_from_triplets_argtypes
self.core.bsr_matrix_from_triplets_double_host.argtypes = bsr_matrix_from_triplets_argtypes
self.core.bsr_matrix_from_triplets_float_device.argtypes = bsr_matrix_from_triplets_argtypes
self.core.bsr_matrix_from_triplets_double_device.argtypes = bsr_matrix_from_triplets_argtypes
self.core.bsr_matrix_from_triplets_float_host.restype = ctypes.c_int
self.core.bsr_matrix_from_triplets_double_host.restype = ctypes.c_int
self.core.bsr_matrix_from_triplets_float_device.restype = ctypes.c_int
self.core.bsr_matrix_from_triplets_double_device.restype = ctypes.c_int
bsr_transpose_argtypes = [
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_uint64,
]
self.core.bsr_transpose_float_host.argtypes = bsr_transpose_argtypes
self.core.bsr_transpose_double_host.argtypes = bsr_transpose_argtypes
self.core.bsr_transpose_float_device.argtypes = bsr_transpose_argtypes
self.core.bsr_transpose_double_device.argtypes = bsr_transpose_argtypes
self.core.is_cuda_enabled.argtypes = None
self.core.is_cuda_enabled.restype = ctypes.c_int
self.core.is_cuda_compatibility_enabled.argtypes = None
self.core.is_cuda_compatibility_enabled.restype = ctypes.c_int
self.core.is_cutlass_enabled.argtypes = None
self.core.is_cutlass_enabled.restype = ctypes.c_int
self.core.cuda_driver_version.argtypes = None
self.core.cuda_driver_version.restype = ctypes.c_int
self.core.cuda_toolkit_version.argtypes = None
self.core.cuda_toolkit_version.restype = ctypes.c_int
self.core.cuda_driver_is_initialized.argtypes = None
self.core.cuda_driver_is_initialized.restype = ctypes.c_bool
self.core.nvrtc_supported_arch_count.argtypes = None
self.core.nvrtc_supported_arch_count.restype = ctypes.c_int
self.core.nvrtc_supported_archs.argtypes = [ctypes.POINTER(ctypes.c_int)]
self.core.nvrtc_supported_archs.restype = None
self.core.cuda_device_get_count.argtypes = None
self.core.cuda_device_get_count.restype = ctypes.c_int
self.core.cuda_device_get_primary_context.argtypes = [ctypes.c_int]
self.core.cuda_device_get_primary_context.restype = ctypes.c_void_p
self.core.cuda_device_get_name.argtypes = [ctypes.c_int]
self.core.cuda_device_get_name.restype = ctypes.c_char_p
self.core.cuda_device_get_arch.argtypes = [ctypes.c_int]
self.core.cuda_device_get_arch.restype = ctypes.c_int
self.core.cuda_device_is_uva.argtypes = [ctypes.c_int]
self.core.cuda_device_is_uva.restype = ctypes.c_int
self.core.cuda_device_is_mempool_supported.argtypes = [ctypes.c_int]
self.core.cuda_device_is_mempool_supported.restype = ctypes.c_int
self.core.cuda_device_set_mempool_release_threshold.argtypes = [ctypes.c_int, ctypes.c_uint64]
self.core.cuda_device_set_mempool_release_threshold.restype = ctypes.c_int
self.core.cuda_device_get_mempool_release_threshold.argtypes = [ctypes.c_int]
self.core.cuda_device_get_mempool_release_threshold.restype = ctypes.c_uint64
self.core.cuda_device_get_memory_info.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_device_get_memory_info.restype = None
self.core.cuda_device_get_uuid.argtypes = [ctypes.c_int, ctypes.c_char * 16]
self.core.cuda_device_get_uuid.restype = None
self.core.cuda_device_get_pci_domain_id.argtypes = [ctypes.c_int]
self.core.cuda_device_get_pci_domain_id.restype = ctypes.c_int
self.core.cuda_device_get_pci_bus_id.argtypes = [ctypes.c_int]
self.core.cuda_device_get_pci_bus_id.restype = ctypes.c_int
self.core.cuda_device_get_pci_device_id.argtypes = [ctypes.c_int]
self.core.cuda_device_get_pci_device_id.restype = ctypes.c_int
self.core.cuda_context_get_current.argtypes = None
self.core.cuda_context_get_current.restype = ctypes.c_void_p
self.core.cuda_context_set_current.argtypes = [ctypes.c_void_p]
self.core.cuda_context_set_current.restype = None
self.core.cuda_context_push_current.argtypes = [ctypes.c_void_p]
self.core.cuda_context_push_current.restype = None
self.core.cuda_context_pop_current.argtypes = None
self.core.cuda_context_pop_current.restype = None
self.core.cuda_context_create.argtypes = [ctypes.c_int]
self.core.cuda_context_create.restype = ctypes.c_void_p
self.core.cuda_context_destroy.argtypes = [ctypes.c_void_p]
self.core.cuda_context_destroy.restype = None
self.core.cuda_context_synchronize.argtypes = [ctypes.c_void_p]
self.core.cuda_context_synchronize.restype = None
self.core.cuda_context_check.argtypes = [ctypes.c_void_p]
self.core.cuda_context_check.restype = ctypes.c_uint64
self.core.cuda_context_get_device_ordinal.argtypes = [ctypes.c_void_p]
self.core.cuda_context_get_device_ordinal.restype = ctypes.c_int
self.core.cuda_context_is_primary.argtypes = [ctypes.c_void_p]
self.core.cuda_context_is_primary.restype = ctypes.c_int
self.core.cuda_context_get_stream.argtypes = [ctypes.c_void_p]
self.core.cuda_context_get_stream.restype = ctypes.c_void_p
self.core.cuda_context_set_stream.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
self.core.cuda_context_set_stream.restype = None
# peer access
self.core.cuda_is_peer_access_supported.argtypes = [ctypes.c_int, ctypes.c_int]
self.core.cuda_is_peer_access_supported.restype = ctypes.c_int
self.core.cuda_is_peer_access_enabled.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_is_peer_access_enabled.restype = ctypes.c_int
self.core.cuda_set_peer_access_enabled.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
self.core.cuda_set_peer_access_enabled.restype = ctypes.c_int
self.core.cuda_is_mempool_access_enabled.argtypes = [ctypes.c_int, ctypes.c_int]
self.core.cuda_is_mempool_access_enabled.restype = ctypes.c_int
self.core.cuda_set_mempool_access_enabled.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int]
self.core.cuda_set_mempool_access_enabled.restype = ctypes.c_int
self.core.cuda_stream_create.argtypes = [ctypes.c_void_p]
self.core.cuda_stream_create.restype = ctypes.c_void_p
self.core.cuda_stream_destroy.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_stream_destroy.restype = None
self.core.cuda_stream_register.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_stream_register.restype = None
self.core.cuda_stream_unregister.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_stream_unregister.restype = None
self.core.cuda_stream_synchronize.argtypes = [ctypes.c_void_p]
self.core.cuda_stream_synchronize.restype = None
self.core.cuda_stream_wait_event.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_stream_wait_event.restype = None
self.core.cuda_stream_wait_stream.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_stream_wait_stream.restype = None
self.core.cuda_stream_is_capturing.argtypes = [ctypes.c_void_p]
self.core.cuda_stream_is_capturing.restype = ctypes.c_int
self.core.cuda_event_create.argtypes = [ctypes.c_void_p, ctypes.c_uint]
self.core.cuda_event_create.restype = ctypes.c_void_p
self.core.cuda_event_destroy.argtypes = [ctypes.c_void_p]
self.core.cuda_event_destroy.restype = None
self.core.cuda_event_record.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_event_record.restype = None
self.core.cuda_event_synchronize.argtypes = [ctypes.c_void_p]
self.core.cuda_event_synchronize.restype = None
self.core.cuda_event_elapsed_time.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_event_elapsed_time.restype = ctypes.c_float
self.core.cuda_graph_begin_capture.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int]
self.core.cuda_graph_begin_capture.restype = ctypes.c_bool
self.core.cuda_graph_end_capture.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.POINTER(ctypes.c_void_p),
]
self.core.cuda_graph_end_capture.restype = ctypes.c_bool
self.core.cuda_graph_launch.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_graph_launch.restype = ctypes.c_bool
self.core.cuda_graph_destroy.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_graph_destroy.restype = ctypes.c_bool
self.core.cuda_compile_program.argtypes = [
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_bool,
ctypes.c_bool,
ctypes.c_bool,
ctypes.c_bool,
ctypes.c_char_p,
]
self.core.cuda_compile_program.restype = ctypes.c_size_t
self.core.cuda_load_module.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
self.core.cuda_load_module.restype = ctypes.c_void_p
self.core.cuda_unload_module.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_unload_module.restype = None
self.core.cuda_get_kernel.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p]
self.core.cuda_get_kernel.restype = ctypes.c_void_p
self.core.cuda_launch_kernel.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_int,
ctypes.POINTER(ctypes.c_void_p),
ctypes.c_void_p,
]
self.core.cuda_launch_kernel.restype = ctypes.c_size_t
self.core.cuda_graphics_map.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_graphics_map.restype = None
self.core.cuda_graphics_unmap.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_graphics_unmap.restype = None
self.core.cuda_graphics_device_ptr_and_size.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.POINTER(ctypes.c_uint64),
ctypes.POINTER(ctypes.c_size_t),
]
self.core.cuda_graphics_device_ptr_and_size.restype = None
self.core.cuda_graphics_register_gl_buffer.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint]
self.core.cuda_graphics_register_gl_buffer.restype = ctypes.c_void_p
self.core.cuda_graphics_unregister_resource.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
self.core.cuda_graphics_unregister_resource.restype = None
self.core.cuda_timing_begin.argtypes = [ctypes.c_int]
self.core.cuda_timing_begin.restype = None
self.core.cuda_timing_get_result_count.argtypes = []
self.core.cuda_timing_get_result_count.restype = int
self.core.cuda_timing_end.argtypes = []
self.core.cuda_timing_end.restype = None
self.core.init.restype = ctypes.c_int
except AttributeError as e:
raise RuntimeError(f"Setting C-types for {warp_lib} failed. It may need rebuilding.") from e
error = self.core.init()
if error != 0:
raise Exception("Warp initialization failed")
self.device_map = {} # device lookup by alias
self.context_map = {} # device lookup by context
# register CPU device
cpu_name = platform.processor()
if not cpu_name:
cpu_name = "CPU"
self.cpu_device = Device(self, "cpu")
self.device_map["cpu"] = self.cpu_device
self.context_map[None] = self.cpu_device
cuda_device_count = self.core.cuda_device_get_count()
if cuda_device_count > 0:
# get CUDA Toolkit and driver versions
self.toolkit_version = self.core.cuda_toolkit_version()
self.driver_version = self.core.cuda_driver_version()
# get all architectures supported by NVRTC
num_archs = self.core.nvrtc_supported_arch_count()
if num_archs > 0:
archs = (ctypes.c_int * num_archs)()
self.core.nvrtc_supported_archs(archs)
self.nvrtc_supported_archs = list(archs)
else:
self.nvrtc_supported_archs = []
# this is so we can give non-primary contexts a reasonable alias
# associated with the physical device (e.g., "cuda:0.0", "cuda:0.1")
self.cuda_custom_context_count = [0] * cuda_device_count
# register primary CUDA devices
self.cuda_devices = []
self.cuda_primary_devices = []
for i in range(cuda_device_count):
alias = f"cuda:{i}"
device = Device(self, alias, ordinal=i, is_primary=True)
self.cuda_devices.append(device)
self.cuda_primary_devices.append(device)
self.device_map[alias] = device
# set default device
if cuda_device_count > 0:
# stick with the current cuda context, if one is bound
initial_context = self.core.cuda_context_get_current()
if initial_context is not None:
self.set_default_device("cuda")
# if this is a non-primary context that was just registered, update the device count
cuda_device_count = len(self.cuda_devices)
else:
self.set_default_device("cuda:0")
else:
# CUDA not available
self.set_default_device("cpu")
# initialize kernel cache
warp.build.init_kernel_cache(warp.config.kernel_cache_dir)
devices_without_uva = []
devices_without_mempool = []
for cuda_device in self.cuda_devices:
if cuda_device.is_primary:
if not cuda_device.is_uva:
devices_without_uva.append(cuda_device)
if not cuda_device.is_mempool_supported:
devices_without_mempool.append(cuda_device)
# print device and version information
if not warp.config.quiet:
greeting = []
greeting.append(f"Warp {warp.config.version} initialized:")
if cuda_device_count > 0:
toolkit_version = (self.toolkit_version // 1000, (self.toolkit_version % 1000) // 10)
driver_version = (self.driver_version // 1000, (self.driver_version % 1000) // 10)
greeting.append(
f" CUDA Toolkit {toolkit_version[0]}.{toolkit_version[1]}, Driver {driver_version[0]}.{driver_version[1]}"
)
else:
if self.core.is_cuda_enabled():
# Warp was compiled with CUDA support, but no devices are available
greeting.append(" CUDA devices not available")
else:
# Warp was compiled without CUDA support
greeting.append(" CUDA support not enabled in this build")
greeting.append(" Devices:")
alias_str = f'"{self.cpu_device.alias}"'
name_str = f'"{self.cpu_device.name}"'
greeting.append(f" {alias_str:10s} : {name_str}")
for cuda_device in self.cuda_devices:
alias_str = f'"{cuda_device.alias}"'
if cuda_device.is_primary:
name_str = f'"{cuda_device.name}"'
arch_str = f"sm_{cuda_device.arch}"
mem_str = f"{cuda_device.total_memory / 1024 / 1024 / 1024:.0f} GiB"
if cuda_device.is_mempool_supported:
if cuda_device.is_mempool_enabled:
mempool_str = "mempool enabled"
else:
mempool_str = "mempool supported"
else:
mempool_str = "mempool not supported"
greeting.append(f" {alias_str:10s} : {name_str} ({mem_str}, {arch_str}, {mempool_str})")
else:
primary_alias_str = f'"{self.cuda_primary_devices[cuda_device.ordinal].alias}"'
greeting.append(f" {alias_str:10s} : Non-primary context on device {primary_alias_str}")
if cuda_device_count > 1:
# check peer access support
access_matrix = []
all_accessible = True
none_accessible = True
for i in range(cuda_device_count):
target_device = self.cuda_devices[i]
access_vector = []
for j in range(cuda_device_count):
if i == j:
access_vector.append(1)
else:
peer_device = self.cuda_devices[j]
can_access = self.core.cuda_is_peer_access_supported(
target_device.ordinal, peer_device.ordinal
)
access_vector.append(can_access)
all_accessible = all_accessible and can_access
none_accessible = none_accessible and not can_access
access_matrix.append(access_vector)
greeting.append(" CUDA peer access:")
if all_accessible:
greeting.append(" Supported fully (all-directional)")
elif none_accessible:
greeting.append(" Not supported")
else:
greeting.append(" Supported partially (see access matrix)")
# print access matrix
for i in range(cuda_device_count):
alias_str = f'"{self.cuda_devices[i].alias}"'
greeting.append(f" {alias_str:10s} : {access_matrix[i]}")
greeting.append(" Kernel cache:")
greeting.append(f" {warp.config.kernel_cache_dir}")
print("\n".join(greeting))
if cuda_device_count > 0:
# warn about possible misconfiguration of the system
if devices_without_uva:
# This should not happen on any system officially supported by Warp. UVA is not available
# on 32-bit Windows, which we don't support. Nonetheless, we should check and report a
# warning out of abundance of caution. It may help with debugging a broken VM setup etc.
warp.utils.warn(
f"Support for Unified Virtual Addressing (UVA) was not detected on devices {devices_without_uva}."
)
if devices_without_mempool:
warp.utils.warn(
f"Support for CUDA memory pools was not detected on devices {devices_without_mempool}. "
"This prevents memory allocations in CUDA graphs and may result in poor performance. "
"Is the UVM driver enabled?"
)
# CUDA compatibility check. This should only affect developer builds done with the
# --quick flag. The consequences of running with an older driver can be obscure and severe,
# so make sure we print a very visible warning.
if self.driver_version < self.toolkit_version and not self.core.is_cuda_compatibility_enabled():
print(
"******************************************************************\n"
"* WARNING: *\n"
"* Warp was compiled without CUDA compatibility support *\n"
"* (quick build). The CUDA Toolkit version used to build *\n"
"* Warp is not fully supported by the current driver. *\n"
"* Some CUDA functionality may not work correctly! *\n"
"* Update the driver or rebuild Warp without the --quick flag. *\n"
"******************************************************************\n"
)
# ensure initialization did not change the initial context (e.g. querying available memory)
self.core.cuda_context_set_current(initial_context)
# global tape
self.tape = None
def get_error_string(self):
return self.core.get_error_string().decode("utf-8")
def load_dll(self, dll_path):
try:
if sys.version_info >= (3, 8):
dll = ctypes.CDLL(dll_path, winmode=0)
else:
dll = ctypes.CDLL(dll_path)
except OSError as e:
if "GLIBCXX" in str(e):
raise RuntimeError(
f"Failed to load the shared library '{dll_path}'.\n"
"The execution environment's libstdc++ runtime is older than the version the Warp library was built for.\n"
"See https://nvidia.github.io/warp/installation.html#conda-environments for details."
) from e
else:
raise RuntimeError(f"Failed to load the shared library '{dll_path}'") from e
return dll
def get_device(self, ident: Devicelike = None) -> Device:
if isinstance(ident, Device):
return ident
elif ident is None:
return self.default_device
elif isinstance(ident, str):
if ident == "cuda":
return self.get_current_cuda_device()
else:
return self.device_map[ident]
else:
raise RuntimeError(f"Unable to resolve device from argument of type {type(ident)}")
def set_default_device(self, ident: Devicelike):
self.default_device = self.get_device(ident)
def get_current_cuda_device(self):
current_context = self.core.cuda_context_get_current()
if current_context is not None:
current_device = self.context_map.get(current_context)
if current_device is not None:
# this is a known device
return current_device
elif self.core.cuda_context_is_primary(current_context):
# this is a primary context that we haven't used yet
ordinal = self.core.cuda_context_get_device_ordinal(current_context)
device = self.cuda_devices[ordinal]
self.context_map[current_context] = device
return device
else:
# this is an unseen non-primary context, register it as a new device with a unique alias
ordinal = self.core.cuda_context_get_device_ordinal(current_context)
alias = f"cuda:{ordinal}.{self.cuda_custom_context_count[ordinal]}"
self.cuda_custom_context_count[ordinal] += 1
return self.map_cuda_device(alias, current_context)
elif self.default_device.is_cuda:
return self.default_device
elif self.cuda_devices:
return self.cuda_devices[0]
else:
# CUDA is not available
if not self.core.is_cuda_enabled():
raise RuntimeError('"cuda" device requested but this build of Warp does not support CUDA')
else:
raise RuntimeError('"cuda" device requested but CUDA is not supported by the hardware or driver')
def rename_device(self, device, alias):
del self.device_map[device.alias]
device.alias = alias
self.device_map[alias] = device
return device
def map_cuda_device(self, alias, context=None) -> Device:
if context is None:
context = self.core.cuda_context_get_current()
if context is None:
raise RuntimeError(f"Unable to determine CUDA context for device alias '{alias}'")
# check if this alias already exists
if alias in self.device_map:
device = self.device_map[alias]
if context == device.context:
# device already exists with the same alias, that's fine
return device
else:
raise RuntimeError(f"Device alias '{alias}' already exists")
# check if this context already has an associated Warp device
if context in self.context_map:
# rename the device
device = self.context_map[context]
return self.rename_device(device, alias)
else:
# it's an unmapped context
# get the device ordinal
ordinal = self.core.cuda_context_get_device_ordinal(context)
# check if this is a primary context (we could get here if it's a device that hasn't been used yet)
if self.core.cuda_context_is_primary(context):
# rename the device
device = self.cuda_primary_devices[ordinal]
return self.rename_device(device, alias)
else:
# create a new Warp device for this context
device = Device(self, alias, ordinal=ordinal, is_primary=False, context=context)
self.device_map[alias] = device
self.context_map[context] = device
self.cuda_devices.append(device)
return device
def unmap_cuda_device(self, alias):
device = self.device_map.get(alias)
# make sure the alias refers to a CUDA device
if device is None or not device.is_cuda:
raise RuntimeError(f"Invalid CUDA device alias '{alias}'")
del self.device_map[alias]
del self.context_map[device.context]
self.cuda_devices.remove(device)
def verify_cuda_device(self, device: Devicelike = None):
if warp.config.verify_cuda:
device = runtime.get_device(device)
if not device.is_cuda:
return
err = self.core.cuda_context_check(device.context)
if err != 0:
raise RuntimeError(f"CUDA error detected: {err}")
# global entry points
def is_cpu_available():
init()
return runtime.llvm
def is_cuda_available():
return get_cuda_device_count() > 0
def is_device_available(device):
return device in get_devices()
def is_cuda_driver_initialized() -> bool:
"""Returns ``True`` if the CUDA driver is initialized.
This is a stricter test than ``is_cuda_available()`` since a CUDA driver
call to ``cuCtxGetCurrent`` is made, and the result is compared to
`CUDA_SUCCESS`. Note that `CUDA_SUCCESS` is returned by ``cuCtxGetCurrent``
even if there is no context bound to the calling CPU thread.
This can be helpful in cases in which ``cuInit()`` was called before a fork.
"""
init()
return runtime.core.cuda_driver_is_initialized()
def get_devices() -> List[Device]:
"""Returns a list of devices supported in this environment."""
init()
devices = []
if is_cpu_available():
devices.append(runtime.cpu_device)
for cuda_device in runtime.cuda_devices:
devices.append(cuda_device)
return devices
def get_cuda_device_count() -> int:
"""Returns the number of CUDA devices supported in this environment."""
init()
return len(runtime.cuda_devices)
def get_cuda_device(ordinal: Union[int, None] = None) -> Device:
"""Returns the CUDA device with the given ordinal or the current CUDA device if ordinal is None."""
init()
if ordinal is None:
return runtime.get_current_cuda_device()
else:
return runtime.cuda_devices[ordinal]
def get_cuda_devices() -> List[Device]:
"""Returns a list of CUDA devices supported in this environment."""
init()
return runtime.cuda_devices
def get_preferred_device() -> Device:
"""Returns the preferred compute device, CUDA if available and CPU otherwise."""
init()
if is_cuda_available():
return runtime.cuda_devices[0]
elif is_cpu_available():
return runtime.cpu_device
else:
return None
def get_device(ident: Devicelike = None) -> Device:
"""Returns the device identified by the argument."""
init()
return runtime.get_device(ident)
def set_device(ident: Devicelike):
"""Sets the target device identified by the argument."""
init()
device = runtime.get_device(ident)
runtime.set_default_device(device)
device.make_current()
def map_cuda_device(alias: str, context: ctypes.c_void_p = None) -> Device:
"""Assign a device alias to a CUDA context.
This function can be used to create a wp.Device for an external CUDA context.
If a wp.Device already exists for the given context, it's alias will change to the given value.
Args:
alias: A unique string to identify the device.
context: A CUDA context pointer (CUcontext). If None, the currently bound CUDA context will be used.
Returns:
The associated wp.Device.
"""
init()
return runtime.map_cuda_device(alias, context)
def unmap_cuda_device(alias: str):
"""Remove a CUDA device with the given alias."""
init()
runtime.unmap_cuda_device(alias)
def is_mempool_supported(device: Devicelike):
"""Check if CUDA memory pool allocators are available on the device."""
init()
device = runtime.get_device(device)
return device.is_mempool_supported
def is_mempool_enabled(device: Devicelike):
"""Check if CUDA memory pool allocators are enabled on the device."""
init()
device = runtime.get_device(device)
return device.is_mempool_enabled
def set_mempool_enabled(device: Devicelike, enable: bool):
"""Enable or disable CUDA memory pool allocators on the device.
Pooled allocators are typically faster and allow allocating memory during graph capture.
They should generally be enabled, but there is a rare caveat. Copying data between different GPUs
may fail during graph capture if the memory was allocated using pooled allocators and memory pool
access is not enabled between the two GPUs. This is an internal CUDA limitation that is not related
to Warp. The preferred solution is to enable memory pool access using `warp.set_mempool_access_enabled()`.
If peer access is not supported, then the default CUDA allocators must be used to pre-allocate the memory
prior to graph capture.
"""
init()
device = runtime.get_device(device)
if device.is_cuda:
if enable:
if not device.is_mempool_supported:
raise RuntimeError(f"Device {device} does not support memory pools")
device.current_allocator = device.mempool_allocator
device.is_mempool_enabled = True
else:
device.current_allocator = device.default_allocator
device.is_mempool_enabled = False
else:
if enable:
raise ValueError("Memory pools are only supported on CUDA devices")
def set_mempool_release_threshold(device: Devicelike, threshold: Union[int, float]):
"""Set the CUDA memory pool release threshold on the device.
This is the amount of reserved memory to hold onto before trying to release memory back to the OS.
When more than this amount of bytes is held by the memory pool, the allocator will try to release
memory back to the OS on the next call to stream, event, or device synchronize.
Values between 0 and 1 are interpreted as fractions of available memory. For example, 0.5 means
half of the device's physical memory. Greater values are interpreted as an absolute number of bytes.
For example, 1024**3 means one GiB of memory.
"""
init()
device = runtime.get_device(device)
if not device.is_cuda:
raise ValueError("Memory pools are only supported on CUDA devices")
if not device.is_mempool_supported:
raise RuntimeError(f"Device {device} does not support memory pools")
if threshold < 0:
threshold = 0
elif threshold > 0 and threshold <= 1:
threshold = int(threshold * device.total_memory)
if not runtime.core.cuda_device_set_mempool_release_threshold(device.ordinal, threshold):
raise RuntimeError(f"Failed to set memory pool release threshold for device {device}")
def get_mempool_release_threshold(device: Devicelike):
"""Get the CUDA memory pool release threshold on the device."""
init()
device = runtime.get_device(device)
if not device.is_cuda:
raise ValueError("Memory pools are only supported on CUDA devices")
if not device.is_mempool_supported:
raise RuntimeError(f"Device {device} does not support memory pools")
return runtime.core.cuda_device_get_mempool_release_threshold(device.ordinal)
def is_peer_access_supported(target_device: Devicelike, peer_device: Devicelike):
"""Check if `peer_device` can directly access the memory of `target_device` on this system.
This applies to memory allocated using default CUDA allocators. For memory allocated using
CUDA pooled allocators, use `is_mempool_access_supported()`.
Returns:
A Boolean value indicating if this peer access is supported by the system.
"""
init()
target_device = runtime.get_device(target_device)
peer_device = runtime.get_device(peer_device)
if not target_device.is_cuda or not peer_device.is_cuda:
return False
return bool(runtime.core.cuda_is_peer_access_supported(target_device.ordinal, peer_device.ordinal))
def is_peer_access_enabled(target_device: Devicelike, peer_device: Devicelike):
"""Check if `peer_device` can currently access the memory of `target_device`.
This applies to memory allocated using default CUDA allocators. For memory allocated using
CUDA pooled allocators, use `is_mempool_access_enabled()`.
Returns:
A Boolean value indicating if this peer access is currently enabled.
"""
init()
target_device = runtime.get_device(target_device)
peer_device = runtime.get_device(peer_device)
if not target_device.is_cuda or not peer_device.is_cuda:
return False
return bool(runtime.core.cuda_is_peer_access_enabled(target_device.context, peer_device.context))
def set_peer_access_enabled(target_device: Devicelike, peer_device: Devicelike, enable: bool):
"""Enable or disable direct access from `peer_device` to the memory of `target_device`.
Enabling peer access can improve the speed of peer-to-peer memory transfers, but can have
a negative impact on memory consumption and allocation performance.
This applies to memory allocated using default CUDA allocators. For memory allocated using
CUDA pooled allocators, use `set_mempool_access_enabled()`.
"""
init()
target_device = runtime.get_device(target_device)
peer_device = runtime.get_device(peer_device)
if not target_device.is_cuda or not peer_device.is_cuda:
if enable:
raise ValueError("Peer access is only supported between CUDA devices")
else:
return
if not is_peer_access_supported(target_device, peer_device):
if enable:
raise RuntimeError(f"Device {peer_device} cannot access device {target_device}")
else:
return
if not runtime.core.cuda_set_peer_access_enabled(target_device.context, peer_device.context, int(enable)):
action = "enable" if enable else "disable"
raise RuntimeError(f"Failed to {action} peer access from device {peer_device} to device {target_device}")
def is_mempool_access_supported(target_device: Devicelike, peer_device: Devicelike):
"""Check if `peer_device` can directly access the memory pool of `target_device`.
If mempool access is possible, it can be managed using `set_mempool_access_enabled()` and `is_mempool_access_enabled()`.
Returns:
A Boolean value indicating if this memory pool access is supported by the system.
"""
init()
return target_device.is_mempool_supported and is_peer_access_supported(target_device, peer_device)
def is_mempool_access_enabled(target_device: Devicelike, peer_device: Devicelike):
"""Check if `peer_device` can currently access the memory pool of `target_device`.
This applies to memory allocated using CUDA pooled allocators. For memory allocated using
default CUDA allocators, use `is_peer_access_enabled()`.
Returns:
A Boolean value indicating if this peer access is currently enabled.
"""
init()
target_device = runtime.get_device(target_device)
peer_device = runtime.get_device(peer_device)
if not peer_device.is_cuda or not target_device.is_cuda or not target_device.is_mempool_supported:
return False
return bool(runtime.core.cuda_is_mempool_access_enabled(target_device.ordinal, peer_device.ordinal))
def set_mempool_access_enabled(target_device: Devicelike, peer_device: Devicelike, enable: bool):
"""Enable or disable access from `peer_device` to the memory pool of `target_device`.
This applies to memory allocated using CUDA pooled allocators. For memory allocated using
default CUDA allocators, use `set_peer_access_enabled()`.
"""
init()
target_device = runtime.get_device(target_device)
peer_device = runtime.get_device(peer_device)
if not target_device.is_cuda or not peer_device.is_cuda:
if enable:
raise ValueError("Memory pool access is only supported between CUDA devices")
else:
return
if not target_device.is_mempool_supported:
if enable:
raise RuntimeError(f"Device {target_device} does not support memory pools")
else:
return
if not is_peer_access_supported(target_device, peer_device):
if enable:
raise RuntimeError(f"Device {peer_device} cannot access device {target_device}")
else:
return
if not runtime.core.cuda_set_mempool_access_enabled(target_device.ordinal, peer_device.ordinal, int(enable)):
action = "enable" if enable else "disable"
raise RuntimeError(f"Failed to {action} memory pool access from device {peer_device} to device {target_device}")
def get_stream(device: Devicelike = None) -> Stream:
"""Return the stream currently used by the given device"""
return get_device(device).stream
def set_stream(stream, device: Devicelike = None, sync: bool = False):
"""Set the stream to be used by the given device.
If this is an external stream, caller is responsible for guaranteeing the lifetime of the stream.
Consider using wp.ScopedStream instead.
"""
get_device(device).set_stream(stream, sync=sync)
def record_event(event: Event = None):
"""Record a CUDA event on the current stream.
Args:
event: Event to record. If None, a new Event will be created.
Returns:
The recorded event.
"""
return get_stream().record_event(event)
def wait_event(event: Event):
"""Make the current stream wait for a CUDA event.
Args:
event: Event to wait for.
"""
get_stream().wait_event(event)
def get_event_elapsed_time(start_event: Event, end_event: Event, synchronize: bool = True):
"""Get the elapsed time between two recorded events.
The result is in milliseconds with a resolution of about 0.5 microsecond.
Both events must have been previously recorded with ``wp.record_event()`` or ``wp.Stream.record_event()``.
If ``synchronize`` is False, the caller must ensure that device execution has reached ``end_event``
prior to calling ``get_event_elapsed_time()``.
Args:
start_event (Event): The start event.
end_event (Event): The end event.
synchronize (bool, optional): Whether Warp should synchronize on the ``end_event``.
"""
# ensure the end_event is reached
if synchronize:
synchronize_event(end_event)
return runtime.core.cuda_event_elapsed_time(start_event.cuda_event, end_event.cuda_event)
def wait_stream(stream: Stream, event: Event = None):
"""Make the current stream wait for another CUDA stream to complete its work.
Args:
event: Event to be used. If None, a new Event will be created.
"""
get_stream().wait_stream(stream, event=event)
class RegisteredGLBuffer:
"""
Helper object to register a GL buffer with CUDA so that it can be mapped to a Warp array.
"""
# Specifies no hints about how this resource will be used.
# It is therefore assumed that this resource will be
# read from and written to by CUDA. This is the default value.
NONE = 0x00
# Specifies that CUDA will not write to this resource.
READ_ONLY = 0x01
# Specifies that CUDA will not read from this resource and will write over the
# entire contents of the resource, so none of the data previously
# stored in the resource will be preserved.
WRITE_DISCARD = 0x02
def __init__(self, gl_buffer_id: int, device: Devicelike = None, flags: int = NONE):
"""Create a new RegisteredGLBuffer object.
Args:
gl_buffer_id: The OpenGL buffer id (GLuint).
device: The device to register the buffer with. If None, the current device will be used.
flags: A combination of the flags constants.
"""
self.gl_buffer_id = gl_buffer_id
self.device = get_device(device)
self.context = self.device.context
self.resource = runtime.core.cuda_graphics_register_gl_buffer(self.context, gl_buffer_id, flags)
def __del__(self):
if not self.resource:
return
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
runtime.core.cuda_graphics_unregister_resource(self.context, self.resource)
def map(self, dtype, shape) -> warp.array:
"""Map the OpenGL buffer to a Warp array.
Args:
dtype: The type of each element in the array.
shape: The shape of the array.
Returns:
A Warp array object representing the mapped OpenGL buffer.
"""
runtime.core.cuda_graphics_map(self.context, self.resource)
ctypes.POINTER(ctypes.c_uint64), ctypes.POINTER(ctypes.c_size_t)
ptr = ctypes.c_uint64(0)
size = ctypes.c_size_t(0)
runtime.core.cuda_graphics_device_ptr_and_size(
self.context, self.resource, ctypes.byref(ptr), ctypes.byref(size)
)
return warp.array(ptr=ptr.value, dtype=dtype, shape=shape, device=self.device)
def unmap(self):
"""Unmap the OpenGL buffer."""
runtime.core.cuda_graphics_unmap(self.context, self.resource)
def zeros(
shape: Tuple = None,
dtype=float,
device: Devicelike = None,
requires_grad: bool = False,
pinned: bool = False,
**kwargs,
) -> warp.array:
"""Return a zero-initialized array
Args:
shape: Array dimensions
dtype: Type of each element, e.g.: warp.vec3, warp.mat33, etc
device: Device that array will live on
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
arr = empty(shape=shape, dtype=dtype, device=device, requires_grad=requires_grad, pinned=pinned, **kwargs)
arr.zero_()
return arr
def zeros_like(
src: warp.array, device: Devicelike = None, requires_grad: bool = None, pinned: bool = None
) -> warp.array:
"""Return a zero-initialized array with the same type and dimension of another array
Args:
src: The template array to use for shape, data type, and device
device: The device where the new array will be created (defaults to src.device)
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
arr = empty_like(src, device=device, requires_grad=requires_grad, pinned=pinned)
arr.zero_()
return arr
def ones(
shape: Tuple = None,
dtype=float,
device: Devicelike = None,
requires_grad: bool = False,
pinned: bool = False,
**kwargs,
) -> warp.array:
"""Return a one-initialized array
Args:
shape: Array dimensions
dtype: Type of each element, e.g.: warp.vec3, warp.mat33, etc
device: Device that array will live on
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
return full(shape=shape, value=1, dtype=dtype, device=device, requires_grad=requires_grad, pinned=pinned, **kwargs)
def ones_like(
src: warp.array, device: Devicelike = None, requires_grad: bool = None, pinned: bool = None
) -> warp.array:
"""Return a one-initialized array with the same type and dimension of another array
Args:
src: The template array to use for shape, data type, and device
device: The device where the new array will be created (defaults to src.device)
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
return full_like(src, 1, device=device, requires_grad=requires_grad, pinned=pinned)
def full(
shape: Tuple = None,
value=0,
dtype=Any,
device: Devicelike = None,
requires_grad: bool = False,
pinned: bool = False,
**kwargs,
) -> warp.array:
"""Return an array with all elements initialized to the given value
Args:
shape: Array dimensions
value: Element value
dtype: Type of each element, e.g.: float, warp.vec3, warp.mat33, etc
device: Device that array will live on
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
if dtype == Any:
# determine dtype from value
value_type = type(value)
if value_type == int:
dtype = warp.int32
elif value_type == float:
dtype = warp.float32
elif value_type == bool:
dtype = warp.bool
elif value_type in warp.types.scalar_types or hasattr(value_type, "_wp_scalar_type_"):
dtype = value_type
elif isinstance(value, warp.codegen.StructInstance):
dtype = value._cls
elif hasattr(value, "__len__"):
# a sequence, assume it's a vector or matrix value
try:
# try to convert to a numpy array first
na = np.array(value, copy=False)
except Exception as e:
raise ValueError(f"Failed to interpret the value as a vector or matrix: {e}") from e
# determine the scalar type
scalar_type = warp.types.np_dtype_to_warp_type.get(na.dtype)
if scalar_type is None:
raise ValueError(f"Failed to convert {na.dtype} to a Warp data type")
# determine if vector or matrix
if na.ndim == 1:
dtype = warp.types.vector(na.size, scalar_type)
elif na.ndim == 2:
dtype = warp.types.matrix(na.shape, scalar_type)
else:
raise ValueError("Values with more than two dimensions are not supported")
else:
raise ValueError(f"Invalid value type for Warp array: {value_type}")
arr = empty(shape=shape, dtype=dtype, device=device, requires_grad=requires_grad, pinned=pinned, **kwargs)
arr.fill_(value)
return arr
def full_like(
src: warp.array, value: Any, device: Devicelike = None, requires_grad: bool = None, pinned: bool = None
) -> warp.array:
"""Return an array with all elements initialized to the given value with the same type and dimension of another array
Args:
src: The template array to use for shape, data type, and device
value: Element value
device: The device where the new array will be created (defaults to src.device)
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
arr = empty_like(src, device=device, requires_grad=requires_grad, pinned=pinned)
arr.fill_(value)
return arr
def clone(src: warp.array, device: Devicelike = None, requires_grad: bool = None, pinned: bool = None) -> warp.array:
"""Clone an existing array, allocates a copy of the src memory
Args:
src: The source array to copy
device: The device where the new array will be created (defaults to src.device)
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
arr = empty_like(src, device=device, requires_grad=requires_grad, pinned=pinned)
warp.copy(arr, src)
return arr
def empty(
shape: Tuple = None,
dtype=float,
device: Devicelike = None,
requires_grad: bool = False,
pinned: bool = False,
**kwargs,
) -> warp.array:
"""Returns an uninitialized array
Args:
shape: Array dimensions
dtype: Type of each element, e.g.: `warp.vec3`, `warp.mat33`, etc
device: Device that array will live on
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
# backwards compatibility for case where users called wp.empty(n=length, ...)
if "n" in kwargs:
shape = (kwargs["n"],)
del kwargs["n"]
# ensure shape is specified, even if creating a zero-sized array
if shape is None:
shape = 0
return warp.array(shape=shape, dtype=dtype, device=device, requires_grad=requires_grad, pinned=pinned, **kwargs)
def empty_like(
src: warp.array, device: Devicelike = None, requires_grad: bool = None, pinned: bool = None
) -> warp.array:
"""Return an uninitialized array with the same type and dimension of another array
Args:
src: The template array to use for shape, data type, and device
device: The device where the new array will be created (defaults to src.device)
requires_grad: Whether the array will be tracked for back propagation
pinned: Whether the array uses pinned host memory (only applicable to CPU arrays)
Returns:
A warp.array object representing the allocation
"""
if device is None:
device = src.device
if requires_grad is None:
if hasattr(src, "requires_grad"):
requires_grad = src.requires_grad
else:
requires_grad = False
if pinned is None:
if hasattr(src, "pinned"):
pinned = src.pinned
else:
pinned = False
arr = empty(shape=src.shape, dtype=src.dtype, device=device, requires_grad=requires_grad, pinned=pinned)
return arr
def from_numpy(
arr: np.ndarray,
dtype: Optional[type] = None,
shape: Optional[Sequence[int]] = None,
device: Optional[Devicelike] = None,
requires_grad: bool = False,
) -> warp.array:
"""Returns a Warp array created from a NumPy array.
Args:
arr: The NumPy array providing the data to construct the Warp array.
dtype: The data type of the new Warp array. If this is not provided, the data type will be inferred.
shape: The shape of the Warp array.
device: The device on which the Warp array will be constructed.
requires_grad: Whether or not gradients will be tracked for this array.
Raises:
RuntimeError: The data type of the NumPy array is not supported.
"""
if dtype is None:
base_type = warp.types.np_dtype_to_warp_type.get(arr.dtype)
if base_type is None:
raise RuntimeError("Unsupported NumPy data type '{}'.".format(arr.dtype))
dim_count = len(arr.shape)
if dim_count == 2:
dtype = warp.types.vector(length=arr.shape[1], dtype=base_type)
elif dim_count == 3:
dtype = warp.types.matrix(shape=(arr.shape[1], arr.shape[2]), dtype=base_type)
else:
dtype = base_type
return warp.array(
data=arr,
dtype=dtype,
shape=shape,
device=device,
requires_grad=requires_grad,
)
# given a kernel destination argument type and a value convert
# to a c-type that can be passed to a kernel
def pack_arg(kernel, arg_type, arg_name, value, device, adjoint=False):
if warp.types.is_array(arg_type):
if value is None:
# allow for NULL arrays
return arg_type.__ctype__()
else:
# check for array type
# - in forward passes, array types have to match
# - in backward passes, indexed array gradients are regular arrays
if adjoint:
array_matches = isinstance(value, warp.array)
else:
array_matches = type(value) is type(arg_type)
if not array_matches:
adj = "adjoint " if adjoint else ""
raise RuntimeError(
f"Error launching kernel '{kernel.key}', {adj}argument '{arg_name}' expects an array of type {type(arg_type)}, but passed value has type {type(value)}."
)
# check subtype
if not warp.types.types_equal(value.dtype, arg_type.dtype):
adj = "adjoint " if adjoint else ""
raise RuntimeError(
f"Error launching kernel '{kernel.key}', {adj}argument '{arg_name}' expects an array with dtype={arg_type.dtype} but passed array has dtype={value.dtype}."
)
# check dimensions
if value.ndim != arg_type.ndim:
adj = "adjoint " if adjoint else ""
raise RuntimeError(
f"Error launching kernel '{kernel.key}', {adj}argument '{arg_name}' expects an array with {arg_type.ndim} dimension(s) but the passed array has {value.ndim} dimension(s)."
)
# check device
if value.device != device:
raise RuntimeError(
f"Error launching kernel '{kernel.key}', trying to launch on device='{device}', but input array for argument '{arg_name}' is on device={value.device}."
)
return value.__ctype__()
elif isinstance(arg_type, warp.codegen.Struct):
assert value is not None
return value.__ctype__()
# try to convert to a value type (vec3, mat33, etc)
elif issubclass(arg_type, ctypes.Array):
if warp.types.types_equal(type(value), arg_type):
return value
else:
# try constructing the required value from the argument (handles tuple / list, Gf.Vec3 case)
try:
return arg_type(value)
except Exception as e:
raise ValueError(f"Failed to convert argument for param {arg_name} to {type_str(arg_type)}") from e
elif isinstance(value, bool):
return ctypes.c_bool(value)
elif isinstance(value, arg_type):
try:
# try to pack as a scalar type
if arg_type is warp.types.float16:
return arg_type._type_(warp.types.float_to_half_bits(value.value))
else:
return arg_type._type_(value.value)
except Exception as e:
raise RuntimeError(
"Error launching kernel, unable to pack kernel parameter type "
f"{type(value)} for param {arg_name}, expected {arg_type}"
) from e
else:
try:
# try to pack as a scalar type
if arg_type is warp.types.float16:
return arg_type._type_(warp.types.float_to_half_bits(value))
else:
return arg_type._type_(value)
except Exception as e:
print(e)
raise RuntimeError(
"Error launching kernel, unable to pack kernel parameter type "
f"{type(value)} for param {arg_name}, expected {arg_type}"
) from e
# represents all data required for a kernel launch
# so that launches can be replayed quickly, use `wp.launch(..., record_cmd=True)`
class Launch:
def __init__(self, kernel, device, hooks=None, params=None, params_addr=None, bounds=None, max_blocks=0):
# if not specified look up hooks
if not hooks:
module = kernel.module
if not module.load(device):
return
hooks = module.get_kernel_hooks(kernel, device)
# if not specified set a zero bound
if not bounds:
bounds = warp.types.launch_bounds_t(0)
# if not specified then build a list of default value params for args
if not params:
params = []
params.append(bounds)
for a in kernel.adj.args:
if isinstance(a.type, warp.types.array):
params.append(a.type.__ctype__())
elif isinstance(a.type, warp.codegen.Struct):
params.append(a.type().__ctype__())
else:
params.append(pack_arg(kernel, a.type, a.label, 0, device, False))
kernel_args = [ctypes.c_void_p(ctypes.addressof(x)) for x in params]
kernel_params = (ctypes.c_void_p * len(kernel_args))(*kernel_args)
params_addr = kernel_params
self.kernel = kernel
self.hooks = hooks
self.params = params
self.params_addr = params_addr
self.device = device
self.bounds = bounds
self.max_blocks = max_blocks
def set_dim(self, dim):
self.bounds = warp.types.launch_bounds_t(dim)
# launch bounds always at index 0
self.params[0] = self.bounds
# for CUDA kernels we need to update the address to each arg
if self.params_addr:
self.params_addr[0] = ctypes.c_void_p(ctypes.addressof(self.bounds))
# set kernel param at an index, will convert to ctype as necessary
def set_param_at_index(self, index, value):
arg_type = self.kernel.adj.args[index].type
arg_name = self.kernel.adj.args[index].label
carg = pack_arg(self.kernel, arg_type, arg_name, value, self.device, False)
self.params[index + 1] = carg
# for CUDA kernels we need to update the address to each arg
if self.params_addr:
self.params_addr[index + 1] = ctypes.c_void_p(ctypes.addressof(carg))
# set kernel param at an index without any type conversion
# args must be passed as ctypes or basic int / float types
def set_param_at_index_from_ctype(self, index, value):
if isinstance(value, ctypes.Structure):
# not sure how to directly assign struct->struct without reallocating using ctypes
self.params[index + 1] = value
# for CUDA kernels we need to update the address to each arg
if self.params_addr:
self.params_addr[index + 1] = ctypes.c_void_p(ctypes.addressof(value))
else:
self.params[index + 1].__init__(value)
# set kernel param by argument name
def set_param_by_name(self, name, value):
for i, arg in enumerate(self.kernel.adj.args):
if arg.label == name:
self.set_param_at_index(i, value)
# set kernel param by argument name with no type conversions
def set_param_by_name_from_ctype(self, name, value):
# lookup argument index
for i, arg in enumerate(self.kernel.adj.args):
if arg.label == name:
self.set_param_at_index_from_ctype(i, value)
# set all params
def set_params(self, values):
for i, v in enumerate(values):
self.set_param_at_index(i, v)
# set all params without performing type-conversions
def set_params_from_ctypes(self, values):
for i, v in enumerate(values):
self.set_param_at_index_from_ctype(i, v)
def launch(self, stream=None) -> Any:
if self.device.is_cpu:
self.hooks.forward(*self.params)
else:
if stream is None:
stream = self.device.stream
runtime.core.cuda_launch_kernel(
self.device.context,
self.hooks.forward,
self.bounds.size,
self.max_blocks,
self.params_addr,
stream.cuda_stream,
)
def launch(
kernel,
dim: Tuple[int],
inputs: Sequence = [],
outputs: Sequence = [],
adj_inputs: Sequence = [],
adj_outputs: Sequence = [],
device: Devicelike = None,
stream: Stream = None,
adjoint=False,
record_tape=True,
record_cmd=False,
max_blocks=0,
):
"""Launch a Warp kernel on the target device
Kernel launches are asynchronous with respect to the calling Python thread.
Args:
kernel: The name of a Warp kernel function, decorated with the ``@wp.kernel`` decorator
dim: The number of threads to launch the kernel, can be an integer, or a Tuple of ints with max of 4 dimensions
inputs: The input parameters to the kernel (optional)
outputs: The output parameters (optional)
adj_inputs: The adjoint inputs (optional)
adj_outputs: The adjoint outputs (optional)
device: The device to launch on (optional)
stream: The stream to launch on (optional)
adjoint: Whether to run forward or backward pass (typically use False)
record_tape: When true the launch will be recorded the global wp.Tape() object when present
record_cmd: When True the launch will be returned as a ``Launch`` command object, the launch will not occur until the user calls ``cmd.launch()``
max_blocks: The maximum number of CUDA thread blocks to use. Only has an effect for CUDA kernel launches.
If negative or zero, the maximum hardware value will be used.
"""
init()
# if stream is specified, use the associated device
if stream is not None:
device = stream.device
else:
device = runtime.get_device(device)
# check function is a Kernel
if not isinstance(kernel, Kernel):
raise RuntimeError("Error launching kernel, can only launch functions decorated with @wp.kernel.")
# debugging aid
if warp.config.print_launches:
print(f"kernel: {kernel.key} dim: {dim} inputs: {inputs} outputs: {outputs} device: {device}")
# construct launch bounds
bounds = warp.types.launch_bounds_t(dim)
if bounds.size > 0:
# first param is the number of threads
params = []
params.append(bounds)
# converts arguments to kernel's expected ctypes and packs into params
def pack_args(args, params, adjoint=False):
for i, a in enumerate(args):
arg_type = kernel.adj.args[i].type
arg_name = kernel.adj.args[i].label
params.append(pack_arg(kernel, arg_type, arg_name, a, device, adjoint))
fwd_args = []
fwd_args.extend(inputs)
fwd_args.extend(outputs)
adj_args = []
adj_args.extend(adj_inputs)
adj_args.extend(adj_outputs)
if (len(fwd_args)) != (len(kernel.adj.args)):
raise RuntimeError(
f"Error launching kernel '{kernel.key}', passed {len(fwd_args)} arguments but kernel requires {len(kernel.adj.args)}."
)
# if it's a generic kernel, infer the required overload from the arguments
if kernel.is_generic:
fwd_types = kernel.infer_argument_types(fwd_args)
kernel = kernel.add_overload(fwd_types)
# delay load modules, including new overload if needed
module = kernel.module
if not module.load(device):
return
# late bind
hooks = module.get_kernel_hooks(kernel, device)
pack_args(fwd_args, params)
pack_args(adj_args, params, adjoint=True)
# run kernel
if device.is_cpu:
if adjoint:
if hooks.backward is None:
raise RuntimeError(
f"Failed to find backward kernel '{kernel.key}' from module '{kernel.module.name}' for device '{device}'"
)
hooks.backward(*params)
else:
if hooks.forward is None:
raise RuntimeError(
f"Failed to find forward kernel '{kernel.key}' from module '{kernel.module.name}' for device '{device}'"
)
if record_cmd:
launch = Launch(
kernel=kernel, hooks=hooks, params=params, params_addr=None, bounds=bounds, device=device
)
return launch
else:
hooks.forward(*params)
else:
kernel_args = [ctypes.c_void_p(ctypes.addressof(x)) for x in params]
kernel_params = (ctypes.c_void_p * len(kernel_args))(*kernel_args)
if stream is None:
stream = device.stream
if adjoint:
if hooks.backward is None:
raise RuntimeError(
f"Failed to find backward kernel '{kernel.key}' from module '{kernel.module.name}' for device '{device}'"
)
runtime.core.cuda_launch_kernel(
device.context, hooks.backward, bounds.size, max_blocks, kernel_params, stream.cuda_stream
)
else:
if hooks.forward is None:
raise RuntimeError(
f"Failed to find forward kernel '{kernel.key}' from module '{kernel.module.name}' for device '{device}'"
)
if record_cmd:
launch = Launch(
kernel=kernel,
hooks=hooks,
params=params,
params_addr=kernel_params,
bounds=bounds,
device=device,
)
return launch
else:
# launch
runtime.core.cuda_launch_kernel(
device.context, hooks.forward, bounds.size, max_blocks, kernel_params, stream.cuda_stream
)
try:
runtime.verify_cuda_device(device)
except Exception as e:
print(f"Error launching kernel: {kernel.key} on device {device}")
raise e
# record on tape if one is active
if runtime.tape and record_tape:
# record file, lineno, func as metadata
frame = inspect.currentframe().f_back
caller = {"file": frame.f_code.co_filename, "lineno": frame.f_lineno, "func": frame.f_code.co_name}
runtime.tape.record_launch(kernel, dim, max_blocks, inputs, outputs, device, metadata={"caller": caller})
def synchronize():
"""Manually synchronize the calling CPU thread with any outstanding CUDA work on all devices
This method allows the host application code to ensure that any kernel launches
or memory copies have completed.
"""
if is_cuda_driver_initialized():
# save the original context to avoid side effects
saved_context = runtime.core.cuda_context_get_current()
# TODO: only synchronize devices that have outstanding work
for device in runtime.cuda_devices:
# avoid creating primary context if the device has not been used yet
if device.has_context:
if device.is_capturing:
raise RuntimeError(f"Cannot synchronize device {device} while graph capture is active")
runtime.core.cuda_context_synchronize(device.context)
# restore the original context to avoid side effects
runtime.core.cuda_context_set_current(saved_context)
def synchronize_device(device: Devicelike = None):
"""Synchronize the calling CPU thread with any outstanding CUDA work on the specified device
This function allows the host application code to ensure that all kernel launches
and memory copies have completed on the device.
Args:
device: Device to synchronize.
"""
device = runtime.get_device(device)
if device.is_cuda:
if device.is_capturing:
raise RuntimeError(f"Cannot synchronize device {device} while graph capture is active")
runtime.core.cuda_context_synchronize(device.context)
def synchronize_stream(stream_or_device=None):
"""Synchronize the calling CPU thread with any outstanding CUDA work on the specified stream.
This function allows the host application code to ensure that all kernel launches
and memory copies have completed on the stream.
Args:
stream_or_device: `wp.Stream` or a device. If the argument is a device, synchronize the device's current stream.
"""
if isinstance(stream_or_device, Stream):
stream = stream_or_device
else:
stream = runtime.get_device(stream_or_device).stream
runtime.core.cuda_stream_synchronize(stream.cuda_stream)
def synchronize_event(event: Event):
"""Synchronize the calling CPU thread with an event recorded on a CUDA stream.
This function allows the host application code to ensure that a specific synchronization point was reached.
Args:
event: Event to wait for.
"""
runtime.core.cuda_event_synchronize(event.cuda_event)
def force_load(device: Union[Device, str, List[Device], List[str]] = None, modules: List[Module] = None):
"""Force user-defined kernels to be compiled and loaded
Args:
device: The device or list of devices to load the modules on. If None, load on all devices.
modules: List of modules to load. If None, load all imported modules.
"""
if is_cuda_driver_initialized():
# save original context to avoid side effects
saved_context = runtime.core.cuda_context_get_current()
if device is None:
devices = get_devices()
elif isinstance(device, list):
devices = [get_device(device_item) for device_item in device]
else:
devices = [get_device(device)]
if modules is None:
modules = user_modules.values()
for d in devices:
for m in modules:
m.load(d)
if is_cuda_available():
# restore original context to avoid side effects
runtime.core.cuda_context_set_current(saved_context)
def load_module(
module: Union[Module, types.ModuleType, str] = None, device: Union[Device, str] = None, recursive: bool = False
):
"""Force user-defined module to be compiled and loaded
Args:
module: The module to load. If None, load the current module.
device: The device to load the modules on. If None, load on all devices.
recursive: Whether to load submodules. E.g., if the given module is `warp.sim`, this will also load `warp.sim.model`, `warp.sim.articulation`, etc.
Note: A module must be imported before it can be loaded by this function.
"""
if module is None:
# if module not specified, use the module that called us
module = inspect.getmodule(inspect.stack()[1][0])
module_name = module.__name__
elif isinstance(module, Module):
module_name = module.name
elif isinstance(module, types.ModuleType):
module_name = module.__name__
elif isinstance(module, str):
module_name = module
else:
raise TypeError(f"Argument must be a module, got {type(module)}")
modules = []
# add the given module, if found
m = user_modules.get(module_name)
if m is not None:
modules.append(m)
# add submodules, if recursive
if recursive:
prefix = module_name + "."
for name, mod in user_modules.items():
if name.startswith(prefix):
modules.append(mod)
force_load(device=device, modules=modules)
def set_module_options(options: Dict[str, Any], module: Optional[Any] = None):
"""Set options for the current module.
Options can be used to control runtime compilation and code-generation
for the current module individually. Available options are listed below.
* **mode**: The compilation mode to use, can be "debug", or "release", defaults to the value of ``warp.config.mode``.
* **max_unroll**: The maximum fixed-size loop to unroll, defaults to the value of ``warp.config.max_unroll``.
Args:
options: Set of key-value option pairs
"""
if module is None:
m = inspect.getmodule(inspect.stack()[1][0])
else:
m = module
get_module(m.__name__).options.update(options)
get_module(m.__name__).unload()
def get_module_options(module: Optional[Any] = None) -> Dict[str, Any]:
"""Returns a list of options for the current module."""
if module is None:
m = inspect.getmodule(inspect.stack()[1][0])
else:
m = module
return get_module(m.__name__).options
def capture_begin(device: Devicelike = None, stream=None, force_module_load=None, external=False):
"""Begin capture of a CUDA graph
Captures all subsequent kernel launches and memory operations on CUDA devices.
This can be used to record large numbers of kernels and replay them with low overhead.
If `device` is specified, the capture will begin on the CUDA stream currently
associated with the device. If `stream` is specified, the capture will begin
on the given stream. If both are omitted, the capture will begin on the current
stream of the current device.
Args:
device: The CUDA device to capture on
stream: The CUDA stream to capture on
force_module_load: Whether or not to force loading of all kernels before capture.
In general it is better to use :func:`~warp.load_module()` to selectively load kernels.
When running with CUDA drivers that support CUDA 12.3 or newer, this option is not recommended to be set to
``True`` because kernels can be loaded during graph capture on more recent drivers. If this argument is
``None``, then the behavior inherits from ``wp.config.enable_graph_capture_module_load_by_default`` if the
driver is older than CUDA 12.3.
external: Whether the capture was already started externally
"""
if force_module_load is None:
if runtime.driver_version >= 12030:
# Driver versions 12.3 and can compile modules during graph capture
force_module_load = False
else:
force_module_load = warp.config.enable_graph_capture_module_load_by_default
if warp.config.verify_cuda:
raise RuntimeError("Cannot use CUDA error verification during graph capture")
if stream is not None:
device = stream.device
else:
device = runtime.get_device(device)
if not device.is_cuda:
raise RuntimeError("Must be a CUDA device")
stream = device.stream
if external:
# make sure the stream is already capturing
if not stream.is_capturing:
raise RuntimeError("External capture reported, but the stream is not capturing")
else:
# make sure the stream is not capturing yet
if stream.is_capturing:
raise RuntimeError("Graph capture already in progress on this stream")
if force_module_load:
force_load(device)
device.captures.add(stream)
if not runtime.core.cuda_graph_begin_capture(device.context, stream.cuda_stream, int(external)):
raise RuntimeError(runtime.get_error_string())
def capture_end(device: Devicelike = None, stream: Stream = None) -> Graph:
"""Ends the capture of a CUDA graph
Args:
device: The CUDA device where capture began
stream: The CUDA stream where capture began
Returns:
A Graph object that can be launched with :func:`~warp.capture_launch()`
"""
if stream is not None:
device = stream.device
else:
device = runtime.get_device(device)
if not device.is_cuda:
raise RuntimeError("Must be a CUDA device")
stream = device.stream
if stream not in device.captures:
raise RuntimeError("Graph capture is not active on this stream")
device.captures.remove(stream)
graph = ctypes.c_void_p()
result = runtime.core.cuda_graph_end_capture(device.context, stream.cuda_stream, ctypes.byref(graph))
if not result:
# A concrete error should've already been reported, so we don't need to go into details here
raise RuntimeError(f"CUDA graph capture failed. {runtime.get_error_string()}")
# note that for external captures, we do not return a graph, because we don't instantiate it ourselves
if graph:
return Graph(device, graph)
def capture_launch(graph: Graph, stream: Stream = None):
"""Launch a previously captured CUDA graph
Args:
graph: A Graph as returned by :func:`~warp.capture_end()`
stream: A Stream to launch the graph on (optional)
"""
if stream is not None:
if stream.device != graph.device:
raise RuntimeError(f"Cannot launch graph from device {graph.device} on stream from device {stream.device}")
device = stream.device
else:
device = graph.device
stream = device.stream
if not runtime.core.cuda_graph_launch(graph.exec, stream.cuda_stream):
raise RuntimeError(f"Graph launch error: {runtime.get_error_string()}")
def copy(
dest: warp.array, src: warp.array, dest_offset: int = 0, src_offset: int = 0, count: int = 0, stream: Stream = None
):
"""Copy array contents from `src` to `dest`.
Args:
dest: Destination array, must be at least as big as source buffer
src: Source array
dest_offset: Element offset in the destination array
src_offset: Element offset in the source array
count: Number of array elements to copy (will copy all elements if set to 0)
stream: The stream on which to perform the copy (optional)
The stream, if specified, can be from any device. If the stream is omitted, then Warp selects a stream based on the following rules:
(1) If the destination array is on a CUDA device, use the current stream on the destination device.
(2) Otherwise, if the source array is on a CUDA device, use the current stream on the source device.
If neither source nor destination are on a CUDA device, no stream is used for the copy.
"""
from warp.context import runtime
if not warp.types.is_array(src) or not warp.types.is_array(dest):
raise RuntimeError("Copy source and destination must be arrays")
# backwards compatibility, if count is zero then copy entire src array
if count <= 0:
count = src.size
if count == 0:
return
# figure out the stream for the copy
if stream is None:
if dest.device.is_cuda:
stream = dest.device.stream
elif src.device.is_cuda:
stream = src.device.stream
# Copying between different devices requires contiguous arrays. If the arrays
# are not contiguous, we must use temporary staging buffers for the transfer.
# TODO: We can skip the staging if device access is enabled.
if src.device != dest.device:
# If the source is not contiguous, make a contiguous copy on the source device.
if not src.is_contiguous:
# FIXME: We can't use a temporary CPU allocation during graph capture,
# because launching the graph will crash after the allocation is
# garbage-collected.
if src.device.is_cpu and stream.is_capturing:
raise RuntimeError("Failed to allocate a CPU staging buffer during graph capture")
# This involves an allocation and a kernel launch, which must run on the source device.
if src.device.is_cuda and stream != src.device.stream:
src.device.stream.wait_stream(stream)
src = src.contiguous()
stream.wait_stream(src.device.stream)
else:
src = src.contiguous()
# The source is now contiguous. If the destination is not contiguous,
# clone a contiguous copy on the destination device.
if not dest.is_contiguous:
# FIXME: We can't use a temporary CPU allocation during graph capture,
# because launching the graph will crash after the allocation is
# garbage-collected.
if dest.device.is_cpu and stream.is_capturing:
raise RuntimeError("Failed to allocate a CPU staging buffer during graph capture")
# The allocation must run on the destination device
if dest.device.is_cuda and stream != dest.device.stream:
dest.device.stream.wait_stream(stream)
tmp = empty_like(src, device=dest.device)
stream.wait_stream(dest.device.stream)
else:
tmp = empty_like(src, device=dest.device)
# Run the copy on the stream given by the caller
copy(tmp, src, stream=stream)
src = tmp
if src.is_contiguous and dest.is_contiguous:
bytes_to_copy = count * warp.types.type_size_in_bytes(src.dtype)
src_size_in_bytes = src.size * warp.types.type_size_in_bytes(src.dtype)
dst_size_in_bytes = dest.size * warp.types.type_size_in_bytes(dest.dtype)
src_offset_in_bytes = src_offset * warp.types.type_size_in_bytes(src.dtype)
dst_offset_in_bytes = dest_offset * warp.types.type_size_in_bytes(dest.dtype)
src_ptr = src.ptr + src_offset_in_bytes
dst_ptr = dest.ptr + dst_offset_in_bytes
if src_offset_in_bytes + bytes_to_copy > src_size_in_bytes:
raise RuntimeError(
f"Trying to copy source buffer with size ({bytes_to_copy}) from offset ({src_offset_in_bytes}) is larger than source size ({src_size_in_bytes})"
)
if dst_offset_in_bytes + bytes_to_copy > dst_size_in_bytes:
raise RuntimeError(
f"Trying to copy source buffer with size ({bytes_to_copy}) to offset ({dst_offset_in_bytes}) is larger than destination size ({dst_size_in_bytes})"
)
if dest.device.is_cuda:
if src.device.is_cuda:
if src.device == dest.device:
result = runtime.core.memcpy_d2d(
dest.device.context, dst_ptr, src_ptr, bytes_to_copy, stream.cuda_stream
)
else:
result = runtime.core.memcpy_p2p(
dest.device.context, dst_ptr, src.device.context, src_ptr, bytes_to_copy, stream.cuda_stream
)
else:
result = runtime.core.memcpy_h2d(
dest.device.context, dst_ptr, src_ptr, bytes_to_copy, stream.cuda_stream
)
else:
if src.device.is_cuda:
result = runtime.core.memcpy_d2h(
src.device.context, dst_ptr, src_ptr, bytes_to_copy, stream.cuda_stream
)
else:
result = runtime.core.memcpy_h2h(dst_ptr, src_ptr, bytes_to_copy)
if not result:
raise RuntimeError(f"Warp copy error: {runtime.get_error_string()}")
else:
# handle non-contiguous arrays
if src.shape != dest.shape:
raise RuntimeError("Incompatible array shapes")
src_elem_size = warp.types.type_size_in_bytes(src.dtype)
dst_elem_size = warp.types.type_size_in_bytes(dest.dtype)
if src_elem_size != dst_elem_size:
raise RuntimeError("Incompatible array data types")
# can't copy to/from fabric arrays of arrays, because they are jagged arrays of arbitrary lengths
# TODO?
if (
isinstance(src, (warp.fabricarray, warp.indexedfabricarray))
and src.ndim > 1
or isinstance(dest, (warp.fabricarray, warp.indexedfabricarray))
and dest.ndim > 1
):
raise RuntimeError("Copying to/from Fabric arrays of arrays is not supported")
src_desc = src.__ctype__()
dst_desc = dest.__ctype__()
src_ptr = ctypes.pointer(src_desc)
dst_ptr = ctypes.pointer(dst_desc)
src_type = warp.types.array_type_id(src)
dst_type = warp.types.array_type_id(dest)
if dest.device.is_cuda:
# This work involves a kernel launch, so it must run on the destination device.
# If the copy stream is different, we need to synchronize it.
if stream == dest.device.stream:
result = runtime.core.array_copy_device(
dest.device.context, dst_ptr, src_ptr, dst_type, src_type, src_elem_size
)
else:
dest.device.stream.wait_stream(stream)
result = runtime.core.array_copy_device(
dest.device.context, dst_ptr, src_ptr, dst_type, src_type, src_elem_size
)
stream.wait_stream(dest.device.stream)
else:
result = runtime.core.array_copy_host(dst_ptr, src_ptr, dst_type, src_type, src_elem_size)
if not result:
raise RuntimeError(f"Warp copy error: {runtime.get_error_string()}")
# copy gradient, if needed
if hasattr(src, "grad") and src.grad is not None and hasattr(dest, "grad") and dest.grad is not None:
copy(dest.grad, src.grad, stream=stream)
if runtime.tape:
runtime.tape.record_func(backward=lambda: adj_copy(dest.grad, src.grad, stream=stream), arrays=[dest, src])
def adj_copy(adj_dest: warp.array, adj_src: warp.array, stream: Stream = None):
"""Copy adjoint operation for wp.copy() calls on the tape.
Args:
adj_dest: Destination array adjoint
adj_src: Source array adjoint
stream: The stream on which the copy was performed in the forward pass
"""
copy(adj_src, adj_dest, stream=stream)
def type_str(t):
if t is None:
return "None"
elif t == Any:
return "Any"
elif t == Callable:
return "Callable"
elif t == Tuple[int, int]:
return "Tuple[int, int]"
elif isinstance(t, int):
return str(t)
elif isinstance(t, List):
return "Tuple[" + ", ".join(map(type_str, t)) + "]"
elif isinstance(t, warp.array):
return f"Array[{type_str(t.dtype)}]"
elif isinstance(t, warp.indexedarray):
return f"IndexedArray[{type_str(t.dtype)}]"
elif isinstance(t, warp.fabricarray):
return f"FabricArray[{type_str(t.dtype)}]"
elif isinstance(t, warp.indexedfabricarray):
return f"IndexedFabricArray[{type_str(t.dtype)}]"
elif hasattr(t, "_wp_generic_type_hint_"):
generic_type = t._wp_generic_type_hint_
# for concrete vec/mat types use the short name
if t in warp.types.vector_types:
return t.__name__
# for generic vector / matrix type use a Generic type hint
if generic_type == warp.types.Vector:
# return f"Vector"
return f"Vector[{type_str(t._wp_type_params_[0])},{type_str(t._wp_scalar_type_)}]"
elif generic_type == warp.types.Quaternion:
# return f"Quaternion"
return f"Quaternion[{type_str(t._wp_scalar_type_)}]"
elif generic_type == warp.types.Matrix:
# return f"Matrix"
return f"Matrix[{type_str(t._wp_type_params_[0])},{type_str(t._wp_type_params_[1])},{type_str(t._wp_scalar_type_)}]"
elif generic_type == warp.types.Transformation:
# return f"Transformation"
return f"Transformation[{type_str(t._wp_scalar_type_)}]"
raise TypeError("Invalid vector or matrix dimensions")
return t.__name__
def print_function(f, file, noentry=False): # pragma: no cover
"""Writes a function definition to a file for use in reST documentation
Args:
f: The function being written
file: The file object for output
noentry: If True, then the :noindex: and :nocontentsentry: directive
options will be added
Returns:
A bool indicating True if f was written to file
"""
if f.hidden:
return False
args = ", ".join(f"{k}: {type_str(v)}" for k, v in f.input_types.items())
return_type = ""
try:
# todo: construct a default value for each of the functions args
# so we can generate the return type for overloaded functions
return_type = " -> " + type_str(f.value_func(None, None, None))
except Exception:
pass
print(f".. py:function:: {f.key}({args}){return_type}", file=file)
if noentry:
print(" :noindex:", file=file)
print(" :nocontentsentry:", file=file)
print("", file=file)
if f.doc != "":
if not f.missing_grad:
print(f" {f.doc}", file=file)
else:
print(f" {f.doc} [1]_", file=file)
print("", file=file)
print(file=file)
return True
def export_functions_rst(file): # pragma: no cover
header = (
"..\n"
" Autogenerated File - Do not edit. Run build_docs.py to generate.\n"
"\n"
".. functions:\n"
".. currentmodule:: warp\n"
"\n"
"Kernel Reference\n"
"================"
)
print(header, file=file)
# type definitions of all functions by group
print("\nScalar Types", file=file)
print("------------", file=file)
for t in warp.types.scalar_types:
print(f".. class:: {t.__name__}", file=file)
# Manually add wp.bool since it's inconvenient to add to wp.types.scalar_types:
print(f".. class:: {warp.types.bool.__name__}", file=file)
print("\n\nVector Types", file=file)
print("------------", file=file)
for t in warp.types.vector_types:
print(f".. class:: {t.__name__}", file=file)
print("\nGeneric Types", file=file)
print("-------------", file=file)
print(".. class:: Int", file=file)
print(".. class:: Float", file=file)
print(".. class:: Scalar", file=file)
print(".. class:: Vector", file=file)
print(".. class:: Matrix", file=file)
print(".. class:: Quaternion", file=file)
print(".. class:: Transformation", file=file)
print(".. class:: Array", file=file)
print("\nQuery Types", file=file)
print("-------------", file=file)
print(".. autoclass:: bvh_query_t", file=file)
print(".. autoclass:: hash_grid_query_t", file=file)
print(".. autoclass:: mesh_query_aabb_t", file=file)
print(".. autoclass:: mesh_query_point_t", file=file)
print(".. autoclass:: mesh_query_ray_t", file=file)
# build dictionary of all functions by group
groups = {}
for _k, f in builtin_functions.items():
# build dict of groups
if f.group not in groups:
groups[f.group] = []
# append all overloads to the group
for o in f.overloads:
groups[f.group].append(o)
# Keep track of what function names have been written
written_functions = {}
for k, g in groups.items():
print("\n", file=file)
print(k, file=file)
print("---------------", file=file)
for f in g:
if f.key in written_functions:
# Add :noindex: + :nocontentsentry: since Sphinx gets confused
print_function(f, file=file, noentry=True)
else:
if print_function(f, file=file):
written_functions[f.key] = []
# footnotes
print(".. rubric:: Footnotes", file=file)
print(".. [1] Function gradients have not been implemented for backpropagation.", file=file)
def export_stubs(file): # pragma: no cover
"""Generates stub file for auto-complete of builtin functions"""
print(
"# Autogenerated file, do not edit, this file provides stubs for builtins autocomplete in VSCode, PyCharm, etc",
file=file,
)
print("", file=file)
print("from typing import Any", file=file)
print("from typing import Tuple", file=file)
print("from typing import Callable", file=file)
print("from typing import TypeVar", file=file)
print("from typing import Generic", file=file)
print("from typing import overload as over", file=file)
print(file=file)
# type hints, these need to be mirrored into the stubs file
print('Length = TypeVar("Length", bound=int)', file=file)
print('Rows = TypeVar("Rows", bound=int)', file=file)
print('Cols = TypeVar("Cols", bound=int)', file=file)
print('DType = TypeVar("DType")', file=file)
print('Int = TypeVar("Int")', file=file)
print('Float = TypeVar("Float")', file=file)
print('Scalar = TypeVar("Scalar")', file=file)
print("Vector = Generic[Length, Scalar]", file=file)
print("Matrix = Generic[Rows, Cols, Scalar]", file=file)
print("Quaternion = Generic[Float]", file=file)
print("Transformation = Generic[Float]", file=file)
print("Array = Generic[DType]", file=file)
print("FabricArray = Generic[DType]", file=file)
print("IndexedFabricArray = Generic[DType]", file=file)
# prepend __init__.py
with open(os.path.join(os.path.dirname(file.name), "__init__.py")) as header_file:
# strip comment lines
lines = [line for line in header_file if not line.startswith("#")]
header = "".join(lines)
print(header, file=file)
print(file=file)
for k, g in builtin_functions.items():
for f in g.overloads:
args = ", ".join(f"{k}: {type_str(v)}" for k, v in f.input_types.items())
return_str = ""
if not f.export or f.hidden: # or f.generic:
continue
try:
# todo: construct a default value for each of the functions args
# so we can generate the return type for overloaded functions
return_type = f.value_func(None, None, None)
if return_type:
return_str = " -> " + type_str(return_type)
except Exception:
pass
print("@over", file=file)
print(f"def {f.key}({args}){return_str}:", file=file)
print(f' """{f.doc}', file=file)
print(' """', file=file)
print(" ...\n\n", file=file)
def export_builtins(file: io.TextIOBase): # pragma: no cover
def ctype_arg_str(t):
if isinstance(t, int):
return "int"
elif isinstance(t, float):
return "float"
elif t in warp.types.vector_types:
return f"{t.__name__}&"
else:
return t.__name__
def ctype_ret_str(t):
if isinstance(t, int):
return "int"
elif isinstance(t, float):
return "float"
else:
return t.__name__
file.write("namespace wp {\n\n")
file.write('extern "C" {\n\n')
for k, g in builtin_functions.items():
for f in g.overloads:
if not f.export or f.generic:
continue
# only export simple types that don't use arrays
# or templated types
if not f.is_simple():
continue
args = ", ".join(f"{ctype_arg_str(v)} {k}" for k, v in f.input_types.items())
params = ", ".join(f.input_types.keys())
return_type = ""
try:
# todo: construct a default value for each of the functions args
# so we can generate the return type for overloaded functions
return_type = ctype_ret_str(f.value_func(None, None, None))
except Exception:
continue
if return_type.startswith("Tuple"):
continue
if args == "":
file.write(f"WP_API void {f.mangled_name}({return_type}* ret) {{ *ret = wp::{f.key}({params}); }}\n")
elif return_type == "None":
file.write(f"WP_API void {f.mangled_name}({args}) {{ wp::{f.key}({params}); }}\n")
else:
file.write(
f"WP_API void {f.mangled_name}({args}, {return_type}* ret) {{ *ret = wp::{f.key}({params}); }}\n"
)
file.write('\n} // extern "C"\n\n')
file.write("} // namespace wp\n")
# initialize global runtime
runtime = None
def init():
"""Initialize the Warp runtime. This function must be called before any other API call. If an error occurs an exception will be raised."""
global runtime
if runtime is None:
runtime = Runtime()
| 208,436 | Python | 38.275862 | 192 | 0.585427 |
NVIDIA/warp/warp/build.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 warp.config
from warp.thirdparty import appdirs
# builds cuda source to PTX or CUBIN using NVRTC (output type determined by output_path extension)
def build_cuda(cu_path, arch, output_path, config="release", verify_fp=False, fast_math=False):
with open(cu_path, "rb") as src_file:
src = src_file.read()
cu_path = cu_path.encode("utf-8")
inc_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "native").encode("utf-8")
output_path = output_path.encode("utf-8")
if warp.config.llvm_cuda:
warp.context.runtime.llvm.compile_cuda(src, cu_path, inc_path, output_path, False)
else:
err = warp.context.runtime.core.cuda_compile_program(
src, arch, inc_path, config == "debug", warp.config.verbose, verify_fp, fast_math, output_path
)
if err != 0:
raise Exception(f"CUDA kernel build failed with error code {err}")
# load PTX or CUBIN as a CUDA runtime module (input type determined by input_path extension)
def load_cuda(input_path, device):
if not device.is_cuda:
raise RuntimeError("Not a CUDA device")
return warp.context.runtime.core.cuda_load_module(device.context, input_path.encode("utf-8"))
def build_cpu(obj_path, cpp_path, mode="release", verify_fp=False, fast_math=False):
with open(cpp_path, "rb") as cpp:
src = cpp.read()
cpp_path = cpp_path.encode("utf-8")
inc_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "native").encode("utf-8")
obj_path = obj_path.encode("utf-8")
err = warp.context.runtime.llvm.compile_cpp(src, cpp_path, inc_path, obj_path, mode == "debug", verify_fp)
if err != 0:
raise Exception(f"CPU kernel build failed with error code {err}")
def init_kernel_cache(path=None):
"""Initialize kernel cache directory.
This function is used during Warp initialization, but it can also be called directly to change the cache location.
If the path is not explicitly specified, a default location will be chosen based on OS-specific conventions.
To change the default cache location, set warp.config.kernel_cache_dir before calling warp.init().
"""
if path is not None:
cache_root_dir = os.path.realpath(path)
elif "WARP_CACHE_PATH" in os.environ:
cache_root_dir = os.path.realpath(os.environ.get("WARP_CACHE_PATH"))
else:
cache_root_dir = appdirs.user_cache_dir(appname="warp", appauthor="NVIDIA", version=warp.config.version)
warp.config.kernel_cache_dir = cache_root_dir
os.makedirs(warp.config.kernel_cache_dir, exist_ok=True)
def clear_kernel_cache():
"""Clear the kernel cache."""
warp.context.init()
import shutil
is_intialized = warp.context.runtime is not None
assert is_intialized, "The kernel cache directory is not configured; wp.init() has not been called yet or failed."
for item in os.listdir(warp.config.kernel_cache_dir):
item_path = os.path.join(warp.config.kernel_cache_dir, item)
if os.path.isdir(item_path) and item.startswith("wp_"):
# Remove the directory and its contents
shutil.rmtree(item_path, ignore_errors=True)
| 3,690 | Python | 40.47191 | 118 | 0.682927 |
NVIDIA/warp/warp/types.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 __future__ import annotations
import builtins
import ctypes
import inspect
import struct
import zlib
from typing import Any, Callable, Generic, List, NamedTuple, Optional, Tuple, TypeVar, Union
import numpy as np
import warp
# type hints
T = TypeVar("T")
Length = TypeVar("Length", bound=int)
Rows = TypeVar("Rows")
Cols = TypeVar("Cols")
DType = TypeVar("DType")
Int = TypeVar("Int")
Float = TypeVar("Float")
Scalar = TypeVar("Scalar")
class Vector(Generic[Length, Scalar]):
pass
class Matrix(Generic[Rows, Cols, Scalar]):
pass
class Quaternion(Generic[Float]):
pass
class Transformation(Generic[Float]):
pass
class Array(Generic[DType]):
pass
def constant(x):
"""Function to declare compile-time constants accessible from Warp kernels
Args:
x: Compile-time constant value, can be any of the built-in math types.
"""
if not isinstance(x, (builtins.bool, int, float, tuple(scalar_and_bool_types), ctypes.Array)):
raise RuntimeError(f"Invalid constant type: {type(x)}")
return x
def float_to_half_bits(value):
return warp.context.runtime.core.float_to_half_bits(value)
def half_bits_to_float(value):
return warp.context.runtime.core.half_bits_to_float(value)
# ----------------------
# built-in types
def vector(length, dtype):
# canonicalize dtype
if dtype == int:
dtype = int32
elif dtype == float:
dtype = float32
elif dtype == builtins.bool:
dtype = bool
class vec_t(ctypes.Array):
# ctypes.Array data for length, shape and c type:
_length_ = 0 if length is Any else length
_shape_ = (_length_,)
if dtype is bool:
_type_ = ctypes.c_bool
elif dtype in [Scalar, Float]:
_type_ = ctypes.c_float
else:
_type_ = dtype._type_
# warp scalar type:
_wp_scalar_type_ = dtype
_wp_type_params_ = [length, dtype]
_wp_generic_type_str_ = "vec_t"
_wp_generic_type_hint_ = Vector
_wp_constructor_ = "vector"
# special handling for float16 type: in this case, data is stored
# as uint16 but it's actually half precision floating point
# data. This means we need to convert each of the arguments
# to uint16s containing half float bits before storing them in
# the array:
scalar_import = float_to_half_bits if _wp_scalar_type_ == float16 else lambda x: x
scalar_export = half_bits_to_float if _wp_scalar_type_ == float16 else lambda x: x
def __init__(self, *args):
num_args = len(args)
if num_args == 0:
super().__init__()
elif num_args == 1:
if hasattr(args[0], "__len__"):
# try to copy from expanded sequence, e.g. (1, 2, 3)
self.__init__(*args[0])
else:
# set all elements to the same value
value = vec_t.scalar_import(args[0])
for i in range(self._length_):
super().__setitem__(i, value)
elif num_args == self._length_:
# set all scalar elements
for i in range(self._length_):
super().__setitem__(i, vec_t.scalar_import(args[i]))
else:
raise ValueError(
f"Invalid number of arguments in vector constructor, expected {self._length_} elements, got {num_args}"
)
def __getitem__(self, key):
if isinstance(key, int):
return vec_t.scalar_export(super().__getitem__(key))
elif isinstance(key, slice):
if self._wp_scalar_type_ == float16:
return [vec_t.scalar_export(x) for x in super().__getitem__(key)]
else:
return super().__getitem__(key)
else:
raise KeyError(f"Invalid key {key}, expected int or slice")
def __setitem__(self, key, value):
if isinstance(key, int):
try:
return super().__setitem__(key, vec_t.scalar_import(value))
except (TypeError, ctypes.ArgumentError):
raise TypeError(
f"Expected to assign a `{self._wp_scalar_type_.__name__}` value "
f"but got `{type(value).__name__}` instead"
) from None
elif isinstance(key, slice):
try:
iter(value)
except TypeError:
raise TypeError(
f"Expected to assign a slice from a sequence of values "
f"but got `{type(value).__name__}` instead"
) from None
if self._wp_scalar_type_ == float16:
converted = []
try:
for x in value:
converted.append(vec_t.scalar_import(x))
except ctypes.ArgumentError:
raise TypeError(
f"Expected to assign a slice from a sequence of `float16` values "
f"but got `{type(x).__name__}` instead"
) from None
value = converted
try:
return super().__setitem__(key, value)
except TypeError:
for x in value:
try:
self._type_(x)
except TypeError:
raise TypeError(
f"Expected to assign a slice from a sequence of `{self._wp_scalar_type_.__name__}` values "
f"but got `{type(x).__name__}` instead"
) from None
else:
raise KeyError(f"Invalid key {key}, expected int or slice")
def __getattr__(self, name):
idx = "xyzw".find(name)
if idx != -1:
return self.__getitem__(idx)
return self.__getattribute__(name)
def __setattr__(self, name, value):
idx = "xyzw".find(name)
if idx != -1:
return self.__setitem__(idx, value)
return super().__setattr__(name, value)
def __add__(self, y):
return warp.add(self, y)
def __radd__(self, y):
return warp.add(y, self)
def __sub__(self, y):
return warp.sub(self, y)
def __rsub__(self, y):
return warp.sub(y, self)
def __mul__(self, y):
return warp.mul(self, y)
def __rmul__(self, x):
return warp.mul(x, self)
def __truediv__(self, y):
return warp.div(self, y)
def __rtruediv__(self, x):
return warp.div(x, self)
def __pos__(self):
return warp.pos(self)
def __neg__(self):
return warp.neg(self)
def __str__(self):
return f"[{', '.join(map(str, self))}]"
def __eq__(self, other):
for i in range(self._length_):
if self[i] != other[i]:
return False
return True
@classmethod
def from_ptr(cls, ptr):
if ptr:
# create a new vector instance and initialize the contents from the binary data
# this skips float16 conversions, assuming that float16 data is already encoded as uint16
value = cls()
ctypes.memmove(ctypes.byref(value), ptr, ctypes.sizeof(cls._type_) * cls._length_)
return value
else:
raise RuntimeError("NULL pointer exception")
return vec_t
def matrix(shape, dtype):
assert len(shape) == 2
# canonicalize dtype
if dtype == int:
dtype = int32
elif dtype == float:
dtype = float32
elif dtype == builtins.bool:
dtype = bool
class mat_t(ctypes.Array):
_length_ = 0 if shape[0] == Any or shape[1] == Any else shape[0] * shape[1]
_shape_ = (0, 0) if _length_ == 0 else shape
if dtype is bool:
_type_ = ctypes.c_bool
elif dtype in [Scalar, Float]:
_type_ = ctypes.c_float
else:
_type_ = dtype._type_
# warp scalar type:
# used in type checking and when writing out c++ code for constructors:
_wp_scalar_type_ = dtype
_wp_type_params_ = [shape[0], shape[1], dtype]
_wp_generic_type_str_ = "mat_t"
_wp_generic_type_hint_ = Matrix
_wp_constructor_ = "matrix"
_wp_row_type_ = vector(0 if shape[1] == Any else shape[1], dtype)
# special handling for float16 type: in this case, data is stored
# as uint16 but it's actually half precision floating point
# data. This means we need to convert each of the arguments
# to uint16s containing half float bits before storing them in
# the array:
scalar_import = float_to_half_bits if _wp_scalar_type_ == float16 else lambda x: x
scalar_export = half_bits_to_float if _wp_scalar_type_ == float16 else lambda x: x
def __init__(self, *args):
num_args = len(args)
if num_args == 0:
super().__init__()
elif num_args == 1:
if hasattr(args[0], "__len__"):
# try to copy from expanded sequence, e.g. [[1, 0], [0, 1]]
self.__init__(*args[0])
else:
# set all elements to the same value
value = mat_t.scalar_import(args[0])
for i in range(self._length_):
super().__setitem__(i, value)
elif num_args == self._length_:
# set all scalar elements
for i in range(self._length_):
super().__setitem__(i, mat_t.scalar_import(args[i]))
elif num_args == self._shape_[0]:
# row vectors
for i, row in enumerate(args):
if not hasattr(row, "__len__") or len(row) != self._shape_[1]:
raise TypeError(
f"Invalid argument in matrix constructor, expected row of length {self._shape_[1]}, got {row}"
)
offset = i * self._shape_[1]
for i in range(self._shape_[1]):
super().__setitem__(offset + i, mat_t.scalar_import(row[i]))
else:
raise ValueError(
f"Invalid number of arguments in matrix constructor, expected {self._length_} elements, got {num_args}"
)
def __add__(self, y):
return warp.add(self, y)
def __radd__(self, y):
return warp.add(y, self)
def __sub__(self, y):
return warp.sub(self, y)
def __rsub__(self, y):
return warp.sub(y, self)
def __mul__(self, y):
return warp.mul(self, y)
def __rmul__(self, x):
return warp.mul(x, self)
def __matmul__(self, y):
return warp.mul(self, y)
def __rmatmul__(self, x):
return warp.mul(x, self)
def __truediv__(self, y):
return warp.div(self, y)
def __rtruediv__(self, x):
return warp.div(x, self)
def __pos__(self):
return warp.pos(self)
def __neg__(self):
return warp.neg(self)
def __str__(self):
row_str = []
for r in range(self._shape_[0]):
row_val = self.get_row(r)
row_str.append(f"[{', '.join(map(str, row_val))}]")
return "[" + ",\n ".join(row_str) + "]"
def __eq__(self, other):
for i in range(self._shape_[0]):
for j in range(self._shape_[1]):
if self[i][j] != other[i][j]:
return False
return True
def get_row(self, r):
if r < 0 or r >= self._shape_[0]:
raise IndexError("Invalid row index")
row_start = r * self._shape_[1]
row_end = row_start + self._shape_[1]
row_data = super().__getitem__(slice(row_start, row_end))
if self._wp_scalar_type_ == float16:
return self._wp_row_type_(*[mat_t.scalar_export(x) for x in row_data])
else:
return self._wp_row_type_(row_data)
def set_row(self, r, v):
if r < 0 or r >= self._shape_[0]:
raise IndexError("Invalid row index")
try:
iter(v)
except TypeError:
raise TypeError(
f"Expected to assign a slice from a sequence of values " f"but got `{type(v).__name__}` instead"
) from None
row_start = r * self._shape_[1]
row_end = row_start + self._shape_[1]
if self._wp_scalar_type_ == float16:
converted = []
try:
for x in v:
converted.append(mat_t.scalar_import(x))
except ctypes.ArgumentError:
raise TypeError(
f"Expected to assign a slice from a sequence of `float16` values "
f"but got `{type(x).__name__}` instead"
) from None
v = converted
super().__setitem__(slice(row_start, row_end), v)
def __getitem__(self, key):
if isinstance(key, Tuple):
# element indexing m[i,j]
if len(key) != 2:
raise KeyError(f"Invalid key, expected one or two indices, got {len(key)}")
if any(isinstance(x, slice) for x in key):
raise KeyError("Slices are not supported when indexing matrices using the `m[i, j]` notation")
return mat_t.scalar_export(super().__getitem__(key[0] * self._shape_[1] + key[1]))
elif isinstance(key, int):
# row vector indexing m[r]
return self.get_row(key)
else:
raise KeyError(f"Invalid key {key}, expected int or pair of ints")
def __setitem__(self, key, value):
if isinstance(key, Tuple):
# element indexing m[i,j] = x
if len(key) != 2:
raise KeyError(f"Invalid key, expected one or two indices, got {len(key)}")
if any(isinstance(x, slice) for x in key):
raise KeyError("Slices are not supported when indexing matrices using the `m[i, j]` notation")
try:
return super().__setitem__(key[0] * self._shape_[1] + key[1], mat_t.scalar_import(value))
except (TypeError, ctypes.ArgumentError):
raise TypeError(
f"Expected to assign a `{self._wp_scalar_type_.__name__}` value "
f"but got `{type(value).__name__}` instead"
) from None
elif isinstance(key, int):
# row vector indexing m[r] = v
return self.set_row(key, value)
elif isinstance(key, slice):
raise KeyError("Slices are not supported when indexing matrices using the `m[start:end]` notation")
else:
raise KeyError(f"Invalid key {key}, expected int or pair of ints")
@classmethod
def from_ptr(cls, ptr):
if ptr:
# create a new matrix instance and initialize the contents from the binary data
# this skips float16 conversions, assuming that float16 data is already encoded as uint16
value = cls()
ctypes.memmove(ctypes.byref(value), ptr, ctypes.sizeof(cls._type_) * cls._length_)
return value
else:
raise RuntimeError("NULL pointer exception")
return mat_t
class void:
def __init__(self):
pass
class bool:
_length_ = 1
_type_ = ctypes.c_bool
def __init__(self, x=False):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value != 0)
def __int__(self) -> int:
return int(self.value != 0)
class float16:
_length_ = 1
_type_ = ctypes.c_uint16
def __init__(self, x=0.0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0.0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
class float32:
_length_ = 1
_type_ = ctypes.c_float
def __init__(self, x=0.0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0.0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
class float64:
_length_ = 1
_type_ = ctypes.c_double
def __init__(self, x=0.0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0.0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
class int8:
_length_ = 1
_type_ = ctypes.c_int8
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class uint8:
_length_ = 1
_type_ = ctypes.c_uint8
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class int16:
_length_ = 1
_type_ = ctypes.c_int16
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class uint16:
_length_ = 1
_type_ = ctypes.c_uint16
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class int32:
_length_ = 1
_type_ = ctypes.c_int32
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class uint32:
_length_ = 1
_type_ = ctypes.c_uint32
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class int64:
_length_ = 1
_type_ = ctypes.c_int64
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
class uint64:
_length_ = 1
_type_ = ctypes.c_uint64
def __init__(self, x=0):
self.value = x
def __bool__(self) -> bool:
return self.value != 0
def __float__(self) -> float:
return float(self.value)
def __int__(self) -> int:
return int(self.value)
def __index__(self) -> int:
return int(self.value)
def quaternion(dtype=Any):
class quat_t(vector(length=4, dtype=dtype)):
pass
# def __init__(self, *args):
# super().__init__(args)
ret = quat_t
ret._wp_type_params_ = [dtype]
ret._wp_generic_type_str_ = "quat_t"
ret._wp_generic_type_hint_ = Quaternion
ret._wp_constructor_ = "quaternion"
return ret
class quath(quaternion(dtype=float16)):
pass
class quatf(quaternion(dtype=float32)):
pass
class quatd(quaternion(dtype=float64)):
pass
def transformation(dtype=Any):
class transform_t(vector(length=7, dtype=dtype)):
_wp_init_from_components_sig_ = inspect.Signature(
(
inspect.Parameter(
"p",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
default=(0.0, 0.0, 0.0),
),
inspect.Parameter(
"q",
inspect.Parameter.POSITIONAL_OR_KEYWORD,
default=(0.0, 0.0, 0.0, 1.0),
),
),
)
_wp_type_params_ = [dtype]
_wp_generic_type_str_ = "transform_t"
_wp_generic_type_hint_ = Transformation
_wp_constructor_ = "transformation"
def __init__(self, *args, **kwargs):
if len(args) == 1 and len(kwargs) == 0:
if args[0]._wp_generic_type_str_ == self._wp_generic_type_str_:
# Copy constructor.
super().__init__(*args[0])
return
try:
# For backward compatibility, try to check if the arguments
# match the original signature that'd allow initializing
# the `p` and `q` components separately.
bound_args = self._wp_init_from_components_sig_.bind(*args, **kwargs)
bound_args.apply_defaults()
p, q = bound_args.args
except (TypeError, ValueError):
# Fallback to the vector's constructor.
super().__init__(*args)
return
# Even if the arguments match the original “from components”
# signature, we still need to make sure that they represent
# sequences that can be unpacked.
if hasattr(p, "__len__") and hasattr(q, "__len__"):
# Initialize from the `p` and `q` components.
super().__init__()
self[0:3] = vector(length=3, dtype=dtype)(*p)
self[3:7] = quaternion(dtype=dtype)(*q)
return
# Fallback to the vector's constructor.
super().__init__(*args)
@property
def p(self):
return vec3(self[0:3])
@property
def q(self):
return quat(self[3:7])
return transform_t
class transformh(transformation(dtype=float16)):
pass
class transformf(transformation(dtype=float32)):
pass
class transformd(transformation(dtype=float64)):
pass
class vec2h(vector(length=2, dtype=float16)):
pass
class vec3h(vector(length=3, dtype=float16)):
pass
class vec4h(vector(length=4, dtype=float16)):
pass
class vec2f(vector(length=2, dtype=float32)):
pass
class vec3f(vector(length=3, dtype=float32)):
pass
class vec4f(vector(length=4, dtype=float32)):
pass
class vec2d(vector(length=2, dtype=float64)):
pass
class vec3d(vector(length=3, dtype=float64)):
pass
class vec4d(vector(length=4, dtype=float64)):
pass
class vec2b(vector(length=2, dtype=int8)):
pass
class vec3b(vector(length=3, dtype=int8)):
pass
class vec4b(vector(length=4, dtype=int8)):
pass
class vec2ub(vector(length=2, dtype=uint8)):
pass
class vec3ub(vector(length=3, dtype=uint8)):
pass
class vec4ub(vector(length=4, dtype=uint8)):
pass
class vec2s(vector(length=2, dtype=int16)):
pass
class vec3s(vector(length=3, dtype=int16)):
pass
class vec4s(vector(length=4, dtype=int16)):
pass
class vec2us(vector(length=2, dtype=uint16)):
pass
class vec3us(vector(length=3, dtype=uint16)):
pass
class vec4us(vector(length=4, dtype=uint16)):
pass
class vec2i(vector(length=2, dtype=int32)):
pass
class vec3i(vector(length=3, dtype=int32)):
pass
class vec4i(vector(length=4, dtype=int32)):
pass
class vec2ui(vector(length=2, dtype=uint32)):
pass
class vec3ui(vector(length=3, dtype=uint32)):
pass
class vec4ui(vector(length=4, dtype=uint32)):
pass
class vec2l(vector(length=2, dtype=int64)):
pass
class vec3l(vector(length=3, dtype=int64)):
pass
class vec4l(vector(length=4, dtype=int64)):
pass
class vec2ul(vector(length=2, dtype=uint64)):
pass
class vec3ul(vector(length=3, dtype=uint64)):
pass
class vec4ul(vector(length=4, dtype=uint64)):
pass
class mat22h(matrix(shape=(2, 2), dtype=float16)):
pass
class mat33h(matrix(shape=(3, 3), dtype=float16)):
pass
class mat44h(matrix(shape=(4, 4), dtype=float16)):
pass
class mat22f(matrix(shape=(2, 2), dtype=float32)):
pass
class mat33f(matrix(shape=(3, 3), dtype=float32)):
pass
class mat44f(matrix(shape=(4, 4), dtype=float32)):
pass
class mat22d(matrix(shape=(2, 2), dtype=float64)):
pass
class mat33d(matrix(shape=(3, 3), dtype=float64)):
pass
class mat44d(matrix(shape=(4, 4), dtype=float64)):
pass
class spatial_vectorh(vector(length=6, dtype=float16)):
pass
class spatial_vectorf(vector(length=6, dtype=float32)):
pass
class spatial_vectord(vector(length=6, dtype=float64)):
pass
class spatial_matrixh(matrix(shape=(6, 6), dtype=float16)):
pass
class spatial_matrixf(matrix(shape=(6, 6), dtype=float32)):
pass
class spatial_matrixd(matrix(shape=(6, 6), dtype=float64)):
pass
# built-in type aliases that default to 32bit precision
vec2 = vec2f
vec3 = vec3f
vec4 = vec4f
mat22 = mat22f
mat33 = mat33f
mat44 = mat44f
quat = quatf
transform = transformf
spatial_vector = spatial_vectorf
spatial_matrix = spatial_matrixf
int_types = (int8, uint8, int16, uint16, int32, uint32, int64, uint64)
float_types = (float16, float32, float64)
scalar_types = int_types + float_types
scalar_and_bool_types = scalar_types + (bool,)
vector_types = (
vec2b,
vec2ub,
vec2s,
vec2us,
vec2i,
vec2ui,
vec2l,
vec2ul,
vec2h,
vec2f,
vec2d,
vec3b,
vec3ub,
vec3s,
vec3us,
vec3i,
vec3ui,
vec3l,
vec3ul,
vec3h,
vec3f,
vec3d,
vec4b,
vec4ub,
vec4s,
vec4us,
vec4i,
vec4ui,
vec4l,
vec4ul,
vec4h,
vec4f,
vec4d,
mat22h,
mat22f,
mat22d,
mat33h,
mat33f,
mat33d,
mat44h,
mat44f,
mat44d,
quath,
quatf,
quatd,
transformh,
transformf,
transformd,
spatial_vectorh,
spatial_vectorf,
spatial_vectord,
spatial_matrixh,
spatial_matrixf,
spatial_matrixd,
)
np_dtype_to_warp_type = {
# Numpy scalar types
np.bool_: bool,
np.int8: int8,
np.uint8: uint8,
np.int16: int16,
np.uint16: uint16,
np.int32: int32,
np.int64: int64,
np.uint32: uint32,
np.uint64: uint64,
np.byte: int8,
np.ubyte: uint8,
np.float16: float16,
np.float32: float32,
np.float64: float64,
# Numpy dtype objects
np.dtype(np.bool_): bool,
np.dtype(np.int8): int8,
np.dtype(np.uint8): uint8,
np.dtype(np.int16): int16,
np.dtype(np.uint16): uint16,
np.dtype(np.int32): int32,
np.dtype(np.int64): int64,
np.dtype(np.uint32): uint32,
np.dtype(np.uint64): uint64,
np.dtype(np.byte): int8,
np.dtype(np.ubyte): uint8,
np.dtype(np.float16): float16,
np.dtype(np.float32): float32,
np.dtype(np.float64): float64,
}
warp_type_to_np_dtype = {
bool: np.bool_,
int8: np.int8,
int16: np.int16,
int32: np.int32,
int64: np.int64,
uint8: np.uint8,
uint16: np.uint16,
uint32: np.uint32,
uint64: np.uint64,
float16: np.float16,
float32: np.float32,
float64: np.float64,
}
def dtype_from_numpy(numpy_dtype):
"""Return the Warp dtype corresponding to a NumPy dtype."""
wp_dtype = np_dtype_to_warp_type.get(numpy_dtype)
if wp_dtype is not None:
return wp_dtype
else:
raise TypeError(f"Cannot convert {numpy_dtype} to a Warp type")
def dtype_to_numpy(warp_dtype):
"""Return the NumPy dtype corresponding to a Warp dtype."""
np_dtype = warp_type_to_np_dtype.get(warp_dtype)
if np_dtype is not None:
return np_dtype
else:
raise TypeError(f"Cannot convert {warp_dtype} to a NumPy type")
# represent a Python range iterator
class range_t:
def __init__(self):
pass
# definition just for kernel type (cannot be a parameter), see bvh.h
class bvh_query_t:
"""Object used to track state during BVH traversal."""
def __init__(self):
pass
# definition just for kernel type (cannot be a parameter), see mesh.h
class mesh_query_aabb_t:
"""Object used to track state during mesh traversal."""
def __init__(self):
pass
# definition just for kernel type (cannot be a parameter), see hash_grid.h
class hash_grid_query_t:
"""Object used to track state during neighbor traversal."""
def __init__(self):
pass
# maximum number of dimensions, must match array.h
ARRAY_MAX_DIMS = 4
LAUNCH_MAX_DIMS = 4
# must match array.h
ARRAY_TYPE_REGULAR = 0
ARRAY_TYPE_INDEXED = 1
ARRAY_TYPE_FABRIC = 2
ARRAY_TYPE_FABRIC_INDEXED = 3
# represents bounds for kernel launch (number of threads across multiple dimensions)
class launch_bounds_t(ctypes.Structure):
_fields_ = [("shape", ctypes.c_int32 * LAUNCH_MAX_DIMS), ("ndim", ctypes.c_int32), ("size", ctypes.c_size_t)]
def __init__(self, shape):
if isinstance(shape, int):
# 1d launch
self.ndim = 1
self.size = shape
self.shape[0] = shape
else:
# nd launch
self.ndim = len(shape)
self.size = 1
for i in range(self.ndim):
self.shape[i] = shape[i]
self.size = self.size * shape[i]
# initialize the remaining dims to 1
for i in range(self.ndim, LAUNCH_MAX_DIMS):
self.shape[i] = 1
class shape_t(ctypes.Structure):
_fields_ = [("dims", ctypes.c_int32 * ARRAY_MAX_DIMS)]
def __init__(self):
pass
class array_t(ctypes.Structure):
_fields_ = [
("data", ctypes.c_uint64),
("grad", ctypes.c_uint64),
("shape", ctypes.c_int32 * ARRAY_MAX_DIMS),
("strides", ctypes.c_int32 * ARRAY_MAX_DIMS),
("ndim", ctypes.c_int32),
]
def __init__(self, data=0, grad=0, ndim=0, shape=(0,), strides=(0,)):
self.data = data
self.grad = grad
self.ndim = ndim
for i in range(ndim):
self.shape[i] = shape[i]
self.strides[i] = strides[i]
# structured type description used when array_t is packed in a struct and shared via numpy structured array.
@classmethod
def numpy_dtype(cls):
return cls._numpy_dtype_
# structured value used when array_t is packed in a struct and shared via a numpy structured array
def numpy_value(self):
return (self.data, self.grad, list(self.shape), list(self.strides), self.ndim)
# NOTE: must match array_t._fields_
array_t._numpy_dtype_ = {
"names": ["data", "grad", "shape", "strides", "ndim"],
"formats": ["u8", "u8", f"{ARRAY_MAX_DIMS}i4", f"{ARRAY_MAX_DIMS}i4", "i4"],
"offsets": [
array_t.data.offset,
array_t.grad.offset,
array_t.shape.offset,
array_t.strides.offset,
array_t.ndim.offset,
],
"itemsize": ctypes.sizeof(array_t),
}
class indexedarray_t(ctypes.Structure):
_fields_ = [
("data", array_t),
("indices", ctypes.c_void_p * ARRAY_MAX_DIMS),
("shape", ctypes.c_int32 * ARRAY_MAX_DIMS),
]
def __init__(self, data, indices, shape):
if data is None:
self.data = array().__ctype__()
for i in range(ARRAY_MAX_DIMS):
self.indices[i] = ctypes.c_void_p(None)
self.shape[i] = 0
else:
self.data = data.__ctype__()
for i in range(data.ndim):
if indices[i] is not None:
self.indices[i] = ctypes.c_void_p(indices[i].ptr)
else:
self.indices[i] = ctypes.c_void_p(None)
self.shape[i] = shape[i]
def type_ctype(dtype):
if dtype == float:
return ctypes.c_float
elif dtype == int:
return ctypes.c_int32
else:
# scalar type
return dtype._type_
def type_length(dtype):
if dtype == float or dtype == int or isinstance(dtype, warp.codegen.Struct):
return 1
else:
return dtype._length_
def type_scalar_type(dtype):
return getattr(dtype, "_wp_scalar_type_", dtype)
# Cache results of type_size_in_bytes(), because the function is actually quite slow.
_type_size_cache = {
float: 4,
int: 4,
}
def type_size_in_bytes(dtype):
size = _type_size_cache.get(dtype)
if size is None:
if dtype.__module__ == "ctypes":
size = ctypes.sizeof(dtype)
elif hasattr(dtype, "_type_"):
size = getattr(dtype, "_length_", 1) * ctypes.sizeof(dtype._type_)
elif isinstance(dtype, warp.codegen.Struct):
size = ctypes.sizeof(dtype.ctype)
elif dtype == Any:
raise TypeError("A concrete type is required")
else:
raise TypeError(f"Invalid data type: {dtype}")
_type_size_cache[dtype] = size
return size
def type_to_warp(dtype):
if dtype == float:
return float32
elif dtype == int:
return int32
elif dtype == builtins.bool:
return bool
else:
return dtype
def type_typestr(dtype):
if dtype == bool:
return "?"
elif dtype == float16:
return "<f2"
elif dtype == float32:
return "<f4"
elif dtype == float64:
return "<f8"
elif dtype == int8:
return "b"
elif dtype == uint8:
return "B"
elif dtype == int16:
return "<i2"
elif dtype == uint16:
return "<u2"
elif dtype == int32:
return "<i4"
elif dtype == uint32:
return "<u4"
elif dtype == int64:
return "<i8"
elif dtype == uint64:
return "<u8"
elif isinstance(dtype, warp.codegen.Struct):
return f"|V{ctypes.sizeof(dtype.ctype)}"
elif issubclass(dtype, ctypes.Array):
return type_typestr(dtype._wp_scalar_type_)
else:
raise Exception("Unknown ctype")
# converts any known type to a human readable string, good for error messages, reporting etc
def type_repr(t):
if is_array(t):
return str(f"array(ndim={t.ndim}, dtype={t.dtype})")
if type_is_vector(t):
return str(f"vector(length={t._shape_[0]}, dtype={t._wp_scalar_type_})")
if type_is_matrix(t):
return str(f"matrix(shape=({t._shape_[0]}, {t._shape_[1]}), dtype={t._wp_scalar_type_})")
if isinstance(t, warp.codegen.Struct):
return type_repr(t.cls)
if t in scalar_types:
return t.__name__
return t.__module__ + "." + t.__qualname__
def type_is_int(t):
if t == int:
t = int32
return t in int_types
def type_is_float(t):
if t == float:
t = float32
return t in float_types
# returns True if the passed *type* is a vector
def type_is_vector(t):
return getattr(t, "_wp_generic_type_hint_", None) is Vector
# returns True if the passed *type* is a matrix
def type_is_matrix(t):
return getattr(t, "_wp_generic_type_hint_", None) is Matrix
value_types = (int, float, builtins.bool) + scalar_types
# returns true for all value types (int, float, bool, scalars, vectors, matrices)
def type_is_value(x):
return x in value_types or issubclass(x, ctypes.Array)
# equivalent of the above but for values
def is_int(x):
return type_is_int(type(x))
def is_float(x):
return type_is_float(type(x))
def is_value(x):
return type_is_value(type(x))
# returns true if the passed *instance* is one of the array types
def is_array(a):
return isinstance(a, array_types)
def scalars_equal(a, b, match_generic):
if match_generic:
if a == Any or b == Any:
return True
if a == Scalar and b in scalar_and_bool_types:
return True
if b == Scalar and a in scalar_and_bool_types:
return True
if a == Scalar and b == Scalar:
return True
if a == Float and b in float_types:
return True
if b == Float and a in float_types:
return True
if a == Float and b == Float:
return True
# convert to canonical types
if a == float:
a = float32
elif a == int:
a = int32
elif a == builtins.bool:
a = bool
if b == float:
b = float32
elif b == int:
b = int32
elif b == builtins.bool:
b = bool
return a == b
def types_equal(a, b, match_generic=False):
# convert to canonical types
if a == float:
a = float32
elif a == int:
a = int32
elif a == builtins.bool:
a = bool
if b == float:
b = float32
elif b == int:
b = int32
elif b == builtins.bool:
b = bool
if getattr(a, "_wp_generic_type_hint_", "a") is getattr(b, "_wp_generic_type_hint_", "b"):
for p1, p2 in zip(a._wp_type_params_, b._wp_type_params_):
if not scalars_equal(p1, p2, match_generic):
return False
return True
if is_array(a) and type(a) is type(b):
return True
return scalars_equal(a, b, match_generic)
def strides_from_shape(shape: Tuple, dtype):
ndims = len(shape)
strides = [None] * ndims
i = ndims - 1
strides[i] = type_size_in_bytes(dtype)
while i > 0:
strides[i - 1] = strides[i] * shape[i]
i -= 1
return tuple(strides)
def check_array_shape(shape: Tuple):
"""Checks that the size in each dimension is positive and less than 2^32."""
for dim_index, dim_size in enumerate(shape):
if dim_size < 0:
raise ValueError(f"Array shapes must be non-negative, got {dim_size} in dimension {dim_index}")
if dim_size >= 2**31:
raise ValueError(
"Array shapes must not exceed the maximum representable value of a signed 32-bit integer, "
f"got {dim_size} in dimension {dim_index}."
)
class array(Array):
# member attributes available during code-gen (e.g.: d = array.shape[0])
# (initialized when needed)
_vars = None
def __new__(cls, *args, **kwargs):
instance = super(array, cls).__new__(cls)
instance.deleter = None
return instance
def __init__(
self,
data=None,
dtype: DType = Any,
shape=None,
strides=None,
length=None,
ptr=None,
capacity=None,
device=None,
pinned=False,
copy=True,
owner=False, # deprecated - pass deleter instead
deleter=None,
ndim=None,
grad=None,
requires_grad=False,
):
"""Constructs a new Warp array object
When the ``data`` argument is a valid list, tuple, or ndarray the array will be constructed from this object's data.
For objects that are not stored sequentially in memory (e.g.: a list), then the data will first
be flattened before being transferred to the memory space given by device.
The second construction path occurs when the ``ptr`` argument is a non-zero uint64 value representing the
start address in memory where existing array data resides, e.g.: from an external or C-library. The memory
allocation should reside on the same device given by the device argument, and the user should set the length
and dtype parameter appropriately.
If neither ``data`` nor ``ptr`` are specified, the ``shape`` or ``length`` arguments are checked next.
This construction path can be used to create new uninitialized arrays, but users are encouraged to call
``wp.empty()``, ``wp.zeros()``, or ``wp.full()`` instead to create new arrays.
If none of the above arguments are specified, a simple type annotation is constructed. This is used when annotating
kernel arguments or struct members (e.g.,``arr: wp.array(dtype=float)``). In this case, only ``dtype`` and ``ndim``
are taken into account and no memory is allocated for the array.
Args:
data (Union[list, tuple, ndarray]): An object to construct the array from, can be a Tuple, List, or generally any type convertible to an np.array
dtype (Union): One of the built-in types, e.g.: :class:`warp.mat33`, if dtype is Any and data an ndarray then it will be inferred from the array data type
shape (tuple): Dimensions of the array
strides (tuple): Number of bytes in each dimension between successive elements of the array
length (int): Number of elements of the data type (deprecated, users should use `shape` argument)
ptr (uint64): Address of an external memory address to alias (data should be None)
capacity (int): Maximum size in bytes of the ptr allocation (data should be None)
device (Devicelike): Device the array lives on
copy (bool): Whether the incoming data will be copied or aliased, this is only possible when the incoming `data` already lives on the device specified and types match
owner (bool): Should the array object try to deallocate memory when it is deleted (deprecated, pass `deleter` if you wish to transfer ownership to Warp)
deleter (Callable): Function to be called when deallocating the array, taking two arguments, pointer and size
requires_grad (bool): Whether or not gradients will be tracked for this array, see :class:`warp.Tape` for details
grad (array): The gradient array to use
pinned (bool): Whether to allocate pinned host memory, which allows asynchronous host-device transfers (only applicable with device="cpu")
"""
self.ctype = None
# properties
self._requires_grad = False
self._grad = None
# __array_interface__ or __cuda_array_interface__, evaluated lazily and cached
self._array_interface = None
self.is_transposed = False
# canonicalize dtype
if dtype == int:
dtype = int32
elif dtype == float:
dtype = float32
elif dtype == builtins.bool:
dtype = bool
# convert shape to tuple (or leave shape=None if neither shape nor length were specified)
if shape is not None:
if isinstance(shape, int):
shape = (shape,)
else:
shape = tuple(shape)
if len(shape) > ARRAY_MAX_DIMS:
raise RuntimeError(
f"Failed to create array with shape {shape}, the maximum number of dimensions is {ARRAY_MAX_DIMS}"
)
elif length is not None:
# backward compatibility
shape = (length,)
# determine the construction path from the given arguments
if data is not None:
# data or ptr, not both
if ptr is not None:
raise RuntimeError("Can only construct arrays with either `data` or `ptr` arguments, not both")
self._init_from_data(data, dtype, shape, device, copy, pinned)
elif ptr is not None:
self._init_from_ptr(ptr, dtype, shape, strides, capacity, device, pinned, deleter)
elif shape is not None:
self._init_new(dtype, shape, strides, device, pinned)
else:
self._init_annotation(dtype, ndim or 1)
# initialize gradient, if needed
if self.device is not None:
if grad is not None:
# this will also check whether the gradient array is compatible
self.grad = grad
else:
# allocate gradient if needed
self._requires_grad = requires_grad
if requires_grad:
self._alloc_grad()
def _init_from_data(self, data, dtype, shape, device, copy, pinned):
if not hasattr(data, "__len__"):
raise RuntimeError(f"Data must be a sequence or array, got scalar {data}")
if hasattr(data, "__cuda_array_interface__"):
try:
# Performance note: try first, ask questions later
device = warp.context.runtime.get_device(device)
except:
warp.context.init()
raise
if device.is_cuda:
desc = data.__cuda_array_interface__
shape = desc.get("shape")
strides = desc.get("strides")
dtype = np_dtype_to_warp_type[np.dtype(desc.get("typestr"))]
ptr = desc.get("data")[0]
self._init_from_ptr(ptr, dtype, shape, strides, None, device, False, None)
# keep a ref to the source data to keep allocation alive
self._ref = data
return
else:
raise RuntimeError(
f"Trying to construct a Warp array from data argument's __cuda_array_interface__ but {device} is not CUDA-capable"
)
if hasattr(dtype, "_wp_scalar_type_"):
dtype_shape = dtype._shape_
dtype_ndim = len(dtype_shape)
scalar_dtype = dtype._wp_scalar_type_
else:
dtype_shape = ()
dtype_ndim = 0
scalar_dtype = dtype
# convert input data to ndarray (handles lists, tuples, etc.) and determine dtype
if dtype == Any:
# infer dtype from data
try:
arr = np.array(data, copy=False, ndmin=1)
except Exception as e:
raise RuntimeError(f"Failed to convert input data to an array: {e}") from e
dtype = np_dtype_to_warp_type.get(arr.dtype)
if dtype is None:
raise RuntimeError(f"Unsupported input data dtype: {arr.dtype}")
elif isinstance(dtype, warp.codegen.Struct):
if isinstance(data, np.ndarray):
# construct from numpy structured array
if data.dtype != dtype.numpy_dtype():
raise RuntimeError(
f"Invalid source data type for array of structs, expected {dtype.numpy_dtype()}, got {data.dtype}"
)
arr = data
elif isinstance(data, (list, tuple)):
# construct from a sequence of structs
try:
# convert each struct instance to its corresponding ctype
ctype_list = [v.__ctype__() for v in data]
# convert the list of ctypes to a contiguous ctypes array
ctype_arr = (dtype.ctype * len(ctype_list))(*ctype_list)
# convert to numpy
arr = np.frombuffer(ctype_arr, dtype=dtype.ctype)
except Exception as e:
raise RuntimeError(
f"Error while trying to construct Warp array from a sequence of Warp structs: {e}"
) from e
else:
raise RuntimeError(
"Invalid data argument for array of structs, expected a sequence of structs or a NumPy structured array"
)
else:
# convert input data to the given dtype
npdtype = warp_type_to_np_dtype.get(scalar_dtype)
if npdtype is None:
raise RuntimeError(
f"Failed to convert input data to an array with Warp type {warp.context.type_str(dtype)}"
)
try:
arr = np.array(data, dtype=npdtype, copy=False, ndmin=1)
except Exception as e:
raise RuntimeError(f"Failed to convert input data to an array with type {npdtype}: {e}") from e
# determine whether the input needs reshaping
target_npshape = None
if shape is not None:
target_npshape = (*shape, *dtype_shape)
elif dtype_ndim > 0:
# prune inner dimensions of length 1
while arr.ndim > 1 and arr.shape[-1] == 1:
arr = np.squeeze(arr, axis=-1)
# if the inner dims don't match exactly, check if the innermost dim is a multiple of type length
if arr.ndim < dtype_ndim or arr.shape[-dtype_ndim:] != dtype_shape:
if arr.shape[-1] == dtype._length_:
target_npshape = (*arr.shape[:-1], *dtype_shape)
elif arr.shape[-1] % dtype._length_ == 0:
target_npshape = (*arr.shape[:-1], arr.shape[-1] // dtype._length_, *dtype_shape)
else:
if dtype_ndim == 1:
raise RuntimeError(
f"The inner dimensions of the input data are not compatible with the requested vector type {warp.context.type_str(dtype)}: expected an inner dimension that is a multiple of {dtype._length_}"
)
else:
raise RuntimeError(
f"The inner dimensions of the input data are not compatible with the requested matrix type {warp.context.type_str(dtype)}: expected inner dimensions {dtype._shape_} or a multiple of {dtype._length_}"
)
if target_npshape is not None:
try:
arr = arr.reshape(target_npshape)
except Exception as e:
raise RuntimeError(
f"Failed to reshape the input data to the given shape {shape} and type {warp.context.type_str(dtype)}: {e}"
) from e
# determine final shape and strides
if dtype_ndim > 0:
# make sure the inner dims are contiguous for vector/matrix types
scalar_size = type_size_in_bytes(dtype._wp_scalar_type_)
inner_contiguous = arr.strides[-1] == scalar_size
if inner_contiguous and dtype_ndim > 1:
inner_contiguous = arr.strides[-2] == scalar_size * dtype_shape[-1]
if not inner_contiguous:
arr = np.ascontiguousarray(arr)
shape = arr.shape[:-dtype_ndim] or (1,)
strides = arr.strides[:-dtype_ndim] or (type_size_in_bytes(dtype),)
else:
shape = arr.shape or (1,)
strides = arr.strides or (type_size_in_bytes(dtype),)
try:
# Performance note: try first, ask questions later
device = warp.context.runtime.get_device(device)
except:
warp.context.init()
raise
if device.is_cpu and not copy and not pinned:
# reference numpy memory directly
self._init_from_ptr(arr.ctypes.data, dtype, shape, strides, None, device, False, None)
# keep a ref to the source array to keep allocation alive
self._ref = arr
else:
# copy data into a new array
self._init_new(dtype, shape, None, device, pinned)
src = array(
ptr=arr.ctypes.data,
dtype=dtype,
shape=shape,
strides=strides,
device="cpu",
copy=False,
)
warp.copy(self, src)
def _init_from_ptr(self, ptr, dtype, shape, strides, capacity, device, pinned, deleter):
try:
# Performance note: try first, ask questions later
device = warp.context.runtime.get_device(device)
except:
warp.context.init()
raise
check_array_shape(shape)
ndim = len(shape)
dtype_size = type_size_in_bytes(dtype)
# compute size and contiguous strides
# Performance note: we could use strides_from_shape() here, but inlining it is faster.
contiguous_strides = [None] * ndim
i = ndim - 1
contiguous_strides[i] = dtype_size
size = shape[i]
while i > 0:
contiguous_strides[i - 1] = contiguous_strides[i] * shape[i]
i -= 1
size *= shape[i]
contiguous_strides = tuple(contiguous_strides)
if strides is None:
strides = contiguous_strides
is_contiguous = True
if capacity is None:
capacity = size * dtype_size
else:
strides = tuple(strides)
is_contiguous = strides == contiguous_strides
if capacity is None:
capacity = shape[0] * strides[0]
self.dtype = dtype
self.ndim = ndim
self.size = size
self.capacity = capacity
self.shape = shape
self.strides = strides
self.ptr = ptr
self.device = device
self.pinned = pinned if device.is_cpu else False
self.is_contiguous = is_contiguous
self.deleter = deleter
def _init_new(self, dtype, shape, strides, device, pinned):
try:
# Performance note: try first, ask questions later
device = warp.context.runtime.get_device(device)
except:
warp.context.init()
raise
check_array_shape(shape)
ndim = len(shape)
dtype_size = type_size_in_bytes(dtype)
# compute size and contiguous strides
# Performance note: we could use strides_from_shape() here, but inlining it is faster.
contiguous_strides = [None] * ndim
i = ndim - 1
contiguous_strides[i] = dtype_size
size = shape[i]
while i > 0:
contiguous_strides[i - 1] = contiguous_strides[i] * shape[i]
i -= 1
size *= shape[i]
contiguous_strides = tuple(contiguous_strides)
if strides is None:
strides = contiguous_strides
is_contiguous = True
capacity = size * dtype_size
else:
strides = tuple(strides)
is_contiguous = strides == contiguous_strides
capacity = shape[0] * strides[0]
allocator = device.get_allocator(pinned=pinned)
if capacity > 0:
ptr = allocator.alloc(capacity)
else:
ptr = None
self.dtype = dtype
self.ndim = ndim
self.size = size
self.capacity = capacity
self.shape = shape
self.strides = strides
self.ptr = ptr
self.device = device
self.pinned = pinned if device.is_cpu else False
self.is_contiguous = is_contiguous
self.deleter = allocator.deleter
def _init_annotation(self, dtype, ndim):
self.dtype = dtype
self.ndim = ndim
self.size = 0
self.capacity = 0
self.shape = (0,) * ndim
self.strides = (0,) * ndim
self.ptr = None
self.device = None
self.pinned = False
self.is_contiguous = False
def __del__(self):
if self.deleter is None:
return
with self.device.context_guard:
self.deleter(self.ptr, self.capacity)
@property
def __array_interface__(self):
# raising an AttributeError here makes hasattr() return False
if self.device is None or not self.device.is_cpu:
raise AttributeError(f"__array_interface__ not supported because device is {self.device}")
if self._array_interface is None:
# get flat shape (including type shape)
if isinstance(self.dtype, warp.codegen.Struct):
# struct
arr_shape = self.shape
arr_strides = self.strides
descr = self.dtype.numpy_dtype()
elif issubclass(self.dtype, ctypes.Array):
# vector type, flatten the dimensions into one tuple
arr_shape = (*self.shape, *self.dtype._shape_)
dtype_strides = strides_from_shape(self.dtype._shape_, self.dtype._type_)
arr_strides = (*self.strides, *dtype_strides)
descr = None
else:
# scalar type
arr_shape = self.shape
arr_strides = self.strides
descr = None
self._array_interface = {
"data": (self.ptr if self.ptr is not None else 0, False),
"shape": tuple(arr_shape),
"strides": tuple(arr_strides),
"typestr": type_typestr(self.dtype),
"descr": descr, # optional description of structured array layout
"version": 3,
}
return self._array_interface
@property
def __cuda_array_interface__(self):
# raising an AttributeError here makes hasattr() return False
if self.device is None or not self.device.is_cuda:
raise AttributeError(f"__cuda_array_interface__ is not supported because device is {self.device}")
if self._array_interface is None:
# get flat shape (including type shape)
if issubclass(self.dtype, ctypes.Array):
# vector type, flatten the dimensions into one tuple
arr_shape = (*self.shape, *self.dtype._shape_)
dtype_strides = strides_from_shape(self.dtype._shape_, self.dtype._type_)
arr_strides = (*self.strides, *dtype_strides)
else:
# scalar or struct type
arr_shape = self.shape
arr_strides = self.strides
self._array_interface = {
"data": (self.ptr if self.ptr is not None else 0, False),
"shape": tuple(arr_shape),
"strides": tuple(arr_strides),
"typestr": type_typestr(self.dtype),
"version": 2,
}
return self._array_interface
def __dlpack__(self, stream=None):
# See https://data-apis.org/array-api/2022.12/API_specification/generated/array_api.array.__dlpack__.html
if self.device is None:
raise RuntimeError("Array has no device assigned")
if self.device.is_cuda and stream != -1:
if not isinstance(stream, int):
raise TypeError("DLPack stream must be an integer or None")
# assume that the array is being used on its device's current stream
array_stream = self.device.stream
# the external stream should wait for outstanding operations to complete
if stream in (None, 0, 1):
external_stream = 0
else:
external_stream = stream
# Performance note: avoid wrapping the external stream in a temporary Stream object
if external_stream != array_stream.cuda_stream:
warp.context.runtime.core.cuda_stream_wait_stream(
external_stream, array_stream.cuda_stream, array_stream.cached_event.cuda_event
)
return warp.dlpack.to_dlpack(self)
def __dlpack_device__(self):
# See https://data-apis.org/array-api/2022.12/API_specification/generated/array_api.array.__dlpack_device__.html
if self.device is None:
raise RuntimeError("Array has no device assigned")
if self.device.is_cuda:
return (warp.dlpack.DLDeviceType.kDLCUDA, self.device.ordinal)
elif self.pinned:
return (warp.dlpack.DLDeviceType.kDLCUDAHost, 0)
else:
return (warp.dlpack.DLDeviceType.kDLCPU, 0)
def __len__(self):
return self.shape[0]
def __str__(self):
if self.device is None:
# for 'empty' arrays we just return the type information, these are used in kernel function signatures
return f"array{self.dtype}"
else:
return str(self.numpy())
def __getitem__(self, key):
if isinstance(key, int):
if self.ndim == 1:
raise RuntimeError("Item indexing is not supported on wp.array objects")
key = [key]
elif isinstance(key, (slice, array)):
key = [key]
elif isinstance(key, Tuple):
contains_slice = False
contains_indices = False
for k in key:
if isinstance(k, slice):
contains_slice = True
if isinstance(k, array):
contains_indices = True
if not contains_slice and not contains_indices and len(key) == self.ndim:
raise RuntimeError("Item indexing is not supported on wp.array objects")
else:
raise RuntimeError(f"Invalid index: {key}")
new_key = []
for i in range(0, len(key)):
new_key.append(key[i])
for _i in range(len(key), self.ndim):
new_key.append(slice(None, None, None))
key = tuple(new_key)
new_shape = []
new_strides = []
ptr_offset = 0
new_dim = self.ndim
# maps dimension index to an array of indices, if given
index_arrays = {}
for idx, k in enumerate(key):
if isinstance(k, slice):
start, stop, step = k.start, k.stop, k.step
if start is None:
start = 0
if stop is None:
stop = self.shape[idx]
if step is None:
step = 1
if start < 0:
start = self.shape[idx] + start
if stop < 0:
stop = self.shape[idx] + stop
if start < 0 or start >= self.shape[idx]:
raise RuntimeError(f"Invalid indexing in slice: {start}:{stop}:{step}")
if stop < 1 or stop > self.shape[idx]:
raise RuntimeError(f"Invalid indexing in slice: {start}:{stop}:{step}")
if stop <= start:
raise RuntimeError(f"Invalid indexing in slice: {start}:{stop}:{step}")
new_shape.append(-((stop - start) // -step)) # ceil division
new_strides.append(self.strides[idx] * step)
ptr_offset += self.strides[idx] * start
elif isinstance(k, array):
# note: index array properties will be checked during indexedarray construction
index_arrays[idx] = k
# shape and strides are unchanged for this dimension
new_shape.append(self.shape[idx])
new_strides.append(self.strides[idx])
else: # is int
start = k
if start < 0:
start = self.shape[idx] + start
if start < 0 or start >= self.shape[idx]:
raise RuntimeError(f"Invalid indexing in slice: {k}")
new_dim -= 1
ptr_offset += self.strides[idx] * start
# handle grad
if self.grad is not None:
new_grad = array(
ptr=self.grad.ptr + ptr_offset if self.grad.ptr is not None else None,
dtype=self.grad.dtype,
shape=tuple(new_shape),
strides=tuple(new_strides),
device=self.grad.device,
pinned=self.grad.pinned,
)
# store back-ref to stop data being destroyed
new_grad._ref = self.grad
else:
new_grad = None
a = array(
ptr=self.ptr + ptr_offset if self.ptr is not None else None,
dtype=self.dtype,
shape=tuple(new_shape),
strides=tuple(new_strides),
device=self.device,
pinned=self.pinned,
grad=new_grad,
)
# store back-ref to stop data being destroyed
a._ref = self
if index_arrays:
indices = [None] * self.ndim
for dim, index_array in index_arrays.items():
indices[dim] = index_array
return indexedarray(a, indices)
else:
return a
# construct a C-representation of the array for passing to kernels
def __ctype__(self):
if self.ctype is None:
data = 0 if self.ptr is None else ctypes.c_uint64(self.ptr)
grad = 0 if self.grad is None or self.grad.ptr is None else ctypes.c_uint64(self.grad.ptr)
self.ctype = array_t(data=data, grad=grad, ndim=self.ndim, shape=self.shape, strides=self.strides)
return self.ctype
def __matmul__(self, other):
"""
Enables A @ B syntax for matrix multiplication
"""
if self.ndim != 2 or other.ndim != 2:
raise RuntimeError(
"A has dim = {}, B has dim = {}. If multiplying with @, A and B must have dim = 2.".format(
self.ndim, other.ndim
)
)
m = self.shape[0]
n = other.shape[1]
c = warp.zeros(shape=(m, n), dtype=self.dtype, device=self.device, requires_grad=True)
d = warp.zeros(shape=(m, n), dtype=self.dtype, device=self.device, requires_grad=True)
matmul(self, other, c, d)
return d
@property
def grad(self):
return self._grad
@grad.setter
def grad(self, grad):
if grad is None:
self._grad = None
self._requires_grad = False
else:
# make sure the given gradient array is compatible
if (
grad.dtype != self.dtype
or grad.shape != self.shape
or grad.strides != self.strides
or grad.device != self.device
):
raise ValueError("The given gradient array is incompatible")
self._grad = grad
self._requires_grad = True
# trigger re-creation of C-representation
self.ctype = None
@property
def requires_grad(self):
return self._requires_grad
@requires_grad.setter
def requires_grad(self, value: builtins.bool):
if value and self._grad is None:
self._alloc_grad()
elif not value:
self._grad = None
self._requires_grad = value
# trigger re-creation of C-representation
self.ctype = None
def _alloc_grad(self):
self._grad = warp.zeros(
dtype=self.dtype, shape=self.shape, strides=self.strides, device=self.device, pinned=self.pinned
)
# trigger re-creation of C-representation
self.ctype = None
@property
def vars(self):
# member attributes available during code-gen (e.g.: d = array.shape[0])
# Note: we use a shared dict for all array instances
if array._vars is None:
array._vars = {"shape": warp.codegen.Var("shape", shape_t)}
return array._vars
def zero_(self):
"""Zeroes-out the array entries."""
if self.is_contiguous:
# simple memset is usually faster than generic fill
self.device.memset(self.ptr, 0, self.size * type_size_in_bytes(self.dtype))
else:
self.fill_(0)
def fill_(self, value):
"""Set all array entries to `value`
args:
value: The value to set every array entry to. Must be convertible to the array's ``dtype``.
Raises:
ValueError: If `value` cannot be converted to the array's ``dtype``.
Examples:
``fill_()`` can take lists or other sequences when filling arrays of vectors or matrices.
>>> arr = wp.zeros(2, dtype=wp.mat22)
>>> arr.numpy()
array([[[0., 0.],
[0., 0.]],
<BLANKLINE>
[[0., 0.],
[0., 0.]]], dtype=float32)
>>> arr.fill_([[1, 2], [3, 4]])
>>> arr.numpy()
array([[[1., 2.],
[3., 4.]],
<BLANKLINE>
[[1., 2.],
[3., 4.]]], dtype=float32)
"""
if self.size == 0:
return
# try to convert the given value to the array dtype
try:
if isinstance(self.dtype, warp.codegen.Struct):
if isinstance(value, self.dtype.cls):
cvalue = value.__ctype__()
elif value == 0:
# allow zero-initializing structs using default constructor
cvalue = self.dtype().__ctype__()
else:
raise ValueError(
f"Invalid initializer value for struct {self.dtype.cls.__name__}, expected struct instance or 0"
)
elif issubclass(self.dtype, ctypes.Array):
# vector/matrix
cvalue = self.dtype(value)
else:
# scalar
if type(value) in warp.types.scalar_types:
value = value.value
if self.dtype == float16:
cvalue = self.dtype._type_(float_to_half_bits(value))
else:
cvalue = self.dtype._type_(value)
except Exception as e:
raise ValueError(f"Failed to convert the value to the array data type: {e}") from e
cvalue_ptr = ctypes.pointer(cvalue)
cvalue_size = ctypes.sizeof(cvalue)
# prefer using memtile for contiguous arrays, because it should be faster than generic fill
if self.is_contiguous:
self.device.memtile(self.ptr, cvalue_ptr, cvalue_size, self.size)
else:
carr = self.__ctype__()
carr_ptr = ctypes.pointer(carr)
if self.device.is_cuda:
warp.context.runtime.core.array_fill_device(
self.device.context, carr_ptr, ARRAY_TYPE_REGULAR, cvalue_ptr, cvalue_size
)
else:
warp.context.runtime.core.array_fill_host(carr_ptr, ARRAY_TYPE_REGULAR, cvalue_ptr, cvalue_size)
def assign(self, src):
"""Wraps ``src`` in an :class:`warp.array` if it is not already one and copies the contents to ``self``."""
if is_array(src):
warp.copy(self, src)
else:
warp.copy(self, array(data=src, dtype=self.dtype, copy=False, device="cpu"))
def numpy(self):
"""Converts the array to a :class:`numpy.ndarray` (aliasing memory through the array interface protocol)
If the array is on the GPU, a synchronous device-to-host copy (on the CUDA default stream) will be
automatically performed to ensure that any outstanding work is completed.
"""
if self.ptr:
# use the CUDA default stream for synchronous behaviour with other streams
with warp.ScopedStream(self.device.null_stream):
a = self.to("cpu", requires_grad=False)
# convert through __array_interface__
# Note: this handles arrays of structs using `descr`, so the result will be a structured NumPy array
return np.array(a, copy=False)
else:
# return an empty numpy array with the correct dtype and shape
if isinstance(self.dtype, warp.codegen.Struct):
npdtype = self.dtype.numpy_dtype()
npshape = self.shape
elif issubclass(self.dtype, ctypes.Array):
npdtype = warp_type_to_np_dtype[self.dtype._wp_scalar_type_]
npshape = (*self.shape, *self.dtype._shape_)
else:
npdtype = warp_type_to_np_dtype[self.dtype]
npshape = self.shape
return np.empty(npshape, dtype=npdtype)
def cptr(self):
"""Return a ctypes cast of the array address.
Notes:
#. Only CPU arrays support this method.
#. The array must be contiguous.
#. Accesses to this object are **not** bounds checked.
#. For ``float16`` types, a pointer to the internal ``uint16`` representation is returned.
"""
if not self.ptr:
return None
if self.device != "cpu" or not self.is_contiguous:
raise RuntimeError(
"Accessing array memory through a ctypes ptr is only supported for contiguous CPU arrays."
)
if isinstance(self.dtype, warp.codegen.Struct):
p = ctypes.cast(self.ptr, ctypes.POINTER(self.dtype.ctype))
else:
p = ctypes.cast(self.ptr, ctypes.POINTER(self.dtype._type_))
# store backref to the underlying array to avoid it being deallocated
p._ref = self
return p
def list(self):
"""Returns a flattened list of items in the array as a Python list."""
a = self.numpy()
if isinstance(self.dtype, warp.codegen.Struct):
# struct
a = a.flatten()
data = a.ctypes.data
stride = a.strides[0]
return [self.dtype.from_ptr(data + i * stride) for i in range(self.size)]
elif issubclass(self.dtype, ctypes.Array):
# vector/matrix - flatten, but preserve inner vector/matrix dimensions
a = a.reshape((self.size, *self.dtype._shape_))
data = a.ctypes.data
stride = a.strides[0]
return [self.dtype.from_ptr(data + i * stride) for i in range(self.size)]
else:
# scalar
return list(a.flatten())
def to(self, device, requires_grad=None):
"""Returns a Warp array with this array's data moved to the specified device, no-op if already on device."""
device = warp.get_device(device)
if self.device == device:
return self
else:
return warp.clone(self, device=device, requires_grad=requires_grad)
def flatten(self):
"""Returns a zero-copy view of the array collapsed to 1-D. Only supported for contiguous arrays."""
if self.ndim == 1:
return self
if not self.is_contiguous:
raise RuntimeError("Flattening non-contiguous arrays is unsupported.")
a = array(
ptr=self.ptr,
dtype=self.dtype,
shape=(self.size,),
device=self.device,
pinned=self.pinned,
copy=False,
grad=None if self.grad is None else self.grad.flatten(),
)
# store back-ref to stop data being destroyed
a._ref = self
return a
def reshape(self, shape):
"""Returns a reshaped array. Only supported for contiguous arrays.
Args:
shape : An int or tuple of ints specifying the shape of the returned array.
"""
if not self.is_contiguous:
raise RuntimeError("Reshaping non-contiguous arrays is unsupported.")
# convert shape to tuple
if shape is None:
raise RuntimeError("shape parameter is required.")
if isinstance(shape, int):
shape = (shape,)
elif not isinstance(shape, tuple):
shape = tuple(shape)
if len(shape) > ARRAY_MAX_DIMS:
raise RuntimeError(
f"Arrays may only have {ARRAY_MAX_DIMS} dimensions maximum, trying to create array with {len(shape)} dims."
)
# check for -1 dimension and reformat
if -1 in shape:
idx = self.size
denom = 1
minus_one_count = 0
for i, d in enumerate(shape):
if d == -1:
idx = i
minus_one_count += 1
else:
denom *= d
if minus_one_count > 1:
raise RuntimeError("Cannot infer shape if more than one index is -1.")
new_shape = list(shape)
new_shape[idx] = int(self.size / denom)
shape = tuple(new_shape)
size = 1
for d in shape:
size *= d
if size != self.size:
raise RuntimeError("Reshaped array must have the same total size as the original.")
a = array(
ptr=self.ptr,
dtype=self.dtype,
shape=shape,
strides=None,
device=self.device,
pinned=self.pinned,
copy=False,
grad=None if self.grad is None else self.grad.reshape(shape),
)
# store back-ref to stop data being destroyed
a._ref = self
return a
def view(self, dtype):
"""Returns a zero-copy view of this array's memory with a different data type.
``dtype`` must have the same byte size of the array's native ``dtype``.
"""
if type_size_in_bytes(dtype) != type_size_in_bytes(self.dtype):
raise RuntimeError("Cannot cast dtypes of unequal byte size")
# return an alias of the array memory with different type information
a = array(
ptr=self.ptr,
dtype=dtype,
shape=self.shape,
strides=self.strides,
device=self.device,
pinned=self.pinned,
copy=False,
grad=None if self.grad is None else self.grad.view(dtype),
)
a._ref = self
return a
def contiguous(self):
"""Returns a contiguous array with this array's data. No-op if array is already contiguous."""
if self.is_contiguous:
return self
a = warp.empty_like(self)
warp.copy(a, self)
return a
def transpose(self, axes=None):
"""Returns an zero-copy view of the array with axes transposed.
Note: The transpose operation will return an array with a non-contiguous access pattern.
Args:
axes (optional): Specifies the how the axes are permuted. If not specified, the axes order will be reversed.
"""
# noop if 1d array
if self.ndim == 1:
return self
if axes is None:
# reverse the order of the axes
axes = range(self.ndim)[::-1]
elif len(axes) != len(self.shape):
raise RuntimeError("Length of parameter axes must be equal in length to array shape")
shape = []
strides = []
for a in axes:
if not isinstance(a, int):
raise RuntimeError(f"axis index {a} is not of type int")
if a >= len(self.shape):
raise RuntimeError(f"axis index {a} must be smaller than the number of axes in array")
shape.append(self.shape[a])
strides.append(self.strides[a])
a = array(
ptr=self.ptr,
dtype=self.dtype,
shape=tuple(shape),
strides=tuple(strides),
device=self.device,
pinned=self.pinned,
copy=False,
grad=None if self.grad is None else self.grad.transpose(axes=axes),
)
a.is_transposed = not self.is_transposed
a._ref = self
return a
# aliases for arrays with small dimensions
def array1d(*args, **kwargs):
kwargs["ndim"] = 1
return array(*args, **kwargs)
# equivalent to calling array(..., ndim=2)
def array2d(*args, **kwargs):
kwargs["ndim"] = 2
return array(*args, **kwargs)
# equivalent to calling array(..., ndim=3)
def array3d(*args, **kwargs):
kwargs["ndim"] = 3
return array(*args, **kwargs)
# equivalent to calling array(..., ndim=4)
def array4d(*args, **kwargs):
kwargs["ndim"] = 4
return array(*args, **kwargs)
def from_ptr(ptr, length, dtype=None, shape=None, device=None):
warp.utils.warn(
"This version of wp.from_ptr() is deprecated. OmniGraph applications should use from_omni_graph_ptr() instead. In the future, wp.from_ptr() will work only with regular pointers.",
category=DeprecationWarning,
)
return array(
dtype=dtype,
length=length,
capacity=length * type_size_in_bytes(dtype),
ptr=0 if ptr == 0 else ctypes.cast(ptr, ctypes.POINTER(ctypes.c_size_t)).contents.value,
shape=shape,
device=device,
requires_grad=False,
)
# A base class for non-contiguous arrays, providing the implementation of common methods like
# contiguous(), to(), numpy(), list(), assign(), zero_(), and fill_().
class noncontiguous_array_base(Generic[T]):
def __init__(self, array_type_id):
self.type_id = array_type_id
self.is_contiguous = False
# return a contiguous copy
def contiguous(self):
a = warp.empty_like(self)
warp.copy(a, self)
return a
# copy data from one device to another, nop if already on device
def to(self, device):
device = warp.get_device(device)
if self.device == device:
return self
else:
return warp.clone(self, device=device)
# return a contiguous numpy copy
def numpy(self):
# use the CUDA default stream for synchronous behaviour with other streams
with warp.ScopedStream(self.device.null_stream):
return self.contiguous().numpy()
# returns a flattened list of items in the array as a Python list
def list(self):
# use the CUDA default stream for synchronous behaviour with other streams
with warp.ScopedStream(self.device.null_stream):
return self.contiguous().list()
# equivalent to wrapping src data in an array and copying to self
def assign(self, src):
if is_array(src):
warp.copy(self, src)
else:
warp.copy(self, array(data=src, dtype=self.dtype, copy=False, device="cpu"))
def zero_(self):
self.fill_(0)
def fill_(self, value):
if self.size == 0:
return
# try to convert the given value to the array dtype
try:
if isinstance(self.dtype, warp.codegen.Struct):
if isinstance(value, self.dtype.cls):
cvalue = value.__ctype__()
elif value == 0:
# allow zero-initializing structs using default constructor
cvalue = self.dtype().__ctype__()
else:
raise ValueError(
f"Invalid initializer value for struct {self.dtype.cls.__name__}, expected struct instance or 0"
)
elif issubclass(self.dtype, ctypes.Array):
# vector/matrix
cvalue = self.dtype(value)
else:
# scalar
if type(value) in warp.types.scalar_types:
value = value.value
if self.dtype == float16:
cvalue = self.dtype._type_(float_to_half_bits(value))
else:
cvalue = self.dtype._type_(value)
except Exception as e:
raise ValueError(f"Failed to convert the value to the array data type: {e}") from e
cvalue_ptr = ctypes.pointer(cvalue)
cvalue_size = ctypes.sizeof(cvalue)
ctype = self.__ctype__()
ctype_ptr = ctypes.pointer(ctype)
if self.device.is_cuda:
warp.context.runtime.core.array_fill_device(
self.device.context, ctype_ptr, self.type_id, cvalue_ptr, cvalue_size
)
else:
warp.context.runtime.core.array_fill_host(ctype_ptr, self.type_id, cvalue_ptr, cvalue_size)
# helper to check index array properties
def check_index_array(indices, expected_device):
if not isinstance(indices, array):
raise ValueError(f"Indices must be a Warp array, got {type(indices)}")
if indices.ndim != 1:
raise ValueError(f"Index array must be one-dimensional, got {indices.ndim}")
if indices.dtype != int32:
raise ValueError(f"Index array must use int32, got dtype {indices.dtype}")
if indices.device != expected_device:
raise ValueError(f"Index array device ({indices.device} does not match data array device ({expected_device}))")
class indexedarray(noncontiguous_array_base[T]):
# member attributes available during code-gen (e.g.: d = arr.shape[0])
# (initialized when needed)
_vars = None
def __init__(self, data: array = None, indices: Union[array, List[array]] = None, dtype=None, ndim=None):
super().__init__(ARRAY_TYPE_INDEXED)
# canonicalize types
if dtype is not None:
if dtype == int:
dtype = int32
elif dtype == float:
dtype = float32
self.data = data
self.indices = [None] * ARRAY_MAX_DIMS
if data is not None:
if not isinstance(data, array):
raise ValueError("Indexed array data must be a Warp array")
if dtype is not None and dtype != data.dtype:
raise ValueError(f"Requested dtype ({dtype}) does not match dtype of data array ({data.dtype})")
if ndim is not None and ndim != data.ndim:
raise ValueError(
f"Requested dimensionality ({ndim}) does not match dimensionality of data array ({data.ndim})"
)
self.dtype = data.dtype
self.ndim = data.ndim
self.device = data.device
self.pinned = data.pinned
# determine shape from original data shape and index counts
shape = list(data.shape)
if indices is not None:
if isinstance(indices, (list, tuple)):
if len(indices) > self.ndim:
raise ValueError(
f"Number of indices provided ({len(indices)}) exceeds number of dimensions ({self.ndim})"
)
for i in range(len(indices)):
if indices[i] is not None:
check_index_array(indices[i], data.device)
self.indices[i] = indices[i]
shape[i] = len(indices[i])
elif isinstance(indices, array):
# only a single index array was provided
check_index_array(indices, data.device)
self.indices[0] = indices
shape[0] = len(indices)
else:
raise ValueError("Indices must be a single Warp array or a list of Warp arrays")
self.shape = tuple(shape)
else:
# allow empty indexedarrays in type annotations
self.dtype = dtype
self.ndim = ndim or 1
self.device = None
self.pinned = False
self.shape = (0,) * self.ndim
# update size (num elements)
self.size = 1
for d in self.shape:
self.size *= d
def __len__(self):
return self.shape[0]
def __str__(self):
if self.device is None:
# type annotation
return f"indexedarray{self.dtype}"
else:
return str(self.numpy())
# construct a C-representation of the array for passing to kernels
def __ctype__(self):
return indexedarray_t(self.data, self.indices, self.shape)
@property
def vars(self):
# member attributes available during code-gen (e.g.: d = arr.shape[0])
# Note: we use a shared dict for all indexedarray instances
if indexedarray._vars is None:
indexedarray._vars = {"shape": warp.codegen.Var("shape", shape_t)}
return indexedarray._vars
# aliases for indexedarrays with small dimensions
def indexedarray1d(*args, **kwargs):
kwargs["ndim"] = 1
return indexedarray(*args, **kwargs)
# equivalent to calling indexedarray(..., ndim=2)
def indexedarray2d(*args, **kwargs):
kwargs["ndim"] = 2
return indexedarray(*args, **kwargs)
# equivalent to calling indexedarray(..., ndim=3)
def indexedarray3d(*args, **kwargs):
kwargs["ndim"] = 3
return indexedarray(*args, **kwargs)
# equivalent to calling indexedarray(..., ndim=4)
def indexedarray4d(*args, **kwargs):
kwargs["ndim"] = 4
return indexedarray(*args, **kwargs)
from warp.fabric import fabricarray, indexedfabricarray # noqa: E402
array_types = (array, indexedarray, fabricarray, indexedfabricarray)
def array_type_id(a):
if isinstance(a, array):
return ARRAY_TYPE_REGULAR
elif isinstance(a, indexedarray):
return ARRAY_TYPE_INDEXED
elif isinstance(a, fabricarray):
return ARRAY_TYPE_FABRIC
elif isinstance(a, indexedfabricarray):
return ARRAY_TYPE_FABRIC_INDEXED
else:
raise ValueError("Invalid array type")
class Bvh:
def __init__(self, lowers, uppers):
"""Class representing a bounding volume hierarchy.
Attributes:
id: Unique identifier for this bvh object, can be passed to kernels.
device: Device this object lives on, all buffers must live on the same device.
Args:
lowers (:class:`warp.array`): Array of lower bounds :class:`warp.vec3`
uppers (:class:`warp.array`): Array of upper bounds :class:`warp.vec3`
"""
self.id = 0
if len(lowers) != len(uppers):
raise RuntimeError("Bvh the same number of lower and upper bounds must be provided")
if lowers.device != uppers.device:
raise RuntimeError("Bvh lower and upper bounds must live on the same device")
if lowers.dtype != vec3 or not lowers.is_contiguous:
raise RuntimeError("Bvh lowers should be a contiguous array of type wp.vec3")
if uppers.dtype != vec3 or not uppers.is_contiguous:
raise RuntimeError("Bvh uppers should be a contiguous array of type wp.vec3")
self.device = lowers.device
self.lowers = lowers
self.uppers = uppers
def get_data(array):
if array:
return ctypes.c_void_p(array.ptr)
else:
return ctypes.c_void_p(0)
self.runtime = warp.context.runtime
if self.device.is_cpu:
self.id = self.runtime.core.bvh_create_host(get_data(lowers), get_data(uppers), int(len(lowers)))
else:
self.id = self.runtime.core.bvh_create_device(
self.device.context, get_data(lowers), get_data(uppers), int(len(lowers))
)
def __del__(self):
if not self.id:
return
if self.device.is_cpu:
self.runtime.core.bvh_destroy_host(self.id)
else:
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
self.runtime.core.bvh_destroy_device(self.id)
def refit(self):
"""Refit the BVH. This should be called after users modify the `lowers` and `uppers` arrays."""
if self.device.is_cpu:
self.runtime.core.bvh_refit_host(self.id)
else:
self.runtime.core.bvh_refit_device(self.id)
self.runtime.verify_cuda_device(self.device)
class Mesh:
from warp.codegen import Var
vars = {
"points": Var("points", array(dtype=vec3)),
"velocities": Var("velocities", array(dtype=vec3)),
"indices": Var("indices", array(dtype=int32)),
}
def __init__(self, points=None, indices=None, velocities=None, support_winding_number=False):
"""Class representing a triangle mesh.
Attributes:
id: Unique identifier for this mesh object, can be passed to kernels.
device: Device this object lives on, all buffers must live on the same device.
Args:
points (:class:`warp.array`): Array of vertex positions of type :class:`warp.vec3`
indices (:class:`warp.array`): Array of triangle indices of type :class:`warp.int32`, should be a 1d array with shape (num_tris, 3)
velocities (:class:`warp.array`): Array of vertex velocities of type :class:`warp.vec3` (optional)
support_winding_number (bool): If true the mesh will build additional datastructures to support `wp.mesh_query_point_sign_winding_number()` queries
"""
self.id = 0
if points.device != indices.device:
raise RuntimeError("Mesh points and indices must live on the same device")
if points.dtype != vec3 or not points.is_contiguous:
raise RuntimeError("Mesh points should be a contiguous array of type wp.vec3")
if velocities and (velocities.dtype != vec3 or not velocities.is_contiguous):
raise RuntimeError("Mesh velocities should be a contiguous array of type wp.vec3")
if indices.dtype != int32 or not indices.is_contiguous:
raise RuntimeError("Mesh indices should be a contiguous array of type wp.int32")
if indices.ndim > 1:
raise RuntimeError("Mesh indices should be a flattened 1d array of indices")
self.device = points.device
self.points = points
self.velocities = velocities
self.indices = indices
self.runtime = warp.context.runtime
if self.device.is_cpu:
self.id = self.runtime.core.mesh_create_host(
points.__ctype__(),
velocities.__ctype__() if velocities else array().__ctype__(),
indices.__ctype__(),
int(len(points)),
int(indices.size / 3),
int(support_winding_number),
)
else:
self.id = self.runtime.core.mesh_create_device(
self.device.context,
points.__ctype__(),
velocities.__ctype__() if velocities else array().__ctype__(),
indices.__ctype__(),
int(len(points)),
int(indices.size / 3),
int(support_winding_number),
)
def __del__(self):
if not self.id:
return
if self.device.is_cpu:
self.runtime.core.mesh_destroy_host(self.id)
else:
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
self.runtime.core.mesh_destroy_device(self.id)
def refit(self):
"""Refit the BVH to points. This should be called after users modify the `points` data."""
if self.device.is_cpu:
self.runtime.core.mesh_refit_host(self.id)
else:
self.runtime.core.mesh_refit_device(self.id)
self.runtime.verify_cuda_device(self.device)
class Volume:
#: Enum value to specify nearest-neighbor interpolation during sampling
CLOSEST = constant(0)
#: Enum value to specify trilinear interpolation during sampling
LINEAR = constant(1)
def __init__(self, data: array, copy: bool = True):
"""Class representing a sparse grid.
Args:
data (:class:`warp.array`): Array of bytes representing the volume in NanoVDB format
copy (bool): Whether the incoming data will be copied or aliased
"""
self.id = 0
# keep a runtime reference for orderly destruction
self.runtime = warp.context.runtime
if data is None:
return
self.device = data.device
owner = False
if self.device.is_cpu:
self.id = self.runtime.core.volume_create_host(
ctypes.cast(data.ptr, ctypes.c_void_p), data.size, copy, owner
)
else:
self.id = self.runtime.core.volume_create_device(
self.device.context, ctypes.cast(data.ptr, ctypes.c_void_p), data.size, copy, owner
)
if self.id == 0:
raise RuntimeError("Failed to create volume from input array")
def __del__(self):
if not self.id:
return
if self.device.is_cpu:
self.runtime.core.volume_destroy_host(self.id)
else:
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
self.runtime.core.volume_destroy_device(self.id)
def array(self) -> array:
"""Returns the raw memory buffer of the Volume as an array"""
buf = ctypes.c_void_p(0)
size = ctypes.c_uint64(0)
self.runtime.core.volume_get_buffer_info(self.id, ctypes.byref(buf), ctypes.byref(size))
return array(ptr=buf.value, dtype=uint8, shape=size.value, device=self.device, owner=False)
def get_tile_count(self) -> int:
"""Returns the number of tiles (NanoVDB leaf nodes) of the volume"""
voxel_count, tile_count = (
ctypes.c_uint64(0),
ctypes.c_uint32(0),
)
self.runtime.core.volume_get_tile_and_voxel_count(self.id, ctypes.byref(tile_count), ctypes.byref(voxel_count))
return tile_count.value
def get_tiles(self, out: Optional[array] = None) -> array:
"""Returns the integer coordinates of all allocated tiles for this volume.
Args:
out (:class:`warp.array`, optional): If provided, use the `out` array to store the tile coordinates, otherwise
a new array will be allocated. `out` must be a contiguous array of ``tile_count`` ``vec3i`` or ``tile_count x 3`` ``int32``
on the same device as this volume.
"""
if self.id == 0:
raise RuntimeError("Invalid Volume")
tile_count = self.get_tile_count()
if out is None:
out = warp.empty(dtype=int32, shape=(tile_count, 3), device=self.device)
elif out.device != self.device or out.shape[0] < tile_count:
raise RuntimeError(f"'out' array must an array with at least {tile_count} rows on device {self.device}")
elif not _is_contiguous_vec_like_array(out, vec_length=3, scalar_types=(int32,)):
raise RuntimeError(
"'out' must be a contiguous 1D array with type vec3i or a 2D array of type int32 with shape (N, 3) "
)
if self.device.is_cpu:
self.runtime.core.volume_get_tiles_host(self.id, out.ptr)
else:
self.runtime.core.volume_get_tiles_device(self.id, out.ptr)
return out
def get_voxel_count(self) -> int:
"""Returns the total number of allocated voxels for this volume"""
voxel_count, tile_count = (
ctypes.c_uint64(0),
ctypes.c_uint32(0),
)
self.runtime.core.volume_get_tile_and_voxel_count(self.id, ctypes.byref(tile_count), ctypes.byref(voxel_count))
return voxel_count.value
def get_voxels(self, out: Optional[array] = None) -> array:
"""Returns the integer coordinates of all allocated voxels for this volume.
Args:
out (:class:`warp.array`, optional): If provided, use the `out` array to store the voxel coordinates, otherwise
a new array will be allocated. `out` must be a contiguous array of ``voxel_count`` ``vec3i`` or ``voxel_count x 3`` ``int32``
on the same device as this volume.
"""
if self.id == 0:
raise RuntimeError("Invalid Volume")
voxel_count = self.get_voxel_count()
if out is None:
out = warp.empty(dtype=int32, shape=(voxel_count, 3), device=self.device)
elif out.device != self.device or out.shape[0] < voxel_count:
raise RuntimeError(f"'out' array must an array with at least {voxel_count} rows on device {self.device}")
elif not _is_contiguous_vec_like_array(out, vec_length=3, scalar_types=(int32,)):
raise RuntimeError(
"'out' must be a contiguous 1D array with type vec3i or a 2D array of type int32 with shape (N, 3) "
)
if self.device.is_cpu:
self.runtime.core.volume_get_voxels_host(self.id, out.ptr)
else:
self.runtime.core.volume_get_voxels_device(self.id, out.ptr)
return out
def get_voxel_size(self) -> Tuple[float, float, float]:
"""Voxel size, i.e, world coordinates of voxel's diagonal vector"""
if self.id == 0:
raise RuntimeError("Invalid Volume")
dx, dy, dz = ctypes.c_float(0), ctypes.c_float(0), ctypes.c_float(0)
self.runtime.core.volume_get_voxel_size(self.id, ctypes.byref(dx), ctypes.byref(dy), ctypes.byref(dz))
return (dx.value, dy.value, dz.value)
class GridInfo(NamedTuple):
"""Grid metadata"""
name: str
"""Grid name"""
size_in_bytes: int
"""Size of this grid's data, in bytes"""
grid_index: int
"""Index of this grid in the data buffer"""
grid_count: int
"""Total number of grids in the data buffer"""
type_str: str
"""String describing the type of the grid values"""
translation: vec3f
"""Index-to-world translation"""
transform_matrix: mat33f
"""Linear part of the index-to-world transform"""
def get_grid_info(self) -> Volume.GridInfo:
"""Returns the metadata associated with this Volume"""
grid_index = ctypes.c_uint32(0)
grid_count = ctypes.c_uint32(0)
grid_size = ctypes.c_uint64(0)
translation_buffer = (ctypes.c_float * 3)()
transform_buffer = (ctypes.c_float * 9)()
type_str_buffer = (ctypes.c_char * 16)()
name = self.runtime.core.volume_get_grid_info(
self.id,
ctypes.byref(grid_size),
ctypes.byref(grid_index),
ctypes.byref(grid_count),
translation_buffer,
transform_buffer,
type_str_buffer,
)
if name is None:
raise RuntimeError("Invalid volume")
return Volume.GridInfo(
name.decode("ascii"),
grid_size.value,
grid_index.value,
grid_count.value,
type_str_buffer.value.decode("ascii"),
vec3f.from_buffer_copy(translation_buffer),
mat33f.from_buffer_copy(transform_buffer),
)
_nvdb_type_to_dtype = {
"float": float32,
"double": float64,
"int16": int16,
"int32": int32,
"int64": int64,
"Vec3f": vec3f,
"Vec3d": vec3d,
"Half": float16,
"uint32": uint32,
"bool": bool,
"Vec4f": vec4f,
"Vec4d": vec4d,
"Vec3u8": vec3ub,
"Vec3u16": vec3us,
"uint8": uint8,
}
@property
def dtype(self) -> type:
"""Type of the Volume's values as a Warp type.
If the grid does not contain values (e.g. index grids) or if the NanoVDB type is not
representable as a Warp type, returns ``None``.
"""
return Volume._nvdb_type_to_dtype.get(self.get_grid_info().type_str, None)
_nvdb_index_types = ("Index", "OnIndex", "IndexMask", "OnIndexMask")
@property
def is_index(self) -> bool:
"""Whether this Volume contains an index grid, that is, a type of grid that does
not explicitly store values but associates each voxel to linearized index.
"""
return self.get_grid_info().type_str in Volume._nvdb_index_types
def get_feature_array_count(self) -> int:
"""Returns the number of supplemental data arrays stored alongside the grid"""
return self.runtime.core.volume_get_blind_data_count(self.id)
class FeatureArrayInfo(NamedTuple):
"""Metadata for a supplemental data array"""
name: str
"""Name of the data array"""
ptr: int
"""Memory address of the start of the array"""
value_size: int
"""Size in bytes of the array values"""
value_count: int
"""Number of values in the array"""
type_str: str
"""String describing the type of the array values"""
def get_feature_array_info(self, feature_index: int) -> Volume.FeatureArrayInfo:
"""Returns the metadata associated to the feature array at `feature_index`"""
buf = ctypes.c_void_p(0)
value_count = ctypes.c_uint64(0)
value_size = ctypes.c_uint32(0)
type_str_buffer = (ctypes.c_char * 16)()
name = self.runtime.core.volume_get_blind_data_info(
self.id,
feature_index,
ctypes.byref(buf),
ctypes.byref(value_count),
ctypes.byref(value_size),
type_str_buffer,
)
if buf.value is None:
raise RuntimeError("Invalid feature array")
return Volume.FeatureArrayInfo(
name.decode("ascii"),
buf.value,
value_size.value,
value_count.value,
type_str_buffer.value.decode("ascii"),
)
def feature_array(self, feature_index: int, dtype=None) -> array:
"""Returns one the the grid's feature data arrays as a Warp array
Args:
feature_index: Index of the supplemental data array in the grid
dtype: Type for the returned Warp array. If not provided, will be deduced from the array metadata.
"""
info = self.get_feature_array_info(feature_index)
if dtype is None:
try:
dtype = Volume._nvdb_type_to_dtype[info.type_str]
except KeyError:
# Unknown type, default to byte array
dtype = uint8
value_count = info.value_count
value_size = info.value_size
if type_size_in_bytes(dtype) == 1:
# allow requesting a byte array from any type
value_count *= value_size
value_size = 1
elif value_size == 1 and (value_count % type_size_in_bytes(dtype)) == 0:
# allow converting a byte array to any type
value_size = type_size_in_bytes(dtype)
value_count = value_count // value_size
if type_size_in_bytes(dtype) != value_size:
raise RuntimeError(f"Cannot cast feature data of size {value_size} to array dtype {type_repr(dtype)}")
return array(ptr=info.ptr, dtype=dtype, shape=value_count, device=self.device, owner=False)
@classmethod
def load_from_nvdb(cls, file_or_buffer, device=None) -> Volume:
"""Creates a Volume object from a serialized NanoVDB file or in-memory buffer.
Returns:
A ``warp.Volume`` object.
"""
try:
data = file_or_buffer.read()
except AttributeError:
data = file_or_buffer
magic, version, grid_count, codec = struct.unpack("<QIHH", data[0:16])
if magic not in (0x304244566F6E614E, 0x324244566F6E614E): # NanoVDB0 or NanoVDB2 in hex, little-endian
raise RuntimeError("NanoVDB signature not found")
if version >> 21 != 32: # checking major version
raise RuntimeError("Unsupported NanoVDB version")
# Skip over segment metadata, store total payload size
grid_data_offset = 16 # sizeof(FileHeader)
tot_file_size = 0
for _ in range(grid_count):
grid_file_size = struct.unpack("<Q", data[grid_data_offset + 8 : grid_data_offset + 16])[0]
tot_file_size += grid_file_size
grid_name_size = struct.unpack("<I", data[grid_data_offset + 136 : grid_data_offset + 140])[0]
grid_data_offset += 176 + grid_name_size # sizeof(FileMetadata) + grid name
file_end = grid_data_offset + tot_file_size
if codec == 0: # no compression
grid_data = data[grid_data_offset:file_end]
elif codec == 1: # zip compression
grid_data = bytearray()
while grid_data_offset < file_end:
chunk_size = struct.unpack("<Q", data[grid_data_offset : grid_data_offset + 8])[0]
grid_data += zlib.decompress(data[grid_data_offset + 8 :])
grid_data_offset += 8 + chunk_size
elif codec == 2: # blosc compression
try:
import blosc
except ImportError as err:
raise RuntimeError(
f"NanoVDB buffer is compressed using blosc, but Python module could not be imported: {err}"
) from err
grid_data = bytearray()
while grid_data_offset < file_end:
chunk_size = struct.unpack("<Q", data[grid_data_offset : grid_data_offset + 8])[0]
grid_data += blosc.decompress(data[grid_data_offset + 8 :])
grid_data_offset += 8 + chunk_size
else:
raise RuntimeError(f"Unsupported codec code: {codec}")
magic = struct.unpack("<Q", grid_data[0:8])[0]
if magic not in (0x304244566F6E614E, 0x314244566F6E614E): # NanoVDB0 or NanoVDB1 in hex, little-endian
raise RuntimeError("NanoVDB signature not found on grid!")
data_array = array(np.frombuffer(grid_data, dtype=np.byte), device=device)
return cls(data_array)
@classmethod
def load_from_address(cls, grid_ptr: int, buffer_size: int = 0, device=None) -> Volume:
"""
Creates a new :class:`Volume` aliasing an in-memory grid buffer.
In contrast to :meth:`load_from_nvdb` which should be used to load serialized NanoVDB grids,
here the buffer must be uncompressed and must not contain file header information.
If the passed address does not contain a NanoVDB grid, the behavior of this function is undefined.
Args:
grid_ptr: Integer address of the start of the grid buffer
buffer_size: Size of the buffer, in bytes. If not provided, the size will be assumed to be that of the single grid starting at `grid_ptr`.
device: Device of the buffer, and of the returned Volume. If not provided, the current Warp device is assumed.
Returns the newly created Volume.
"""
if not grid_ptr:
raise (RuntimeError, "Invalid grid buffer pointer")
# Check that a Volume has not already been created for this address
# (to allow this we would need to ref-count the volume descriptor)
existing_buf = ctypes.c_void_p(0)
existing_size = ctypes.c_uint64(0)
warp.context.runtime.core.volume_get_buffer_info(
grid_ptr, ctypes.byref(existing_buf), ctypes.byref(existing_size)
)
if existing_buf.value is not None:
raise RuntimeError(
"A warp Volume has already been created for this grid, aliasing it more than once is not possible."
)
data_array = array(ptr=grid_ptr, dtype=uint8, shape=buffer_size, owner=False, device=device)
return cls(data_array, copy=False)
def load_next_grid(self) -> Volume:
"""
Tries to create a new warp Volume for the next grid that is linked to by this Volume.
The existence of a next grid is deduced from the `grid_index` and `grid_count` metadata
as well as the size of this Volume's in-memory buffer.
Returns the newly created Volume, or None if there is no next grid.
"""
grid = self.get_grid_info()
array = self.array()
if grid.grid_index + 1 >= grid.grid_count or array.capacity <= grid.size_in_bytes:
return None
next_volume = Volume.load_from_address(
array.ptr + grid.size_in_bytes, buffer_size=array.capacity - grid.size_in_bytes, device=self.device
)
# makes the new Volume keep a reference to the current grid, as we're aliasing its buffer
next_volume._previous_grid = self
return next_volume
@classmethod
def load_from_numpy(
cls, ndarray: np.array, min_world=(0.0, 0.0, 0.0), voxel_size=1.0, bg_value=0.0, device=None
) -> Volume:
"""Creates a Volume object from a dense 3D NumPy array.
This function is only supported for CUDA devices.
Args:
min_world: The 3D coordinate of the lower corner of the volume.
voxel_size: The size of each voxel in spatial coordinates.
bg_value: Background value
device: The CUDA device to create the volume on, e.g.: "cuda" or "cuda:0".
Returns:
A ``warp.Volume`` object.
"""
import math
target_shape = (
math.ceil(ndarray.shape[0] / 8) * 8,
math.ceil(ndarray.shape[1] / 8) * 8,
math.ceil(ndarray.shape[2] / 8) * 8,
)
if hasattr(bg_value, "__len__"):
# vec3, assuming the numpy array is 4D
padded_array = np.array((target_shape[0], target_shape[1], target_shape[2], 3), dtype=np.single)
padded_array[:, :, :, :] = np.array(bg_value)
padded_array[0 : ndarray.shape[0], 0 : ndarray.shape[1], 0 : ndarray.shape[2], :] = ndarray
else:
padded_amount = (
math.ceil(ndarray.shape[0] / 8) * 8 - ndarray.shape[0],
math.ceil(ndarray.shape[1] / 8) * 8 - ndarray.shape[1],
math.ceil(ndarray.shape[2] / 8) * 8 - ndarray.shape[2],
)
padded_array = np.pad(
ndarray,
((0, padded_amount[0]), (0, padded_amount[1]), (0, padded_amount[2])),
mode="constant",
constant_values=bg_value,
)
shape = padded_array.shape
volume = warp.Volume.allocate(
min_world,
[
min_world[0] + (shape[0] - 1) * voxel_size,
min_world[1] + (shape[1] - 1) * voxel_size,
min_world[2] + (shape[2] - 1) * voxel_size,
],
voxel_size,
bg_value=bg_value,
points_in_world_space=True,
translation=min_world,
device=device,
)
# Populate volume
if hasattr(bg_value, "__len__"):
warp.launch(
warp.utils.copy_dense_volume_to_nano_vdb_v,
dim=(shape[0], shape[1], shape[2]),
inputs=[volume.id, warp.array(padded_array, dtype=warp.vec3, device=device)],
device=device,
)
elif isinstance(bg_value, int):
warp.launch(
warp.utils.copy_dense_volume_to_nano_vdb_i,
dim=shape,
inputs=[volume.id, warp.array(padded_array, dtype=warp.int32, device=device)],
device=device,
)
else:
warp.launch(
warp.utils.copy_dense_volume_to_nano_vdb_f,
dim=shape,
inputs=[volume.id, warp.array(padded_array, dtype=warp.float32, device=device)],
device=device,
)
return volume
@classmethod
def allocate(
cls,
min: List[int],
max: List[int],
voxel_size: float,
bg_value=0.0,
translation=(0.0, 0.0, 0.0),
points_in_world_space=False,
device=None,
) -> Volume:
"""Allocate a new Volume based on the bounding box defined by min and max.
This function is only supported for CUDA devices.
Allocate a volume that is large enough to contain voxels [min[0], min[1], min[2]] - [max[0], max[1], max[2]], inclusive.
If points_in_world_space is true, then min and max are first converted to index space with the given voxel size and
translation, and the volume is allocated with those.
The smallest unit of allocation is a dense tile of 8x8x8 voxels, the requested bounding box is rounded up to tiles, and
the resulting tiles will be available in the new volume.
Args:
min (array-like): Lower 3D coordinates of the bounding box in index space or world space, inclusive.
max (array-like): Upper 3D coordinates of the bounding box in index space or world space, inclusive.
voxel_size (float): Voxel size of the new volume.
bg_value (float or array-like): Value of unallocated voxels of the volume, also defines the volume's type, a :class:`warp.vec3` volume is created if this is `array-like`, otherwise a float volume is created
translation (array-like): translation between the index and world spaces.
device (Devicelike): The CUDA device to create the volume on, e.g.: "cuda" or "cuda:0".
"""
if points_in_world_space:
min = np.around((np.array(min, dtype=np.float32) - translation) / voxel_size)
max = np.around((np.array(max, dtype=np.float32) - translation) / voxel_size)
tile_min = np.array(min, dtype=np.int32) // 8
tile_max = np.array(max, dtype=np.int32) // 8
tiles = np.array(
[
[i, j, k]
for i in range(tile_min[0], tile_max[0] + 1)
for j in range(tile_min[1], tile_max[1] + 1)
for k in range(tile_min[2], tile_max[2] + 1)
],
dtype=np.int32,
)
tile_points = array(tiles * 8, device=device)
return cls.allocate_by_tiles(tile_points, voxel_size, bg_value, translation, device)
@classmethod
def allocate_by_tiles(
cls, tile_points: array, voxel_size: float, bg_value=0.0, translation=(0.0, 0.0, 0.0), device=None
) -> Volume:
"""Allocate a new Volume with active tiles for each point tile_points.
This function is only supported for CUDA devices.
The smallest unit of allocation is a dense tile of 8x8x8 voxels.
This is the primary method for allocating sparse volumes. It uses an array of points indicating the tiles that must be allocated.
Example use cases:
* `tile_points` can mark tiles directly in index space as in the case this method is called by `allocate`.
* `tile_points` can be a list of points used in a simulation that needs to transfer data to a volume.
Args:
tile_points (:class:`warp.array`): Array of positions that define the tiles to be allocated.
The array may use an integer scalar type (2D N-by-3 array of :class:`warp.int32` or 1D array of `warp.vec3i` values), indicating index space positions,
or a floating point scalar type (2D N-by-3 array of :class:`warp.float32` or 1D array of `warp.vec3f` values), indicating world space positions.
Repeated points per tile are allowed and will be efficiently deduplicated.
voxel_size (float): Voxel size of the new volume.
bg_value (array-like, float, int or None): Value of unallocated voxels of the volume, also defines the volume's type. A :class:`warp.vec3` volume is created if this is `array-like`, an index volume will be created if `bg_value` is ``None``.
translation (array-like): Translation between the index and world spaces.
device (Devicelike): The CUDA device to create the volume on, e.g.: "cuda" or "cuda:0".
"""
device = warp.get_device(device)
if voxel_size <= 0.0:
raise RuntimeError(f"Voxel size must be positive! Got {voxel_size}")
if not device.is_cuda:
raise RuntimeError("Only CUDA devices are supported for allocate_by_tiles")
if not _is_contiguous_vec_like_array(tile_points, vec_length=3, scalar_types=(float32, int32)):
raise RuntimeError(
"tile_points must be contiguous and either a 1D warp array of vec3f or vec3i or a 2D n-by-3 array of int32 or float32."
)
if not tile_points.device.is_cuda:
tile_points = tile_points.to(device)
volume = cls(data=None)
volume.device = device
in_world_space = type_scalar_type(tile_points.dtype) == float32
if bg_value is None:
volume.id = volume.runtime.core.volume_index_from_tiles_device(
volume.device.context,
ctypes.c_void_p(tile_points.ptr),
tile_points.shape[0],
voxel_size,
translation[0],
translation[1],
translation[2],
in_world_space,
)
elif hasattr(bg_value, "__len__"):
volume.id = volume.runtime.core.volume_v_from_tiles_device(
volume.device.context,
ctypes.c_void_p(tile_points.ptr),
tile_points.shape[0],
voxel_size,
bg_value[0],
bg_value[1],
bg_value[2],
translation[0],
translation[1],
translation[2],
in_world_space,
)
elif isinstance(bg_value, int):
volume.id = volume.runtime.core.volume_i_from_tiles_device(
volume.device.context,
ctypes.c_void_p(tile_points.ptr),
tile_points.shape[0],
voxel_size,
bg_value,
translation[0],
translation[1],
translation[2],
in_world_space,
)
else:
volume.id = volume.runtime.core.volume_f_from_tiles_device(
volume.device.context,
ctypes.c_void_p(tile_points.ptr),
tile_points.shape[0],
voxel_size,
float(bg_value),
translation[0],
translation[1],
translation[2],
in_world_space,
)
if volume.id == 0:
raise RuntimeError("Failed to create volume")
return volume
@classmethod
def allocate_by_voxels(
cls, voxel_points: array, voxel_size: float, translation=(0.0, 0.0, 0.0), device=None
) -> Volume:
"""Allocate a new Volume with active voxel for each point voxel_points.
This function creates an *index* Volume, a special kind of volume that does not any store any
explicit payload but encodes a linearized index for each active voxel, allowing to lookup and
sample data from arbitrary external arrays.
This function is only supported for CUDA devices.
Args:
voxel_points (:class:`warp.array`): Array of positions that define the voxels to be allocated.
The array may use an integer scalar type (2D N-by-3 array of :class:`warp.int32` or 1D array of `warp.vec3i` values), indicating index space positions,
or a floating point scalar type (2D N-by-3 array of :class:`warp.float32` or 1D array of `warp.vec3f` values), indicating world space positions.
Repeated points per tile are allowed and will be efficiently deduplicated.
voxel_size (float): Voxel size of the new volume.
translation (array-like): Translation between the index and world spaces.
device (Devicelike): The CUDA device to create the volume on, e.g.: "cuda" or "cuda:0".
"""
device = warp.get_device(device)
if voxel_size <= 0.0:
raise RuntimeError(f"Voxel size must be positive! Got {voxel_size}")
if not device.is_cuda:
raise RuntimeError("Only CUDA devices are supported for allocate_by_tiles")
if not (is_array(voxel_points) and voxel_points.is_contiguous):
raise RuntimeError("tile_points must be a contiguous array")
if not _is_contiguous_vec_like_array(voxel_points, vec_length=3, scalar_types=(float32, int32)):
raise RuntimeError(
"voxel_points must be contiguous and either a 1D warp array of vec3f or vec3i or a 2D n-by-3 array of int32 or float32."
)
if not voxel_points.device.is_cuda:
voxel_points = voxel_points.to(device)
volume = cls(data=None)
volume.device = device
in_world_space = type_scalar_type(voxel_points.dtype) == float32
volume.id = volume.runtime.core.volume_from_active_voxels_device(
volume.device.context,
ctypes.c_void_p(voxel_points.ptr),
voxel_points.shape[0],
voxel_size,
translation[0],
translation[1],
translation[2],
in_world_space,
)
if volume.id == 0:
raise RuntimeError("Failed to create volume")
return volume
def _is_contiguous_vec_like_array(array, vec_length: int, scalar_types: Tuple[type]) -> bool:
if not (is_array(array) and array.is_contiguous):
return False
if type_scalar_type(array.dtype) not in scalar_types:
return False
return (array.ndim == 1 and type_length(array.dtype) == vec_length) or (
array.ndim == 2 and array.shape[1] == vec_length and type_length(array.dtype) == 1
)
# definition just for kernel type (cannot be a parameter), see mesh.h
# NOTE: its layout must match the corresponding struct defined in C.
# NOTE: it needs to be defined after `indexedarray` to workaround a circular import issue.
class mesh_query_point_t:
"""Output for the mesh query point functions.
Attributes:
result (bool): Whether a point is found within the given constraints.
sign (float32): A value < 0 if query point is inside the mesh, >=0 otherwise.
Note that mesh must be watertight for this to be robust
face (int32): Index of the closest face.
u (float32): Barycentric u coordinate of the closest point.
v (float32): Barycentric v coordinate of the closest point.
See Also:
:func:`mesh_query_point`, :func:`mesh_query_point_no_sign`,
:func:`mesh_query_furthest_point_no_sign`,
:func:`mesh_query_point_sign_normal`,
and :func:`mesh_query_point_sign_winding_number`.
"""
from warp.codegen import Var
vars = {
"result": Var("result", bool),
"sign": Var("sign", float32),
"face": Var("face", int32),
"u": Var("u", float32),
"v": Var("v", float32),
}
# definition just for kernel type (cannot be a parameter), see mesh.h
# NOTE: its layout must match the corresponding struct defined in C.
class mesh_query_ray_t:
"""Output for the mesh query ray functions.
Attributes:
result (bool): Whether a hit is found within the given constraints.
sign (float32): A value > 0 if the ray hit in front of the face, returns < 0 otherwise.
face (int32): Index of the closest face.
t (float32): Distance of the closest hit along the ray.
u (float32): Barycentric u coordinate of the closest hit.
v (float32): Barycentric v coordinate of the closest hit.
normal (vec3f): Face normal.
See Also:
:func:`mesh_query_ray`.
"""
from warp.codegen import Var
vars = {
"result": Var("result", bool),
"sign": Var("sign", float32),
"face": Var("face", int32),
"t": Var("t", float32),
"u": Var("u", float32),
"v": Var("v", float32),
"normal": Var("normal", vec3),
}
def matmul(
a: array2d,
b: array2d,
c: array2d,
d: array2d,
alpha: float = 1.0,
beta: float = 0.0,
allow_tf32x3_arith: builtins.bool = False,
):
"""Computes a generic matrix-matrix multiplication (GEMM) of the form: `d = alpha * (a @ b) + beta * c`.
Args:
a (array2d): two-dimensional array containing matrix A
b (array2d): two-dimensional array containing matrix B
c (array2d): two-dimensional array containing matrix C
d (array2d): two-dimensional array to which output D is written
alpha (float): parameter alpha of GEMM
beta (float): parameter beta of GEMM
allow_tf32x3_arith (bool): whether to use CUTLASS's 3xTF32 GEMMs, which enable accuracy similar to FP32
while using Tensor Cores
"""
from warp.context import runtime
device = a.device
if b.device != device or c.device != device or d.device != device:
raise RuntimeError("Matrices A, B, C, and D must all be on the same device as the runtime device.")
if a.dtype != b.dtype or a.dtype != c.dtype or a.dtype != d.dtype:
raise RuntimeError(
"wp.matmul currently only supports operation between {A, B, C, D} matrices of the same type."
)
if (
(not a.is_contiguous and not a.is_transposed)
or (not b.is_contiguous and not b.is_transposed)
or (not c.is_contiguous)
or (not d.is_contiguous)
):
raise RuntimeError(
"wp.matmul is only valid for contiguous arrays, with the exception that A and/or B may be transposed."
)
m = a.shape[0]
n = b.shape[1]
k = a.shape[1]
if b.shape != (k, n) or c.shape != (m, n) or d.shape != (m, n):
raise RuntimeError(
"Invalid shapes for matrices: A = {} B = {} C = {} D = {}".format(a.shape, b.shape, c.shape, d.shape)
)
if runtime.tape:
runtime.tape.record_func(
backward=lambda: adj_matmul(a, b, c, a.grad, b.grad, c.grad, d.grad, alpha, beta, allow_tf32x3_arith),
arrays=[a, b, c, d],
)
# cpu fallback if no cuda devices found
if device == "cpu":
d.assign(alpha * (a.numpy() @ b.numpy()) + beta * c.numpy())
return
cc = device.arch
ret = runtime.core.cutlass_gemm(
device.context,
cc,
m,
n,
k,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(a.ptr),
ctypes.c_void_p(b.ptr),
ctypes.c_void_p(c.ptr),
ctypes.c_void_p(d.ptr),
alpha,
beta,
not a.is_transposed,
not b.is_transposed,
allow_tf32x3_arith,
1,
)
if not ret:
raise RuntimeError("matmul failed.")
def adj_matmul(
a: array2d,
b: array2d,
c: array2d,
adj_a: array2d,
adj_b: array2d,
adj_c: array2d,
adj_d: array2d,
alpha: float = 1.0,
beta: float = 0.0,
allow_tf32x3_arith: builtins.bool = False,
):
"""Computes the adjoint of a generic matrix-matrix multiplication (GEMM) of the form: `d = alpha * (a @ b) + beta * c`.
note: the adjoint of parameter alpha is not included but can be computed as `adj_alpha = np.sum(np.concatenate(np.multiply(a @ b, adj_d)))`.
note: the adjoint of parameter beta is not included but can be computed as `adj_beta = np.sum(np.concatenate(np.multiply(c, adj_d)))`.
Args:
a (array2d): two-dimensional array containing matrix A
b (array2d): two-dimensional array containing matrix B
c (array2d): two-dimensional array containing matrix C
adj_a (array2d): two-dimensional array to which the adjoint of matrix A is written
adj_b (array2d): two-dimensional array to which the adjoint of matrix B is written
adj_c (array2d): two-dimensional array to which the adjoint of matrix C is written
adj_d (array2d): two-dimensional array containing the adjoint of matrix D
alpha (float): parameter alpha of GEMM
beta (float): parameter beta of GEMM
allow_tf32x3_arith (bool): whether to use CUTLASS's 3xTF32 GEMMs, which enable accuracy similar to FP32
while using Tensor Cores
"""
from warp.context import runtime
device = a.device
if (
b.device != device
or c.device != device
or adj_a.device != device
or adj_b.device != device
or adj_c.device != device
or adj_d.device != device
):
raise RuntimeError(
"Matrices A, B, C, D, and their adjoints must all be on the same device as the runtime device."
)
if (
a.dtype != b.dtype
or a.dtype != c.dtype
or a.dtype != adj_a.dtype
or a.dtype != adj_b.dtype
or a.dtype != adj_c.dtype
or a.dtype != adj_d.dtype
):
raise RuntimeError(
"wp.adj_matmul currently only supports operation between {A, B, C, adj_D, adj_A, adj_B, adj_C} matrices of the same type."
)
if (
(not a.is_contiguous and not a.is_transposed)
or (not b.is_contiguous and not b.is_transposed)
or (not c.is_contiguous)
or (not adj_a.is_contiguous and not adj_a.is_transposed)
or (not adj_b.is_contiguous and not adj_b.is_transposed)
or (not adj_c.is_contiguous)
or (not adj_d.is_contiguous)
):
raise RuntimeError(
"wp.matmul is only valid for contiguous arrays, with the exception that A and/or B and their associated adjoints may be transposed."
)
m = a.shape[0]
n = b.shape[1]
k = a.shape[1]
if (
a.shape != (m, k)
or b.shape != (k, n)
or c.shape != (m, n)
or adj_d.shape != (m, n)
or adj_a.shape != (m, k)
or adj_b.shape != (k, n)
or adj_c.shape != (m, n)
):
raise RuntimeError(
"Invalid shapes for matrices: A = {} B = {} C = {} adj_D = {} adj_A = {} adj_B = {} adj_C = {}".format(
a.shape, b.shape, c.shape, adj_d.shape, adj_a.shape, adj_b.shape, adj_c.shape
)
)
# cpu fallback if no cuda devices found
if device == "cpu":
adj_a.assign(alpha * np.matmul(adj_d.numpy(), b.numpy().transpose()) + adj_a.numpy())
adj_b.assign(alpha * (a.numpy().transpose() @ adj_d.numpy()) + adj_b.numpy())
adj_c.assign(beta * adj_d.numpy() + adj_c.numpy())
return
cc = device.arch
# adj_a
if not a.is_transposed:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
m,
k,
n,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(adj_d.ptr),
ctypes.c_void_p(b.ptr),
ctypes.c_void_p(adj_a.ptr),
ctypes.c_void_p(adj_a.ptr),
alpha,
1.0,
True,
b.is_transposed,
allow_tf32x3_arith,
1,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
else:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
k,
m,
n,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(b.ptr),
ctypes.c_void_p(adj_d.ptr),
ctypes.c_void_p(adj_a.ptr),
ctypes.c_void_p(adj_a.ptr),
alpha,
1.0,
not b.is_transposed,
False,
allow_tf32x3_arith,
1,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
# adj_b
if not b.is_transposed:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
k,
n,
m,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(a.ptr),
ctypes.c_void_p(adj_d.ptr),
ctypes.c_void_p(adj_b.ptr),
ctypes.c_void_p(adj_b.ptr),
alpha,
1.0,
a.is_transposed,
True,
allow_tf32x3_arith,
1,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
else:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
n,
k,
m,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(adj_d.ptr),
ctypes.c_void_p(a.ptr),
ctypes.c_void_p(adj_b.ptr),
ctypes.c_void_p(adj_b.ptr),
alpha,
1.0,
False,
not a.is_transposed,
allow_tf32x3_arith,
1,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
# adj_c
warp.launch(
kernel=warp.utils.add_kernel_2d,
dim=adj_c.shape,
inputs=[adj_c, adj_d, adj_d.dtype(beta)],
device=device,
record_tape=False,
)
def batched_matmul(
a: array3d,
b: array3d,
c: array3d,
d: array3d,
alpha: float = 1.0,
beta: float = 0.0,
allow_tf32x3_arith: builtins.bool = False,
):
"""Computes a batched generic matrix-matrix multiplication (GEMM) of the form: `d = alpha * (a @ b) + beta * c`.
Args:
a (array3d): three-dimensional array containing A matrices. Overall array dimension is {batch_count, M, K}
b (array3d): three-dimensional array containing B matrices. Overall array dimension is {batch_count, K, N}
c (array3d): three-dimensional array containing C matrices. Overall array dimension is {batch_count, M, N}
d (array3d): three-dimensional array to which output D is written. Overall array dimension is {batch_count, M, N}
alpha (float): parameter alpha of GEMM
beta (float): parameter beta of GEMM
allow_tf32x3_arith (bool): whether to use CUTLASS's 3xTF32 GEMMs, which enable accuracy similar to FP32
while using Tensor Cores
"""
from warp.context import runtime
device = a.device
if b.device != device or c.device != device or d.device != device:
raise RuntimeError("Matrices A, B, C, and D must all be on the same device as the runtime device.")
if a.dtype != b.dtype or a.dtype != c.dtype or a.dtype != d.dtype:
raise RuntimeError(
"wp.batched_matmul currently only supports operation between {A, B, C, D} matrices of the same type."
)
if (
(not a.is_contiguous and not a.is_transposed)
or (not b.is_contiguous and not b.is_transposed)
or (not c.is_contiguous)
or (not d.is_contiguous)
):
raise RuntimeError(
"wp.matmul is only valid for contiguous arrays, with the exception that A and/or B may be transposed."
)
m = a.shape[1]
n = b.shape[2]
k = a.shape[2]
batch_count = a.shape[0]
if b.shape != (batch_count, k, n) or c.shape != (batch_count, m, n) or d.shape != (batch_count, m, n):
raise RuntimeError(
"Invalid shapes for matrices: A = {} B = {} C = {} D = {}".format(a.shape, b.shape, c.shape, d.shape)
)
if runtime.tape:
runtime.tape.record_func(
backward=lambda: adj_batched_matmul(
a, b, c, a.grad, b.grad, c.grad, d.grad, alpha, beta, allow_tf32x3_arith
),
arrays=[a, b, c, d],
)
# cpu fallback if no cuda devices found
if device == "cpu":
d.assign(alpha * np.matmul(a.numpy(), b.numpy()) + beta * c.numpy())
return
# handle case in which batch_count exceeds max_batch_count, which is a CUDA array size maximum
max_batch_count = 65535
iters = int(batch_count / max_batch_count)
remainder = batch_count % max_batch_count
cc = device.arch
for i in range(iters):
idx_start = i * max_batch_count
idx_end = (i + 1) * max_batch_count if i < iters - 1 else batch_count
ret = runtime.core.cutlass_gemm(
device.context,
cc,
m,
n,
k,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(a[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(b[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(c[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(d[idx_start:idx_end, :, :].ptr),
alpha,
beta,
not a.is_transposed,
not b.is_transposed,
allow_tf32x3_arith,
max_batch_count,
)
if not ret:
raise RuntimeError("Batched matmul failed.")
idx_start = iters * max_batch_count
ret = runtime.core.cutlass_gemm(
device.context,
cc,
m,
n,
k,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(a[idx_start:, :, :].ptr),
ctypes.c_void_p(b[idx_start:, :, :].ptr),
ctypes.c_void_p(c[idx_start:, :, :].ptr),
ctypes.c_void_p(d[idx_start:, :, :].ptr),
alpha,
beta,
not a.is_transposed,
not b.is_transposed,
allow_tf32x3_arith,
remainder,
)
if not ret:
raise RuntimeError("Batched matmul failed.")
def adj_batched_matmul(
a: array3d,
b: array3d,
c: array3d,
adj_a: array3d,
adj_b: array3d,
adj_c: array3d,
adj_d: array3d,
alpha: float = 1.0,
beta: float = 0.0,
allow_tf32x3_arith: builtins.bool = False,
):
"""Computes the adjoint of a batched generic matrix-matrix multiplication (GEMM) of the form: `d = alpha * (a @ b) + beta * c`.
Args:
a (array3d): three-dimensional array containing A matrices. Overall array dimension is {batch_count, M, K}
b (array3d): three-dimensional array containing B matrices. Overall array dimension is {batch_count, K, N}
c (array3d): three-dimensional array containing C matrices. Overall array dimension is {batch_count, M, N}
adj_a (array3d): three-dimensional array to which the adjoints of A matrices are written. Overall array dimension is {batch_count, M, K}
adj_b (array3d): three-dimensional array to which the adjoints of B matrices are written. Overall array dimension is {batch_count, K, N}
adj_c (array3d): three-dimensional array to which the adjoints of C matrices are written. Overall array dimension is {batch_count, M, N}
adj_d (array3d): three-dimensional array containing adjoints of D matrices. Overall array dimension is {batch_count, M, N}
alpha (float): parameter alpha of GEMM
beta (float): parameter beta of GEMM
allow_tf32x3_arith (bool): whether to use CUTLASS's 3xTF32 GEMMs, which enable accuracy similar to FP32
while using Tensor Cores
"""
from warp.context import runtime
device = a.device
if (
b.device != device
or c.device != device
or adj_a.device != device
or adj_b.device != device
or adj_c.device != device
or adj_d.device != device
):
raise RuntimeError(
"Matrices A, B, C, D, and their adjoints must all be on the same device as the runtime device."
)
if (
a.dtype != b.dtype
or a.dtype != c.dtype
or a.dtype != adj_a.dtype
or a.dtype != adj_b.dtype
or a.dtype != adj_c.dtype
or a.dtype != adj_d.dtype
):
raise RuntimeError(
"wp.adj_batched_matmul currently only supports operation between {A, B, C, adj_D, adj_A, adj_B, adj_C} matrices of the same type."
)
m = a.shape[1]
n = b.shape[2]
k = a.shape[2]
batch_count = a.shape[0]
if (
b.shape != (batch_count, k, n)
or c.shape != (batch_count, m, n)
or adj_d.shape != (batch_count, m, n)
or adj_a.shape != (batch_count, m, k)
or adj_b.shape != (batch_count, k, n)
or adj_c.shape != (batch_count, m, n)
):
raise RuntimeError(
"Invalid shapes for matrices: A = {} B = {} C = {} adj_D = {} adj_A = {} adj_B = {} adj_C = {}".format(
a.shape, b.shape, c.shape, adj_d.shape, adj_a.shape, adj_b.shape, adj_c.shape
)
)
if (
(not a.is_contiguous and not a.is_transposed)
or (not b.is_contiguous and not b.is_transposed)
or (not c.is_contiguous)
or (not adj_a.is_contiguous and not adj_a.is_transposed)
or (not adj_b.is_contiguous and not adj_b.is_transposed)
or (not adj_c.is_contiguous)
or (not adj_d.is_contiguous)
):
raise RuntimeError(
"wp.matmul is only valid for contiguous arrays, with the exception that A and/or B and their associated adjoints may be transposed."
)
# cpu fallback if no cuda devices found
if device == "cpu":
adj_a.assign(alpha * np.matmul(adj_d.numpy(), b.numpy().transpose((0, 2, 1))) + adj_a.numpy())
adj_b.assign(alpha * np.matmul(a.numpy().transpose((0, 2, 1)), adj_d.numpy()) + adj_b.numpy())
adj_c.assign(beta * adj_d.numpy() + adj_c.numpy())
return
# handle case in which batch_count exceeds max_batch_count, which is a CUDA array size maximum
max_batch_count = 65535
iters = int(batch_count / max_batch_count)
remainder = batch_count % max_batch_count
cc = device.arch
for i in range(iters):
idx_start = i * max_batch_count
idx_end = (i + 1) * max_batch_count if i < iters - 1 else batch_count
# adj_a
if not a.is_transposed:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
m,
k,
n,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(adj_d[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(b[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:idx_end, :, :].ptr),
alpha,
1.0,
True,
b.is_transposed,
allow_tf32x3_arith,
max_batch_count,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
else:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
k,
m,
n,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(b[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_d[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:idx_end, :, :].ptr),
alpha,
1.0,
not b.is_transposed,
False,
allow_tf32x3_arith,
max_batch_count,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
# adj_b
if not b.is_transposed:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
k,
n,
m,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(a[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_d[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:idx_end, :, :].ptr),
alpha,
1.0,
a.is_transposed,
True,
allow_tf32x3_arith,
max_batch_count,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
else:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
n,
k,
m,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(adj_d[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(a[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:idx_end, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:idx_end, :, :].ptr),
alpha,
1.0,
False,
not a.is_transposed,
allow_tf32x3_arith,
max_batch_count,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
idx_start = iters * max_batch_count
# adj_a
if not a.is_transposed:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
m,
k,
n,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(adj_d[idx_start:, :, :].ptr),
ctypes.c_void_p(b[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:, :, :].ptr),
alpha,
1.0,
True,
b.is_transposed,
allow_tf32x3_arith,
remainder,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
else:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
k,
m,
n,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(b[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_d[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_a[idx_start:, :, :].ptr),
alpha,
1.0,
not b.is_transposed,
False,
allow_tf32x3_arith,
remainder,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
# adj_b
if not b.is_transposed:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
k,
n,
m,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(a[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_d[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:, :, :].ptr),
alpha,
1.0,
a.is_transposed,
True,
allow_tf32x3_arith,
remainder,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
else:
ret = runtime.core.cutlass_gemm(
device.context,
cc,
n,
k,
m,
type_typestr(a.dtype).encode(),
ctypes.c_void_p(adj_d[idx_start:, :, :].ptr),
ctypes.c_void_p(a[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:, :, :].ptr),
ctypes.c_void_p(adj_b[idx_start:, :, :].ptr),
alpha,
1.0,
False,
not a.is_transposed,
allow_tf32x3_arith,
remainder,
)
if not ret:
raise RuntimeError("adj_matmul failed.")
# adj_c
warp.launch(
kernel=warp.utils.add_kernel_3d,
dim=adj_c.shape,
inputs=[adj_c, adj_d, adj_d.dtype(beta)],
device=device,
record_tape=False,
)
class HashGrid:
def __init__(self, dim_x, dim_y, dim_z, device=None):
"""Class representing a hash grid object for accelerated point queries.
Attributes:
id: Unique identifier for this mesh object, can be passed to kernels.
device: Device this object lives on, all buffers must live on the same device.
Args:
dim_x (int): Number of cells in x-axis
dim_y (int): Number of cells in y-axis
dim_z (int): Number of cells in z-axis
"""
self.id = 0
self.runtime = warp.context.runtime
self.device = self.runtime.get_device(device)
if self.device.is_cpu:
self.id = self.runtime.core.hash_grid_create_host(dim_x, dim_y, dim_z)
else:
self.id = self.runtime.core.hash_grid_create_device(self.device.context, dim_x, dim_y, dim_z)
# indicates whether the grid data has been reserved for use by a kernel
self.reserved = False
def build(self, points, radius):
"""Updates the hash grid data structure.
This method rebuilds the underlying datastructure and should be called any time the set
of points changes.
Args:
points (:class:`warp.array`): Array of points of type :class:`warp.vec3`
radius (float): The cell size to use for bucketing points, cells are cubes with edges of this width.
For best performance the radius used to construct the grid should match closely to
the radius used when performing queries.
"""
if not warp.types.types_equal(points.dtype, warp.vec3):
raise TypeError("Hash grid points should have type warp.vec3")
if points.ndim > 1:
points = points.contiguous().flatten()
if self.device.is_cpu:
self.runtime.core.hash_grid_update_host(self.id, radius, ctypes.byref(points.__ctype__()))
else:
self.runtime.core.hash_grid_update_device(self.id, radius, ctypes.byref(points.__ctype__()))
self.reserved = True
def reserve(self, num_points):
if self.device.is_cpu:
self.runtime.core.hash_grid_reserve_host(self.id, num_points)
else:
self.runtime.core.hash_grid_reserve_device(self.id, num_points)
self.reserved = True
def __del__(self):
if not self.id:
return
if self.device.is_cpu:
self.runtime.core.hash_grid_destroy_host(self.id)
else:
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
self.runtime.core.hash_grid_destroy_device(self.id)
class MarchingCubes:
def __init__(self, nx: int, ny: int, nz: int, max_verts: int, max_tris: int, device=None):
"""CUDA-based Marching Cubes algorithm to extract a 2D surface mesh from a 3D volume.
Attributes:
id: Unique identifier for this object.
verts (:class:`warp.array`): Array of vertex positions of type :class:`warp.vec3f`
for the output surface mesh.
This is populated after running :func:`surface`.
indices (:class:`warp.array`): Array containing indices of type :class:`warp.int32`
defining triangles for the output surface mesh.
This is populated after running :func:`surface`.
Each set of three consecutive integers in the array represents a single triangle,
in which each integer is an index referring to a vertex in the :attr:`verts` array.
Args:
nx: Number of cubes in the x-direction.
ny: Number of cubes in the y-direction.
nz: Number of cubes in the z-direction.
max_verts: Maximum expected number of vertices (used for array preallocation).
max_tris: Maximum expected number of triangles (used for array preallocation).
device (Devicelike): CUDA device on which to run marching cubes and allocate memory.
Raises:
RuntimeError: ``device`` not a CUDA device.
.. note::
The shape of the marching cubes should match the shape of the scalar field being surfaced.
"""
self.id = 0
self.runtime = warp.context.runtime
self.device = self.runtime.get_device(device)
if not self.device.is_cuda:
raise RuntimeError("Only CUDA devices are supported for marching cubes")
self.nx = nx
self.ny = ny
self.nz = nz
self.max_verts = max_verts
self.max_tris = max_tris
# bindings to warp.so
self.alloc = self.runtime.core.marching_cubes_create_device
self.alloc.argtypes = [ctypes.c_void_p]
self.alloc.restype = ctypes.c_uint64
self.free = self.runtime.core.marching_cubes_destroy_device
from warp.context import zeros
self.verts = zeros(max_verts, dtype=vec3, device=self.device)
self.indices = zeros(max_tris * 3, dtype=warp.int32, device=self.device)
# alloc surfacer
self.id = ctypes.c_uint64(self.alloc(self.device.context))
def __del__(self):
if not self.id:
return
# use CUDA context guard to avoid side effects during garbage collection
with self.device.context_guard:
# destroy surfacer
self.free(self.id)
def resize(self, nx: int, ny: int, nz: int, max_verts: int, max_tris: int) -> None:
"""Update the expected input and maximum output sizes for the marching cubes calculation.
This function has no immediate effect on the underlying buffers.
The new values take effect on the next :func:`surface` call.
Args:
nx: Number of cubes in the x-direction.
ny: Number of cubes in the y-direction.
nz: Number of cubes in the z-direction.
max_verts: Maximum expected number of vertices (used for array preallocation).
max_tris: Maximum expected number of triangles (used for array preallocation).
"""
# actual allocations will be resized on next call to surface()
self.nx = nx
self.ny = ny
self.nz = nz
self.max_verts = max_verts
self.max_tris = max_tris
def surface(self, field: array(dtype=float, ndim=3), threshold: float) -> None:
"""Compute a 2D surface mesh of a given isosurface from a 3D scalar field.
The triangles and vertices defining the output mesh are written to the
:attr:`indices` and :attr:`verts` arrays.
Args:
field: Scalar field from which to generate a mesh.
threshold: Target isosurface value.
Raises:
ValueError: ``field`` is not a 3D array.
ValueError: Marching cubes shape does not match the shape of ``field``.
RuntimeError: :attr:`max_verts` and/or :attr:`max_tris` might be too small to hold the surface mesh.
"""
# WP_API int marching_cubes_surface_host(const float* field, int nx, int ny, int nz, float threshold, wp::vec3* verts, int* triangles, int max_verts, int max_tris, int* out_num_verts, int* out_num_tris);
num_verts = ctypes.c_int(0)
num_tris = ctypes.c_int(0)
self.runtime.core.marching_cubes_surface_device.restype = ctypes.c_int
# For now we require that input field shape matches nx, ny, nz
if field.ndim != 3:
raise ValueError(f"Input field must be a three-dimensional array (got {field.ndim}).")
if field.shape[0] != self.nx or field.shape[1] != self.ny or field.shape[2] != self.nz:
raise ValueError(
f"Marching cubes shape ({self.nx}, {self.ny}, {self.nz}) does not match the "
f"input array shape {field.shape}."
)
error = self.runtime.core.marching_cubes_surface_device(
self.id,
ctypes.cast(field.ptr, ctypes.c_void_p),
self.nx,
self.ny,
self.nz,
ctypes.c_float(threshold),
ctypes.cast(self.verts.ptr, ctypes.c_void_p),
ctypes.cast(self.indices.ptr, ctypes.c_void_p),
self.max_verts,
self.max_tris,
ctypes.c_void_p(ctypes.addressof(num_verts)),
ctypes.c_void_p(ctypes.addressof(num_tris)),
)
if error:
raise RuntimeError(
f"Buffers may not be large enough, marching cubes required at least {num_verts} vertices, and {num_tris} triangles."
)
# resize the geometry arrays
self.verts.shape = (num_verts.value,)
self.indices.shape = (num_tris.value * 3,)
self.verts.size = num_verts.value
self.indices.size = num_tris.value * 3
generic_types = (Any, Scalar, Float, Int)
def type_is_generic(t):
if t in generic_types:
return True
if is_array(t):
return type_is_generic(t.dtype)
if hasattr(t, "_wp_scalar_type_"):
# vector/matrix type, check if dtype is generic
if type_is_generic(t._wp_scalar_type_):
return True
# check if any dimension is generic
for d in t._shape_:
if d == 0:
return True
return False
def type_is_generic_scalar(t):
return t in (Scalar, Float, Int)
def type_matches_template(arg_type, template_type):
"""Check if an argument type matches a template.
This function is used to test whether the arguments passed to a generic @wp.kernel or @wp.func
match the template type annotations. The template_type can be generic, but the arg_type must be concrete.
"""
# canonicalize types
arg_type = type_to_warp(arg_type)
template_type = type_to_warp(template_type)
# arg type must be concrete
if type_is_generic(arg_type):
return False
# if template type is not generic, the argument type must match exactly
if not type_is_generic(template_type):
return types_equal(arg_type, template_type)
# template type is generic, check that the argument type matches
if template_type == Any:
return True
elif is_array(template_type):
# ensure the argument type is a non-generic array with matching dtype and dimensionality
if type(arg_type) is not type(template_type):
return False
if not type_matches_template(arg_type.dtype, template_type.dtype):
return False
if arg_type.ndim != template_type.ndim:
return False
elif template_type == Float:
return arg_type in float_types
elif template_type == Int:
return arg_type in int_types
elif template_type == Scalar:
return arg_type in scalar_types
elif hasattr(template_type, "_wp_scalar_type_"):
# vector/matrix type
if not hasattr(arg_type, "_wp_scalar_type_"):
return False
if not type_matches_template(arg_type._wp_scalar_type_, template_type._wp_scalar_type_):
return False
ndim = len(template_type._shape_)
if len(arg_type._shape_) != ndim:
return False
# for any non-generic dimensions, make sure they match
for i in range(ndim):
if template_type._shape_[i] != 0 and arg_type._shape_[i] != template_type._shape_[i]:
return False
return True
def infer_argument_types(args, template_types, arg_names=None):
"""Resolve argument types with the given list of template types."""
if len(args) != len(template_types):
raise RuntimeError("Number of arguments must match number of template types.")
arg_types = []
for i in range(len(args)):
arg = args[i]
arg_type = type(arg)
arg_name = arg_names[i] if arg_names else str(i)
if arg_type in warp.types.array_types:
arg_types.append(arg_type(dtype=arg.dtype, ndim=arg.ndim))
elif arg_type in warp.types.scalar_and_bool_types:
arg_types.append(arg_type)
elif arg_type in (int, float):
# canonicalize type
arg_types.append(warp.types.type_to_warp(arg_type))
elif hasattr(arg_type, "_wp_scalar_type_"):
# vector/matrix type
arg_types.append(arg_type)
elif issubclass(arg_type, warp.codegen.StructInstance):
# a struct
arg_types.append(arg._cls)
# elif arg_type in [warp.types.launch_bounds_t, warp.types.shape_t, warp.types.range_t]:
# arg_types.append(arg_type)
# elif arg_type in [warp.hash_grid_query_t, warp.mesh_query_aabb_t, warp.mesh_query_point_t, warp.mesh_query_ray_t, warp.bvh_query_t]:
# arg_types.append(arg_type)
elif arg is None:
# allow passing None for arrays
t = template_types[i]
if warp.types.is_array(t):
arg_types.append(type(t)(dtype=t.dtype, ndim=t.ndim))
else:
raise TypeError(f"Unable to infer the type of argument '{arg_name}', got None")
else:
# TODO: attempt to figure out if it's a vector/matrix type given as a numpy array, list, etc.
raise TypeError(f"Unable to infer the type of argument '{arg_name}', got {arg_type}")
return arg_types
simple_type_codes = {
int: "i4",
float: "f4",
builtins.bool: "b",
bool: "b",
str: "str", # accepted by print()
int8: "i1",
int16: "i2",
int32: "i4",
int64: "i8",
uint8: "u1",
uint16: "u2",
uint32: "u4",
uint64: "u8",
float16: "f2",
float32: "f4",
float64: "f8",
shape_t: "sh",
range_t: "rg",
launch_bounds_t: "lb",
hash_grid_query_t: "hgq",
mesh_query_aabb_t: "mqa",
mesh_query_point_t: "mqp",
mesh_query_ray_t: "mqr",
bvh_query_t: "bvhq",
}
def get_type_code(arg_type):
if arg_type == Any:
# special case for generics
# note: since Python 3.11 Any is a type, so we check for it first
return "?"
elif isinstance(arg_type, type):
if hasattr(arg_type, "_wp_scalar_type_"):
# vector/matrix type
dtype_code = get_type_code(arg_type._wp_scalar_type_)
# check for "special" vector/matrix subtypes
if hasattr(arg_type, "_wp_generic_type_str_"):
type_str = arg_type._wp_generic_type_str_
if type_str == "quat_t":
return f"q{dtype_code}"
elif type_str == "transform_t":
return f"t{dtype_code}"
# elif type_str == "spatial_vector_t":
# return f"sv{dtype_code}"
# elif type_str == "spatial_matrix_t":
# return f"sm{dtype_code}"
# generic vector/matrix
ndim = len(arg_type._shape_)
if ndim == 1:
dim_code = "?" if arg_type._shape_[0] == 0 else str(arg_type._shape_[0])
return f"v{dim_code}{dtype_code}"
elif ndim == 2:
dim_code0 = "?" if arg_type._shape_[0] == 0 else str(arg_type._shape_[0])
dim_code1 = "?" if arg_type._shape_[1] == 0 else str(arg_type._shape_[1])
return f"m{dim_code0}{dim_code1}{dtype_code}"
else:
raise TypeError("Invalid vector/matrix dimensionality")
else:
# simple type
type_code = simple_type_codes.get(arg_type)
if type_code is not None:
return type_code
else:
raise TypeError(f"Unrecognized type '{arg_type}'")
elif isinstance(arg_type, array):
return f"a{arg_type.ndim}{get_type_code(arg_type.dtype)}"
elif isinstance(arg_type, indexedarray):
return f"ia{arg_type.ndim}{get_type_code(arg_type.dtype)}"
elif isinstance(arg_type, fabricarray):
return f"fa{arg_type.ndim}{get_type_code(arg_type.dtype)}"
elif isinstance(arg_type, indexedfabricarray):
return f"ifa{arg_type.ndim}{get_type_code(arg_type.dtype)}"
elif isinstance(arg_type, warp.codegen.Struct):
return warp.codegen.make_full_qualified_name(arg_type.cls)
elif arg_type == Scalar:
# generic scalar type
return "s?"
elif arg_type == Float:
# generic float
return "f?"
elif arg_type == Int:
# generic int
return "i?"
elif isinstance(arg_type, Callable):
# TODO: elaborate on Callable type?
return "c"
else:
raise TypeError(f"Unrecognized type '{arg_type}'")
def get_signature(arg_types, func_name=None, arg_names=None):
type_codes = []
for i, arg_type in enumerate(arg_types):
try:
type_codes.append(get_type_code(arg_type))
except Exception as e:
if arg_names is not None:
arg_str = f"'{arg_names[i]}'"
else:
arg_str = str(i + 1)
if func_name is not None:
func_str = f" of function {func_name}"
else:
func_str = ""
raise RuntimeError(f"Failed to determine type code for argument {arg_str}{func_str}: {e}") from e
return "_".join(type_codes)
def is_generic_signature(sig):
return "?" in sig
| 169,652 | Python | 33.328814 | 252 | 0.560017 |
NVIDIA/warp/warp/__init__.pyi | from .stubs import *
| 21 | unknown | 9.999995 | 20 | 0.714286 |
NVIDIA/warp/warp/build_dll.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 os
import platform
import subprocess
import sys
from warp.utils import ScopedTimer
verbose_cmd = True # print command lines before executing them
# returns a canonical machine architecture string
# - "x86_64" for x86-64, aka. AMD64, aka. x64
# - "aarch64" for AArch64, aka. ARM64
def machine_architecture() -> str:
machine = platform.machine()
if machine == "x86_64" or machine == "AMD64":
return "x86_64"
if machine == "aarch64" or machine == "arm64":
return "aarch64"
raise RuntimeError(f"Unrecognized machine architecture {machine}")
def run_cmd(cmd):
if verbose_cmd:
print(cmd)
try:
return subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
if e.stdout:
print(e.stdout.decode())
if e.stderr:
print(e.stderr.decode())
raise (e)
# cut-down version of vcvars64.bat that allows using
# custom toolchain locations, returns the compiler program path
def set_msvc_env(msvc_path, sdk_path):
if "INCLUDE" not in os.environ:
os.environ["INCLUDE"] = ""
if "LIB" not in os.environ:
os.environ["LIB"] = ""
msvc_path = os.path.abspath(msvc_path)
sdk_path = os.path.abspath(sdk_path)
os.environ["INCLUDE"] += os.pathsep + os.path.join(msvc_path, "include")
os.environ["INCLUDE"] += os.pathsep + os.path.join(sdk_path, "include/winrt")
os.environ["INCLUDE"] += os.pathsep + os.path.join(sdk_path, "include/um")
os.environ["INCLUDE"] += os.pathsep + os.path.join(sdk_path, "include/ucrt")
os.environ["INCLUDE"] += os.pathsep + os.path.join(sdk_path, "include/shared")
os.environ["LIB"] += os.pathsep + os.path.join(msvc_path, "lib/x64")
os.environ["LIB"] += os.pathsep + os.path.join(sdk_path, "lib/ucrt/x64")
os.environ["LIB"] += os.pathsep + os.path.join(sdk_path, "lib/um/x64")
os.environ["PATH"] += os.pathsep + os.path.join(msvc_path, "bin/HostX64/x64")
os.environ["PATH"] += os.pathsep + os.path.join(sdk_path, "bin/x64")
return os.path.join(msvc_path, "bin", "HostX64", "x64", "cl.exe")
def find_host_compiler():
if os.name == "nt":
# try and find an installed host compiler (msvc)
# runs vcvars and copies back the build environment
vswhere_path = r"%ProgramFiles(x86)%/Microsoft Visual Studio/Installer/vswhere.exe"
vswhere_path = os.path.expandvars(vswhere_path)
if not os.path.exists(vswhere_path):
return ""
vs_path = run_cmd(f'"{vswhere_path}" -latest -property installationPath').decode().rstrip()
vsvars_path = os.path.join(vs_path, "VC\\Auxiliary\\Build\\vcvars64.bat")
output = run_cmd(f'"{vsvars_path}" && set').decode()
for line in output.splitlines():
pair = line.split("=", 1)
if len(pair) >= 2:
os.environ[pair[0]] = pair[1]
cl_path = run_cmd("where cl.exe").decode("utf-8").rstrip()
cl_version = os.environ["VCToolsVersion"].split(".")
# ensure at least VS2019 version, see list of MSVC versions here https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B
cl_required_major = 14
cl_required_minor = 29
if (
(int(cl_version[0]) < cl_required_major)
or (int(cl_version[0]) == cl_required_major)
and int(cl_version[1]) < cl_required_minor
):
print(
f"Warp: MSVC found but compiler version too old, found {cl_version[0]}.{cl_version[1]}, but must be {cl_required_major}.{cl_required_minor} or higher, kernel host compilation will be disabled."
)
return ""
return cl_path
else:
# try and find g++
return run_cmd("which g++").decode()
def get_cuda_toolkit_version(cuda_home):
try:
# the toolkit version can be obtained by running "nvcc --version"
nvcc_path = os.path.join(cuda_home, "bin", "nvcc")
nvcc_version_output = subprocess.check_output([nvcc_path, "--version"]).decode("utf-8")
# search for release substring (e.g., "release 11.5")
import re
m = re.search(r"(?<=release )\d+\.\d+", nvcc_version_output)
if m is not None:
return tuple(int(x) for x in m.group(0).split("."))
else:
raise Exception("Failed to parse NVCC output")
except Exception as e:
print(f"Failed to determine CUDA Toolkit version: {e}")
def quote(path):
return '"' + path + '"'
def build_dll_for_arch(args, dll_path, cpp_paths, cu_path, libs, arch, mode=None):
mode = args.mode if (mode is None) else mode
cuda_home = args.cuda_path
cuda_cmd = None
if args.quick:
cutlass_includes = ""
cutlass_enabled = "WP_ENABLE_CUTLASS=0"
else:
cutlass_home = "warp/native/cutlass"
cutlass_includes = f'-I"{cutlass_home}/include" -I"{cutlass_home}/tools/util/include"'
cutlass_enabled = "WP_ENABLE_CUTLASS=1"
if args.quick or cu_path is None:
cuda_compat_enabled = "WP_ENABLE_CUDA_COMPATIBILITY=0"
else:
cuda_compat_enabled = "WP_ENABLE_CUDA_COMPATIBILITY=1"
import pathlib
warp_home_path = pathlib.Path(__file__).parent
warp_home = warp_home_path.resolve()
nanovdb_home = warp_home_path.parent / "_build/host-deps/nanovdb/include"
# output stale, rebuild
if args.verbose:
print(f"Building {dll_path}")
native_dir = os.path.join(warp_home, "native")
if cu_path:
# check CUDA Toolkit version
min_ctk_version = (11, 5)
ctk_version = get_cuda_toolkit_version(cuda_home) or min_ctk_version
if ctk_version < min_ctk_version:
raise Exception(
f"CUDA Toolkit version {min_ctk_version[0]}.{min_ctk_version[1]}+ is required (found {ctk_version[0]}.{ctk_version[1]} in {cuda_home})"
)
gencode_opts = []
if args.quick:
# minimum supported architectures (PTX)
gencode_opts += ["-gencode=arch=compute_52,code=compute_52", "-gencode=arch=compute_75,code=compute_75"]
else:
# generate code for all supported architectures
gencode_opts += [
# SASS for supported desktop/datacenter architectures
"-gencode=arch=compute_52,code=sm_52", # Maxwell
"-gencode=arch=compute_60,code=sm_60", # Pascal
"-gencode=arch=compute_61,code=sm_61",
"-gencode=arch=compute_70,code=sm_70", # Volta
"-gencode=arch=compute_75,code=sm_75", # Turing
"-gencode=arch=compute_80,code=sm_80", # Ampere
"-gencode=arch=compute_86,code=sm_86",
]
if arch == "aarch64" and sys.platform == "linux":
gencode_opts += [
# SASS for supported mobile architectures (e.g. Tegra/Jetson)
"-gencode=arch=compute_53,code=sm_53", # X1
"-gencode=arch=compute_62,code=sm_62", # X2
"-gencode=arch=compute_72,code=sm_72", # Xavier
"-gencode=arch=compute_87,code=sm_87", # Orin
]
# support for Ada and Hopper is available with CUDA Toolkit 11.8+
if ctk_version >= (11, 8):
gencode_opts += [
"-gencode=arch=compute_89,code=sm_89", # Ada
"-gencode=arch=compute_90,code=sm_90", # Hopper
# PTX for future hardware
"-gencode=arch=compute_90,code=compute_90",
]
else:
gencode_opts += [
# PTX for future hardware
"-gencode=arch=compute_86,code=compute_86",
]
nvcc_opts = gencode_opts + [
"-t0", # multithreaded compilation
"--extended-lambda",
]
if args.fast_math:
nvcc_opts.append("--use_fast_math")
# is the library being built with CUDA enabled?
cuda_enabled = "WP_ENABLE_CUDA=1" if (cu_path is not None) else "WP_ENABLE_CUDA=0"
if os.name == "nt":
if args.host_compiler:
host_linker = os.path.join(os.path.dirname(args.host_compiler), "link.exe")
else:
raise RuntimeError("Warp build error: No host compiler was found")
cpp_includes = f' /I"{warp_home_path.parent}/external/llvm-project/out/install/{mode}-{arch}/include"'
cpp_includes += f' /I"{warp_home_path.parent}/_build/host-deps/llvm-project/release-{arch}/include"'
cuda_includes = f' /I"{cuda_home}/include"' if cu_path else ""
includes = cpp_includes + cuda_includes
# nvrtc_static.lib is built with /MT and _ITERATOR_DEBUG_LEVEL=0 so if we link it in we must match these options
if cu_path or mode != "debug":
runtime = "/MT"
iter_dbg = "_ITERATOR_DEBUG_LEVEL=0"
debug = "NDEBUG"
else:
runtime = "/MTd"
iter_dbg = "_ITERATOR_DEBUG_LEVEL=2"
debug = "_DEBUG"
cpp_flags = f'/nologo /std:c++17 /GR- {runtime} /D "{debug}" /D "{cuda_enabled}" /D "{cutlass_enabled}" /D "{cuda_compat_enabled}" /D "{iter_dbg}" /I"{native_dir}" /I"{nanovdb_home}" {includes} '
if args.mode == "debug":
cpp_flags += "/Zi /Od /D WP_ENABLE_DEBUG=1"
linkopts = ["/DLL", "/DEBUG"]
elif args.mode == "release":
cpp_flags += "/Ox /D WP_ENABLE_DEBUG=0"
linkopts = ["/DLL"]
else:
raise RuntimeError(f"Unrecognized build configuration (debug, release), got: {args.mode}")
if args.verify_fp:
cpp_flags += ' /D "WP_VERIFY_FP"'
if args.fast_math:
cpp_flags += " /fp:fast"
with ScopedTimer("build", active=args.verbose):
for cpp_path in cpp_paths:
cpp_out = cpp_path + ".obj"
linkopts.append(quote(cpp_out))
cpp_cmd = f'"{args.host_compiler}" {cpp_flags} -c "{cpp_path}" /Fo"{cpp_out}"'
run_cmd(cpp_cmd)
if cu_path:
cu_out = cu_path + ".o"
if mode == "debug":
cuda_cmd = f'"{cuda_home}/bin/nvcc" --compiler-options=/MT,/Zi,/Od -g -G -O0 -DNDEBUG -D_ITERATOR_DEBUG_LEVEL=0 -I"{native_dir}" -I"{nanovdb_home}" -line-info {" ".join(nvcc_opts)} -DWP_ENABLE_CUDA=1 -D{cutlass_enabled} {cutlass_includes} -o "{cu_out}" -c "{cu_path}"'
elif mode == "release":
cuda_cmd = f'"{cuda_home}/bin/nvcc" -O3 {" ".join(nvcc_opts)} -I"{native_dir}" -I"{nanovdb_home}" -DNDEBUG -DWP_ENABLE_CUDA=1 -D{cutlass_enabled} {cutlass_includes} -o "{cu_out}" -c "{cu_path}"'
with ScopedTimer("build_cuda", active=args.verbose):
run_cmd(cuda_cmd)
linkopts.append(quote(cu_out))
linkopts.append(
f'cudart_static.lib nvrtc_static.lib nvrtc-builtins_static.lib nvptxcompiler_static.lib ws2_32.lib user32.lib /LIBPATH:"{cuda_home}/lib/x64"'
)
with ScopedTimer("link", active=args.verbose):
link_cmd = f'"{host_linker}" {" ".join(linkopts + libs)} /out:"{dll_path}"'
run_cmd(link_cmd)
else:
cpp_includes = f' -I"{warp_home_path.parent}/external/llvm-project/out/install/{mode}-{arch}/include"'
cpp_includes += f' -I"{warp_home_path.parent}/_build/host-deps/llvm-project/release-{arch}/include"'
cuda_includes = f' -I"{cuda_home}/include"' if cu_path else ""
includes = cpp_includes + cuda_includes
if sys.platform == "darwin":
version = f"--target={arch}-apple-macos11"
else:
version = "-fabi-version=13" # GCC 8.2+
cpp_flags = f'{version} --std=c++17 -fno-rtti -D{cuda_enabled} -D{cutlass_enabled} -D{cuda_compat_enabled} -fPIC -fvisibility=hidden -D_GLIBCXX_USE_CXX11_ABI=0 -I"{native_dir}" {includes} '
if mode == "debug":
cpp_flags += "-O0 -g -D_DEBUG -DWP_ENABLE_DEBUG=1 -fkeep-inline-functions"
if mode == "release":
cpp_flags += "-O3 -DNDEBUG -DWP_ENABLE_DEBUG=0"
if args.verify_fp:
cpp_flags += " -DWP_VERIFY_FP"
if args.fast_math:
cpp_flags += " -ffast-math"
ld_inputs = []
with ScopedTimer("build", active=args.verbose):
for cpp_path in cpp_paths:
cpp_out = cpp_path + ".o"
ld_inputs.append(quote(cpp_out))
build_cmd = f'g++ {cpp_flags} -c "{cpp_path}" -o "{cpp_out}"'
run_cmd(build_cmd)
if cu_path:
cu_out = cu_path + ".o"
if mode == "debug":
cuda_cmd = f'"{cuda_home}/bin/nvcc" --std=c++17 -g -G -O0 --compiler-options -fPIC,-fvisibility=hidden -D_DEBUG -D_ITERATOR_DEBUG_LEVEL=0 -line-info {" ".join(nvcc_opts)} -DWP_ENABLE_CUDA=1 -I"{native_dir}" -D{cutlass_enabled} {cutlass_includes} -o "{cu_out}" -c "{cu_path}"'
elif mode == "release":
cuda_cmd = f'"{cuda_home}/bin/nvcc" --std=c++17 -O3 --compiler-options -fPIC,-fvisibility=hidden {" ".join(nvcc_opts)} -DNDEBUG -DWP_ENABLE_CUDA=1 -I"{native_dir}" -D{cutlass_enabled} {cutlass_includes} -o "{cu_out}" -c "{cu_path}"'
with ScopedTimer("build_cuda", active=args.verbose):
run_cmd(cuda_cmd)
ld_inputs.append(quote(cu_out))
ld_inputs.append(
f'-L"{cuda_home}/lib64" -lcudart_static -lnvrtc_static -lnvrtc-builtins_static -lnvptxcompiler_static -lpthread -ldl -lrt'
)
if sys.platform == "darwin":
opt_no_undefined = "-Wl,-undefined,error"
opt_exclude_libs = ""
else:
opt_no_undefined = "-Wl,--no-undefined"
opt_exclude_libs = "-Wl,--exclude-libs,ALL"
with ScopedTimer("link", active=args.verbose):
origin = "@loader_path" if (sys.platform == "darwin") else "$ORIGIN"
link_cmd = f"g++ {version} -shared -Wl,-rpath,'{origin}' {opt_no_undefined} {opt_exclude_libs} -o '{dll_path}' {' '.join(ld_inputs + libs)}"
run_cmd(link_cmd)
# Strip symbols to reduce the binary size
if mode == "release":
if sys.platform == "darwin":
run_cmd(f"strip -x {dll_path}") # Strip all local symbols
else: # Linux
# Strip all symbols except for those needed to support debugging JIT-compiled code
run_cmd(
f"strip --strip-all --keep-symbol=__jit_debug_register_code --keep-symbol=__jit_debug_descriptor {dll_path}"
)
def build_dll(args, dll_path, cpp_paths, cu_path, libs=None):
if libs is None:
libs = []
if sys.platform == "darwin":
# create a universal binary by combining x86-64 and AArch64 builds
build_dll_for_arch(args, dll_path + "-x86_64", cpp_paths, cu_path, libs, "x86_64")
build_dll_for_arch(args, dll_path + "-aarch64", cpp_paths, cu_path, libs, "aarch64")
run_cmd(f"lipo -create -output {dll_path} {dll_path}-x86_64 {dll_path}-aarch64")
os.remove(f"{dll_path}-x86_64")
os.remove(f"{dll_path}-aarch64")
else:
build_dll_for_arch(args, dll_path, cpp_paths, cu_path, libs, machine_architecture())
| 15,896 | Python | 40.398437 | 291 | 0.575239 |
NVIDIA/warp/warp/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.
from __future__ import annotations
import ast
import builtins
import ctypes
import inspect
import math
import re
import sys
import textwrap
import types
from typing import Any, Callable, Dict, Mapping
import warp.config
from warp.types import *
class WarpCodegenError(RuntimeError):
def __init__(self, message):
super().__init__(message)
class WarpCodegenTypeError(TypeError):
def __init__(self, message):
super().__init__(message)
class WarpCodegenAttributeError(AttributeError):
def __init__(self, message):
super().__init__(message)
class WarpCodegenKeyError(KeyError):
def __init__(self, message):
super().__init__(message)
# map operator to function name
builtin_operators = {}
# see https://www.ics.uci.edu/~pattis/ICS-31/lectures/opexp.pdf for a
# nice overview of python operators
builtin_operators[ast.Add] = "add"
builtin_operators[ast.Sub] = "sub"
builtin_operators[ast.Mult] = "mul"
builtin_operators[ast.MatMult] = "mul"
builtin_operators[ast.Div] = "div"
builtin_operators[ast.FloorDiv] = "floordiv"
builtin_operators[ast.Pow] = "pow"
builtin_operators[ast.Mod] = "mod"
builtin_operators[ast.UAdd] = "pos"
builtin_operators[ast.USub] = "neg"
builtin_operators[ast.Not] = "unot"
builtin_operators[ast.Gt] = ">"
builtin_operators[ast.Lt] = "<"
builtin_operators[ast.GtE] = ">="
builtin_operators[ast.LtE] = "<="
builtin_operators[ast.Eq] = "=="
builtin_operators[ast.NotEq] = "!="
builtin_operators[ast.BitAnd] = "bit_and"
builtin_operators[ast.BitOr] = "bit_or"
builtin_operators[ast.BitXor] = "bit_xor"
builtin_operators[ast.Invert] = "invert"
builtin_operators[ast.LShift] = "lshift"
builtin_operators[ast.RShift] = "rshift"
comparison_chain_strings = [
builtin_operators[ast.Gt],
builtin_operators[ast.Lt],
builtin_operators[ast.LtE],
builtin_operators[ast.GtE],
builtin_operators[ast.Eq],
builtin_operators[ast.NotEq],
]
def op_str_is_chainable(op: str) -> builtins.bool:
return op in comparison_chain_strings
def get_annotations(obj: Any) -> Mapping[str, Any]:
"""Alternative to `inspect.get_annotations()` for Python 3.9 and older."""
# See https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older
if isinstance(obj, type):
return obj.__dict__.get("__annotations__", {})
return getattr(obj, "__annotations__", {})
def struct_instance_repr_recursive(inst: StructInstance, depth: int) -> str:
indent = "\t"
# handle empty structs
if len(inst._cls.vars) == 0:
return f"{inst._cls.key}()"
lines = []
lines.append(f"{inst._cls.key}(")
for field_name, _ in inst._cls.ctype._fields_:
field_value = getattr(inst, field_name, None)
if isinstance(field_value, StructInstance):
field_value = struct_instance_repr_recursive(field_value, depth + 1)
lines.append(f"{indent * (depth + 1)}{field_name}={field_value},")
lines.append(f"{indent * depth})")
return "\n".join(lines)
class StructInstance:
def __init__(self, cls: Struct, ctype):
super().__setattr__("_cls", cls)
# maintain a c-types object for the top-level instance the struct
if not ctype:
super().__setattr__("_ctype", cls.ctype())
else:
super().__setattr__("_ctype", ctype)
# create Python attributes for each of the struct's variables
for field, var in cls.vars.items():
if isinstance(var.type, warp.codegen.Struct):
self.__dict__[field] = StructInstance(var.type, getattr(self._ctype, field))
elif isinstance(var.type, warp.types.array):
self.__dict__[field] = None
else:
self.__dict__[field] = var.type()
def __getattribute__(self, name):
cls = super().__getattribute__("_cls")
if name in cls.vars:
var = cls.vars[name]
if isinstance(var.type, type) and issubclass(var.type, ctypes.Array):
# Each field stored in a `StructInstance` is exposed as
# a standard Python attribute but also has a `ctypes`
# equivalent that is being updated in `__setattr__`.
# However, when assigning in place an object such as a vec/mat
# (e.g.: `my_struct.my_vec[0] = 1.23`), the `__setattr__` method
# from `StructInstance` isn't called, and the synchronization
# mechanism has no chance of updating the underlying ctype data.
# As a workaround, we catch here all attempts at accessing such
# objects and directly return their underlying ctype since
# the Python-facing Warp vectors and matrices are implemented
# using `ctypes.Array` anyways.
return getattr(self._ctype, name)
return super().__getattribute__(name)
def __setattr__(self, name, value):
if name not in self._cls.vars:
raise RuntimeError(f"Trying to set Warp struct attribute that does not exist {name}")
var = self._cls.vars[name]
# update our ctype flat copy
if isinstance(var.type, array):
if value is None:
# create array with null pointer
setattr(self._ctype, name, array_t())
else:
# wp.array
assert isinstance(value, array)
assert types_equal(
value.dtype, var.type.dtype
), f"assign to struct member variable {name} failed, expected type {type_repr(var.type.dtype)}, got type {type_repr(value.dtype)}"
setattr(self._ctype, name, value.__ctype__())
elif isinstance(var.type, Struct):
# assign structs by-value, otherwise we would have problematic cases transferring ownership
# of the underlying ctypes data between shared Python struct instances
if not isinstance(value, StructInstance):
raise RuntimeError(
f"Trying to assign a non-structure value to a struct attribute with type: {self._cls.key}"
)
# destination attribution on self
dest = getattr(self, name)
if dest._cls.key is not value._cls.key:
raise RuntimeError(
f"Trying to assign a structure of type {value._cls.key} to an attribute of {self._cls.key}"
)
# update all nested ctype vars by deep copy
for n in dest._cls.vars:
setattr(dest, n, getattr(value, n))
# early return to avoid updating our Python StructInstance
return
elif issubclass(var.type, ctypes.Array):
# vector/matrix type, e.g. vec3
if value is None:
setattr(self._ctype, name, var.type())
elif types_equal(type(value), var.type):
setattr(self._ctype, name, value)
else:
# conversion from list/tuple, ndarray, etc.
setattr(self._ctype, name, var.type(value))
else:
# primitive type
if value is None:
# zero initialize
setattr(self._ctype, name, var.type._type_())
else:
if hasattr(value, "_type_"):
# assigning warp type value (e.g.: wp.float32)
value = value.value
# float16 needs conversion to uint16 bits
if var.type == warp.float16:
setattr(self._ctype, name, float_to_half_bits(value))
else:
setattr(self._ctype, name, value)
# update Python instance
super().__setattr__(name, value)
def __ctype__(self):
return self._ctype
def __repr__(self):
return struct_instance_repr_recursive(self, 0)
def to(self, device):
"""Copies this struct with all array members moved onto the given device.
Arrays already living on the desired device are referenced as-is, while
arrays being moved are copied.
"""
out = self._cls()
stack = [(self, out, k, v) for k, v in self._cls.vars.items()]
while stack:
src, dst, name, var = stack.pop()
value = getattr(src, name)
if isinstance(var.type, array):
# array_t
setattr(dst, name, value.to(device))
elif isinstance(var.type, Struct):
# nested struct
new_struct = value._cls()
setattr(dst, name, new_struct)
# The call to `setattr()` just above makes a copy of `new_struct`
# so we need to reference that new instance of the struct.
new_struct = getattr(dst, name)
stack.extend((value, new_struct, k, v) for k, v in value._cls.vars.items())
else:
setattr(dst, name, value)
return out
# type description used in numpy structured arrays
def numpy_dtype(self):
return self._cls.numpy_dtype()
# value usable in numpy structured arrays of .numpy_dtype(), e.g. (42, 13.37, [1.0, 2.0, 3.0])
def numpy_value(self):
npvalue = []
for name, var in self._cls.vars.items():
# get the attribute value
value = getattr(self._ctype, name)
if isinstance(var.type, array):
# array_t
npvalue.append(value.numpy_value())
elif isinstance(var.type, Struct):
# nested struct
npvalue.append(value.numpy_value())
elif issubclass(var.type, ctypes.Array):
if len(var.type._shape_) == 1:
# vector
npvalue.append(list(value))
else:
# matrix
npvalue.append([list(row) for row in value])
else:
# scalar
if var.type == warp.float16:
npvalue.append(half_bits_to_float(value))
else:
npvalue.append(value)
return tuple(npvalue)
class Struct:
def __init__(self, cls, key, module):
self.cls = cls
self.module = module
self.key = key
self.vars = {}
annotations = get_annotations(self.cls)
for label, type in annotations.items():
self.vars[label] = Var(label, type)
fields = []
for label, var in self.vars.items():
if isinstance(var.type, array):
fields.append((label, array_t))
elif isinstance(var.type, Struct):
fields.append((label, var.type.ctype))
elif issubclass(var.type, ctypes.Array):
fields.append((label, var.type))
else:
fields.append((label, var.type._type_))
class StructType(ctypes.Structure):
# if struct is empty, add a dummy field to avoid launch errors on CPU device ("ffi_prep_cif failed")
_fields_ = fields or [("_dummy_", ctypes.c_byte)]
self.ctype = StructType
# create default constructor (zero-initialize)
self.default_constructor = warp.context.Function(
func=None,
key=self.key,
namespace="",
value_func=lambda *_: self,
input_types={},
initializer_list_func=lambda *_: False,
native_func=make_full_qualified_name(self.cls),
)
# build a constructor that takes each param as a value
input_types = {label: var.type for label, var in self.vars.items()}
self.value_constructor = warp.context.Function(
func=None,
key=self.key,
namespace="",
value_func=lambda *_: self,
input_types=input_types,
initializer_list_func=lambda *_: False,
native_func=make_full_qualified_name(self.cls),
)
self.default_constructor.add_overload(self.value_constructor)
if module:
module.register_struct(self)
def __call__(self):
"""
This function returns s = StructInstance(self)
s uses self.cls as template.
To enable autocomplete on s, we inherit from self.cls.
For example,
@wp.struct
class A:
# annotations
...
The type annotations are inherited in A(), allowing autocomplete in kernels
"""
# return StructInstance(self)
class NewStructInstance(self.cls, StructInstance):
def __init__(inst):
StructInstance.__init__(inst, self, None)
return NewStructInstance()
def initializer(self):
return self.default_constructor
# return structured NumPy dtype, including field names, formats, and offsets
def numpy_dtype(self):
names = []
formats = []
offsets = []
for name, var in self.vars.items():
names.append(name)
offsets.append(getattr(self.ctype, name).offset)
if isinstance(var.type, array):
# array_t
formats.append(array_t.numpy_dtype())
elif isinstance(var.type, Struct):
# nested struct
formats.append(var.type.numpy_dtype())
elif issubclass(var.type, ctypes.Array):
scalar_typestr = type_typestr(var.type._wp_scalar_type_)
if len(var.type._shape_) == 1:
# vector
formats.append(f"{var.type._length_}{scalar_typestr}")
else:
# matrix
formats.append(f"{var.type._shape_}{scalar_typestr}")
else:
# scalar
formats.append(type_typestr(var.type))
return {"names": names, "formats": formats, "offsets": offsets, "itemsize": ctypes.sizeof(self.ctype)}
# constructs a Warp struct instance from a pointer to the ctype
def from_ptr(self, ptr):
if not ptr:
raise RuntimeError("NULL pointer exception")
# create a new struct instance
instance = self()
for name, var in self.vars.items():
offset = getattr(self.ctype, name).offset
if isinstance(var.type, array):
# We could reconstruct wp.array from array_t, but it's problematic.
# There's no guarantee that the original wp.array is still allocated and
# no easy way to make a backref.
# Instead, we just create a stub annotation, which is not a fully usable array object.
setattr(instance, name, array(dtype=var.type.dtype, ndim=var.type.ndim))
elif isinstance(var.type, Struct):
# nested struct
value = var.type.from_ptr(ptr + offset)
setattr(instance, name, value)
elif issubclass(var.type, ctypes.Array):
# vector/matrix
value = var.type.from_ptr(ptr + offset)
setattr(instance, name, value)
else:
# scalar
cvalue = ctypes.cast(ptr + offset, ctypes.POINTER(var.type._type_)).contents
if var.type == warp.float16:
setattr(instance, name, half_bits_to_float(cvalue))
else:
setattr(instance, name, cvalue.value)
return instance
class Reference:
def __init__(self, value_type):
self.value_type = value_type
def is_reference(type):
return isinstance(type, Reference)
def strip_reference(arg):
if is_reference(arg):
return arg.value_type
else:
return arg
def compute_type_str(base_name, template_params):
if not template_params:
return base_name
def param2str(p):
if isinstance(p, int):
return str(p)
elif hasattr(p, "_type_"):
if p.__name__ == "bool":
return "bool"
else:
return f"wp::{p.__name__}"
return p.__name__
return f"{base_name}<{','.join(map(param2str, template_params))}>"
class Var:
def __init__(self, label, type, requires_grad=False, constant=None, prefix=True):
# convert built-in types to wp types
if type == float:
type = float32
elif type == int:
type = int32
elif type == builtins.bool:
type = bool
self.label = label
self.type = type
self.requires_grad = requires_grad
self.constant = constant
self.prefix = prefix
def __str__(self):
return self.label
@staticmethod
def type_to_ctype(t, value_type=False):
if is_array(t):
if hasattr(t.dtype, "_wp_generic_type_str_"):
dtypestr = compute_type_str(f"wp::{t.dtype._wp_generic_type_str_}", t.dtype._wp_type_params_)
elif isinstance(t.dtype, Struct):
dtypestr = make_full_qualified_name(t.dtype.cls)
elif t.dtype.__name__ in ("bool", "int", "float"):
dtypestr = t.dtype.__name__
else:
dtypestr = f"wp::{t.dtype.__name__}"
classstr = f"wp::{type(t).__name__}"
return f"{classstr}_t<{dtypestr}>"
elif isinstance(t, Struct):
return make_full_qualified_name(t.cls)
elif is_reference(t):
if not value_type:
return Var.type_to_ctype(t.value_type) + "*"
else:
return Var.type_to_ctype(t.value_type)
elif hasattr(t, "_wp_generic_type_str_"):
return compute_type_str(f"wp::{t._wp_generic_type_str_}", t._wp_type_params_)
elif t.__name__ in ("bool", "int", "float"):
return t.__name__
else:
return f"wp::{t.__name__}"
def ctype(self, value_type=False):
return Var.type_to_ctype(self.type, value_type)
def emit(self, prefix: str = "var"):
if self.prefix:
return f"{prefix}_{self.label}"
else:
return self.label
def emit_adj(self):
return self.emit("adj")
class Block:
# Represents a basic block of instructions, e.g.: list
# of straight line instructions inside a for-loop or conditional
def __init__(self):
# list of statements inside this block
self.body_forward = []
self.body_replay = []
self.body_reverse = []
# list of vars declared in this block
self.vars = []
class Adjoint:
# Source code transformer, this class takes a Python function and
# generates forward and backward SSA forms of the function instructions
def __init__(
adj,
func: Callable[..., Any],
overload_annotations=None,
is_user_function=False,
skip_forward_codegen=False,
skip_reverse_codegen=False,
custom_reverse_mode=False,
custom_reverse_num_input_args=-1,
transformers: Optional[List[ast.NodeTransformer]] = None,
):
adj.func = func
adj.is_user_function = is_user_function
# whether the generation of the forward code is skipped for this function
adj.skip_forward_codegen = skip_forward_codegen
# whether the generation of the adjoint code is skipped for this function
adj.skip_reverse_codegen = skip_reverse_codegen
# extract name of source file
adj.filename = inspect.getsourcefile(func) or "unknown source file"
# get source file line number where function starts
_, adj.fun_lineno = inspect.getsourcelines(func)
# get function source code
adj.source = inspect.getsource(func)
# ensures that indented class methods can be parsed as kernels
adj.source = textwrap.dedent(adj.source)
adj.source_lines = adj.source.splitlines()
if transformers is None:
transformers = []
# build AST and apply node transformers
adj.tree = ast.parse(adj.source)
adj.transformers = transformers
for transformer in transformers:
adj.tree = transformer.visit(adj.tree)
adj.fun_name = adj.tree.body[0].name
# for keeping track of line number in function code
adj.lineno = None
# whether the forward code shall be used for the reverse pass and a custom
# function signature is applied to the reverse version of the function
adj.custom_reverse_mode = custom_reverse_mode
# the number of function arguments that pertain to the forward function
# input arguments (i.e. the number of arguments that are not adjoint arguments)
adj.custom_reverse_num_input_args = custom_reverse_num_input_args
# parse argument types
argspec = inspect.getfullargspec(func)
# ensure all arguments are annotated
if overload_annotations is None:
# use source-level argument annotations
if len(argspec.annotations) < len(argspec.args):
raise WarpCodegenError(f"Incomplete argument annotations on function {adj.fun_name}")
adj.arg_types = argspec.annotations
else:
# use overload argument annotations
for arg_name in argspec.args:
if arg_name not in overload_annotations:
raise WarpCodegenError(f"Incomplete overload annotations for function {adj.fun_name}")
adj.arg_types = overload_annotations.copy()
adj.args = []
adj.symbols = {}
for name, type in adj.arg_types.items():
# skip return hint
if name == "return":
continue
# add variable for argument
arg = Var(name, type, False)
adj.args.append(arg)
# pre-populate symbol dictionary with function argument names
# this is to avoid registering false references to overshadowed modules
adj.symbols[name] = arg
# There are cases where a same module might be rebuilt multiple times,
# for example when kernels are nested inside of functions, or when
# a kernel's launch raises an exception. Ideally we'd always want to
# avoid rebuilding kernels but some corner cases seem to depend on it,
# so we only avoid rebuilding kernels that errored out to give a chance
# for unit testing errors being spit out from kernels.
adj.skip_build = False
# generate function ssa form and adjoint
def build(adj, builder, default_builder_options=None):
if adj.skip_build:
return
adj.builder = builder
if default_builder_options is None:
default_builder_options = {}
if adj.builder:
adj.builder_options = adj.builder.options
else:
adj.builder_options = default_builder_options
adj.symbols = {} # map from symbols to adjoint variables
adj.variables = [] # list of local variables (in order)
adj.return_var = None # return type for function or kernel
adj.loop_symbols = [] # symbols at the start of each loop
# blocks
adj.blocks = [Block()]
adj.loop_blocks = []
# holds current indent level
adj.indentation = ""
# used to generate new label indices
adj.label_count = 0
# update symbol map for each argument
for a in adj.args:
adj.symbols[a.label] = a
# recursively evaluate function body
try:
adj.eval(adj.tree.body[0])
except Exception as e:
try:
if isinstance(e, KeyError) and getattr(e.args[0], "__module__", None) == "ast":
msg = f'Syntax error: unsupported construct "ast.{e.args[0].__name__}"'
else:
msg = "Error"
lineno = adj.lineno + adj.fun_lineno
line = adj.source_lines[adj.lineno]
msg += f' while parsing function "{adj.fun_name}" at {adj.filename}:{lineno}:\n{line}\n'
ex, data, traceback = sys.exc_info()
e = ex(";".join([msg] + [str(a) for a in data.args])).with_traceback(traceback)
finally:
adj.skip_build = True
raise e
if builder is not None:
for a in adj.args:
if isinstance(a.type, Struct):
builder.build_struct_recursive(a.type)
elif isinstance(a.type, warp.types.array) and isinstance(a.type.dtype, Struct):
builder.build_struct_recursive(a.type.dtype)
# code generation methods
def format_template(adj, template, input_vars, output_var):
# output var is always the 0th index
args = [output_var] + input_vars
s = template.format(*args)
return s
# generates a list of formatted args
def format_args(adj, prefix, args):
arg_strs = []
for a in args:
if isinstance(a, warp.context.Function):
# functions don't have a var_ prefix so strip it off here
if prefix == "var":
arg_strs.append(a.key)
else:
arg_strs.append(f"{prefix}_{a.key}")
elif is_reference(a.type):
arg_strs.append(f"{prefix}_{a}")
elif isinstance(a, Var):
arg_strs.append(a.emit(prefix))
else:
raise WarpCodegenTypeError(f"Arguments must be variables or functions, got {type(a)}")
return arg_strs
# generates argument string for a forward function call
def format_forward_call_args(adj, args, use_initializer_list):
arg_str = ", ".join(adj.format_args("var", args))
if use_initializer_list:
return f"{{{arg_str}}}"
return arg_str
# generates argument string for a reverse function call
def format_reverse_call_args(
adj,
args_var,
args,
args_out,
use_initializer_list,
has_output_args=True,
require_original_output_arg=False,
):
formatted_var = adj.format_args("var", args_var)
formatted_out = []
if has_output_args and (require_original_output_arg or len(args_out) > 1):
formatted_out = adj.format_args("var", args_out)
formatted_var_adj = adj.format_args(
"&adj" if use_initializer_list else "adj",
args,
)
formatted_out_adj = adj.format_args("adj", args_out)
if len(formatted_var_adj) == 0 and len(formatted_out_adj) == 0:
# there are no adjoint arguments, so we don't need to call the reverse function
return None
if use_initializer_list:
var_str = f"{{{', '.join(formatted_var)}}}"
out_str = f"{{{', '.join(formatted_out)}}}"
adj_str = f"{{{', '.join(formatted_var_adj)}}}"
out_adj_str = ", ".join(formatted_out_adj)
if len(args_out) > 1:
arg_str = ", ".join([var_str, out_str, adj_str, out_adj_str])
else:
arg_str = ", ".join([var_str, adj_str, out_adj_str])
else:
arg_str = ", ".join(formatted_var + formatted_out + formatted_var_adj + formatted_out_adj)
return arg_str
def indent(adj):
adj.indentation = adj.indentation + " "
def dedent(adj):
adj.indentation = adj.indentation[:-4]
def begin_block(adj, name="block"):
b = Block()
# give block a unique id
b.label = name + "_" + str(adj.label_count)
adj.label_count += 1
adj.blocks.append(b)
return b
def end_block(adj):
return adj.blocks.pop()
def add_var(adj, type=None, constant=None):
index = len(adj.variables)
name = str(index)
# allocate new variable
v = Var(name, type=type, constant=constant)
adj.variables.append(v)
adj.blocks[-1].vars.append(v)
return v
# append a statement to the forward pass
def add_forward(adj, statement, replay=None, skip_replay=False):
adj.blocks[-1].body_forward.append(adj.indentation + statement)
if not skip_replay:
if replay:
# if custom replay specified then output it
adj.blocks[-1].body_replay.append(adj.indentation + replay)
else:
# by default just replay the original statement
adj.blocks[-1].body_replay.append(adj.indentation + statement)
# append a statement to the reverse pass
def add_reverse(adj, statement):
adj.blocks[-1].body_reverse.append(adj.indentation + statement)
def add_constant(adj, n):
output = adj.add_var(type=type(n), constant=n)
return output
def load(adj, var):
if is_reference(var.type):
var = adj.add_builtin_call("load", [var])
return var
def add_comp(adj, op_strings, left, comps):
output = adj.add_var(builtins.bool)
left = adj.load(left)
s = output.emit() + " = " + ("(" * len(comps)) + left.emit() + " "
prev_comp = None
for op, comp in zip(op_strings, comps):
comp_chainable = op_str_is_chainable(op)
if comp_chainable and prev_comp:
# We restrict chaining to operands of the same type
if prev_comp.type is comp.type:
prev_comp = adj.load(prev_comp)
comp = adj.load(comp)
s += "&& (" + prev_comp.emit() + " " + op + " " + comp.emit() + ")) "
else:
raise WarpCodegenTypeError(
f"Cannot chain comparisons of unequal types: {prev_comp.type} {op} {comp.type}."
)
else:
comp = adj.load(comp)
s += op + " " + comp.emit() + ") "
prev_comp = comp
s = s.rstrip() + ";"
adj.add_forward(s)
return output
def add_bool_op(adj, op_string, exprs):
exprs = [adj.load(expr) for expr in exprs]
output = adj.add_var(builtins.bool)
command = output.emit() + " = " + (" " + op_string + " ").join([expr.emit() for expr in exprs]) + ";"
adj.add_forward(command)
return output
def resolve_func(adj, func, args, min_outputs, templates, kwds):
arg_types = [strip_reference(a.type) for a in args if not isinstance(a, warp.context.Function)]
if not func.is_builtin():
# user-defined function
overload = func.get_overload(arg_types)
if overload is not None:
return overload
else:
# if func is overloaded then perform overload resolution here
# we validate argument types before they go to generated native code
for f in func.overloads:
# skip type checking for variadic functions
if not f.variadic:
# check argument counts match are compatible (may be some default args)
if len(f.input_types) < len(args):
continue
def match_args(args, f):
# check argument types equal
for i, (arg_name, arg_type) in enumerate(f.input_types.items()):
# if arg type registered as Any, treat as
# template allowing any type to match
if arg_type == Any:
continue
# handle function refs as a special case
if arg_type == Callable and type(args[i]) is warp.context.Function:
continue
if arg_type == Reference and is_reference(args[i].type):
continue
# look for default values for missing args
if i >= len(args):
if arg_name not in f.defaults:
return False
else:
# otherwise check arg type matches input variable type
if not types_equal(arg_type, strip_reference(args[i].type), match_generic=True):
return False
return True
if not match_args(args, f):
continue
# check output dimensions match expectations
if min_outputs:
try:
value_type = f.value_func(args, kwds, templates)
if not hasattr(value_type, "__len__") or len(value_type) != min_outputs:
continue
except Exception:
# value func may fail if the user has given
# incorrect args, so we need to catch this
continue
# found a match, use it
return f
# unresolved function, report error
arg_types = []
for x in args:
if isinstance(x, Var):
# shorten Warp primitive type names
if isinstance(x.type, list):
if len(x.type) != 1:
raise WarpCodegenError("Argument must not be the result from a multi-valued function")
arg_type = x.type[0]
else:
arg_type = x.type
arg_types.append(type_repr(arg_type))
if isinstance(x, warp.context.Function):
arg_types.append("function")
raise WarpCodegenError(
f"Couldn't find function overload for '{func.key}' that matched inputs with types: [{', '.join(arg_types)}]"
)
def add_call(adj, func, args, min_outputs=None, templates=None, kwds=None):
if templates is None:
templates = []
func = adj.resolve_func(func, args, min_outputs, templates, kwds)
# push any default values onto args
for i, (arg_name, _arg_type) in enumerate(func.input_types.items()):
if i >= len(args):
if arg_name in func.defaults:
const = adj.add_constant(func.defaults[arg_name])
args.append(const)
else:
break
# if it is a user-function then build it recursively
if not func.is_builtin() and func not in adj.builder.functions:
adj.builder.build_function(func)
# add custom grad, replay functions to the list of functions
# to be built later (invalid code could be generated if we built them now)
# so that they are not missed when only the forward function is imported
# from another module
if func.custom_grad_func:
adj.builder.deferred_functions.append(func.custom_grad_func)
if func.custom_replay_func:
adj.builder.deferred_functions.append(func.custom_replay_func)
# evaluate the function type based on inputs
arg_types = [strip_reference(a.type) for a in args if not isinstance(a, warp.context.Function)]
return_type = func.value_func(arg_types, kwds, templates)
func_name = compute_type_str(func.native_func, templates)
param_types = list(func.input_types.values())
use_initializer_list = func.initializer_list_func(args, templates)
args_var = [
(
adj.load(a)
if not ((param_types[i] == Reference or param_types[i] == Callable) if i < len(param_types) else False)
else a
)
for i, a in enumerate(args)
]
if return_type is None:
# handles expression (zero output) functions, e.g.: void do_something();
output = None
output_list = []
forward_call = (
f"{func.namespace}{func_name}({adj.format_forward_call_args(args_var, use_initializer_list)});"
)
replay_call = forward_call
if func.custom_replay_func is not None or func.replay_snippet is not None:
replay_call = f"{func.namespace}replay_{func_name}({adj.format_forward_call_args(args_var, use_initializer_list)});"
elif not isinstance(return_type, list) or len(return_type) == 1:
# handle simple function (one output)
if isinstance(return_type, list):
return_type = return_type[0]
output = adj.add_var(return_type)
output_list = [output]
forward_call = f"var_{output} = {func.namespace}{func_name}({adj.format_forward_call_args(args_var, use_initializer_list)});"
replay_call = forward_call
if func.custom_replay_func is not None:
replay_call = f"var_{output} = {func.namespace}replay_{func_name}({adj.format_forward_call_args(args_var, use_initializer_list)});"
else:
# handle multiple value functions
output = [adj.add_var(v) for v in return_type]
output_list = output
forward_call = (
f"{func.namespace}{func_name}({adj.format_forward_call_args(args_var + output, use_initializer_list)});"
)
replay_call = forward_call
if func.skip_replay:
adj.add_forward(forward_call, replay="// " + replay_call)
else:
adj.add_forward(forward_call, replay=replay_call)
if not func.missing_grad and len(args):
reverse_has_output_args = (
func.require_original_output_arg or len(output_list) > 1
) and func.custom_grad_func is None
arg_str = adj.format_reverse_call_args(
args_var,
args,
output_list,
use_initializer_list,
has_output_args=reverse_has_output_args,
require_original_output_arg=func.require_original_output_arg,
)
if arg_str is not None:
reverse_call = f"{func.namespace}adj_{func.native_func}({arg_str});"
adj.add_reverse(reverse_call)
return output
def add_builtin_call(adj, func_name, args, min_outputs=None, templates=None, kwds=None):
if templates is None:
templates = []
func = warp.context.builtin_functions[func_name]
return adj.add_call(func, args, min_outputs, templates, kwds)
def add_return(adj, var):
if var is None or len(var) == 0:
adj.add_forward("return;", f"goto label{adj.label_count};")
elif len(var) == 1:
adj.add_forward(f"return {var[0].emit()};", f"goto label{adj.label_count};")
adj.add_reverse("adj_" + str(var[0]) + " += adj_ret;")
else:
for i, v in enumerate(var):
adj.add_forward(f"ret_{i} = {v.emit()};")
adj.add_reverse(f"adj_{v} += adj_ret_{i};")
adj.add_forward("return;", f"goto label{adj.label_count};")
adj.add_reverse(f"label{adj.label_count}:;")
adj.label_count += 1
# define an if statement
def begin_if(adj, cond):
cond = adj.load(cond)
adj.add_forward(f"if ({cond.emit()}) {{")
adj.add_reverse("}")
adj.indent()
def end_if(adj, cond):
adj.dedent()
adj.add_forward("}")
cond = adj.load(cond)
adj.add_reverse(f"if ({cond.emit()}) {{")
def begin_else(adj, cond):
cond = adj.load(cond)
adj.add_forward(f"if (!{cond.emit()}) {{")
adj.add_reverse("}")
adj.indent()
def end_else(adj, cond):
adj.dedent()
adj.add_forward("}")
cond = adj.load(cond)
adj.add_reverse(f"if (!{cond.emit()}) {{")
# define a for-loop
def begin_for(adj, iter):
cond_block = adj.begin_block("for")
adj.loop_blocks.append(cond_block)
adj.add_forward(f"start_{cond_block.label}:;")
adj.indent()
# evaluate cond
adj.add_forward(f"if (iter_cmp({iter.emit()}) == 0) goto end_{cond_block.label};")
# evaluate iter
val = adj.add_builtin_call("iter_next", [iter])
adj.begin_block()
return val
def end_for(adj, iter):
body_block = adj.end_block()
cond_block = adj.end_block()
adj.loop_blocks.pop()
####################
# forward pass
for i in cond_block.body_forward:
adj.blocks[-1].body_forward.append(i)
for i in body_block.body_forward:
adj.blocks[-1].body_forward.append(i)
adj.add_forward(f"goto start_{cond_block.label};", skip_replay=True)
adj.dedent()
adj.add_forward(f"end_{cond_block.label}:;", skip_replay=True)
####################
# reverse pass
reverse = []
# reverse iterator
reverse.append(adj.indentation + f"{iter.emit()} = wp::iter_reverse({iter.emit()});")
for i in cond_block.body_forward:
reverse.append(i)
# zero adjoints
for i in body_block.vars:
reverse.append(adj.indentation + f"\t{i.emit_adj()} = {{}};")
# replay
for i in body_block.body_replay:
reverse.append(i)
# reverse
for i in reversed(body_block.body_reverse):
reverse.append(i)
reverse.append(adj.indentation + f"\tgoto start_{cond_block.label};")
reverse.append(adj.indentation + f"end_{cond_block.label}:;")
adj.blocks[-1].body_reverse.extend(reversed(reverse))
# define a while loop
def begin_while(adj, cond):
# evaluate condition in its own block
# so we can control replay
cond_block = adj.begin_block("while")
adj.loop_blocks.append(cond_block)
cond_block.body_forward.append(f"start_{cond_block.label}:;")
c = adj.eval(cond)
cond_block.body_forward.append(f"if (({c.emit()}) == false) goto end_{cond_block.label};")
# being block around loop
adj.begin_block()
adj.indent()
def end_while(adj):
adj.dedent()
body_block = adj.end_block()
cond_block = adj.end_block()
adj.loop_blocks.pop()
####################
# forward pass
for i in cond_block.body_forward:
adj.blocks[-1].body_forward.append(i)
for i in body_block.body_forward:
adj.blocks[-1].body_forward.append(i)
adj.blocks[-1].body_forward.append(f"goto start_{cond_block.label};")
adj.blocks[-1].body_forward.append(f"end_{cond_block.label}:;")
####################
# reverse pass
reverse = []
# cond
for i in cond_block.body_forward:
reverse.append(i)
# zero adjoints of local vars
for i in body_block.vars:
reverse.append(f"{i.emit_adj()} = {{}};")
# replay
for i in body_block.body_replay:
reverse.append(i)
# reverse
for i in reversed(body_block.body_reverse):
reverse.append(i)
reverse.append(f"goto start_{cond_block.label};")
reverse.append(f"end_{cond_block.label}:;")
# output
adj.blocks[-1].body_reverse.extend(reversed(reverse))
def emit_FunctionDef(adj, node):
for f in node.body:
adj.eval(f)
if adj.return_var is not None and len(adj.return_var) == 1:
if not isinstance(node.body[-1], ast.Return):
adj.add_forward("return {};", skip_replay=True)
# native function case: return type is specified, eg -> int or -> wp.float32
is_func_native = False
if node.decorator_list is not None and len(node.decorator_list) == 1:
obj = node.decorator_list[0]
if isinstance(obj, ast.Call):
if isinstance(obj.func, ast.Attribute):
if obj.func.attr == "func_native":
is_func_native = True
if is_func_native and node.returns is not None:
if isinstance(node.returns, ast.Name): # python built-in type
var = Var(label="return_type", type=eval(node.returns.id))
elif isinstance(node.returns, ast.Attribute): # warp type
var = Var(label="return_type", type=eval(node.returns.attr))
else:
raise WarpCodegenTypeError("Native function return type not recognized")
adj.return_var = (var,)
def emit_If(adj, node):
if len(node.body) == 0:
return None
# eval condition
cond = adj.eval(node.test)
# save symbol map
symbols_prev = adj.symbols.copy()
# eval body
adj.begin_if(cond)
for stmt in node.body:
adj.eval(stmt)
adj.end_if(cond)
# detect existing symbols with conflicting definitions (variables assigned inside the branch)
# and resolve with a phi (select) function
for items in symbols_prev.items():
sym = items[0]
var1 = items[1]
var2 = adj.symbols[sym]
if var1 != var2:
# insert a phi function that selects var1, var2 based on cond
out = adj.add_builtin_call("select", [cond, var1, var2])
adj.symbols[sym] = out
symbols_prev = adj.symbols.copy()
# evaluate 'else' statement as if (!cond)
if len(node.orelse) > 0:
adj.begin_else(cond)
for stmt in node.orelse:
adj.eval(stmt)
adj.end_else(cond)
# detect existing symbols with conflicting definitions (variables assigned inside the else)
# and resolve with a phi (select) function
for items in symbols_prev.items():
sym = items[0]
var1 = items[1]
var2 = adj.symbols[sym]
if var1 != var2:
# insert a phi function that selects var1, var2 based on cond
# note the reversed order of vars since we want to use !cond as our select
out = adj.add_builtin_call("select", [cond, var2, var1])
adj.symbols[sym] = out
def emit_Compare(adj, node):
# node.left, node.ops (list of ops), node.comparators (things to compare to)
# e.g. (left ops[0] node.comparators[0]) ops[1] node.comparators[1]
left = adj.eval(node.left)
comps = [adj.eval(comp) for comp in node.comparators]
op_strings = [builtin_operators[type(op)] for op in node.ops]
return adj.add_comp(op_strings, left, comps)
def emit_BoolOp(adj, node):
# op, expr list values
op = node.op
if isinstance(op, ast.And):
func = "&&"
elif isinstance(op, ast.Or):
func = "||"
else:
raise WarpCodegenKeyError(f"Op {op} is not supported")
return adj.add_bool_op(func, [adj.eval(expr) for expr in node.values])
def emit_Name(adj, node):
# lookup symbol, if it has already been assigned to a variable then return the existing mapping
if node.id in adj.symbols:
return adj.symbols[node.id]
# try and resolve the name using the function's globals context (used to lookup constants + functions)
obj = adj.func.__globals__.get(node.id)
if obj is None:
# Lookup constant in captured contents
capturedvars = dict(
zip(adj.func.__code__.co_freevars, [c.cell_contents for c in (adj.func.__closure__ or [])])
)
obj = capturedvars.get(str(node.id), None)
if obj is None:
raise WarpCodegenKeyError("Referencing undefined symbol: " + str(node.id))
if warp.types.is_value(obj):
# evaluate constant
out = adj.add_constant(obj)
adj.symbols[node.id] = out
return out
# the named object is either a function, class name, or module
# pass it back to the caller for processing
if isinstance(obj, warp.context.Function):
return obj
if isinstance(obj, type):
return obj
if isinstance(obj, types.ModuleType):
return obj
raise RuntimeError("Cannot reference a global variable from a kernel unless `wp.constant()` is being used")
@staticmethod
def resolve_type_attribute(var_type: type, attr: str):
if isinstance(var_type, type) and type_is_value(var_type):
if attr == "dtype":
return type_scalar_type(var_type)
elif attr == "length":
return type_length(var_type)
return getattr(var_type, attr, None)
def vector_component_index(adj, component, vector_type):
if len(component) != 1:
raise WarpCodegenAttributeError(f"Vector swizzle must be single character, got .{component}")
dim = vector_type._shape_[0]
swizzles = "xyzw"[0:dim]
if component not in swizzles:
raise WarpCodegenAttributeError(
f"Vector swizzle for {vector_type} must be one of {swizzles}, got {component}"
)
index = swizzles.index(component)
index = adj.add_constant(index)
return index
@staticmethod
def is_differentiable_value_type(var_type):
# checks that the argument type is a value type (i.e, not an array)
# possibly holding differentiable values (for which gradients must be accumulated)
return type_scalar_type(var_type) in float_types or isinstance(var_type, Struct)
def emit_Attribute(adj, node):
if hasattr(node, "is_adjoint"):
node.value.is_adjoint = True
aggregate = adj.eval(node.value)
try:
if isinstance(aggregate, types.ModuleType) or isinstance(aggregate, type):
out = getattr(aggregate, node.attr)
if warp.types.is_value(out):
return adj.add_constant(out)
return out
if hasattr(node, "is_adjoint"):
# create a Var that points to the struct attribute, i.e.: directly generates `struct.attr` when used
attr_name = aggregate.label + "." + node.attr
attr_type = aggregate.type.vars[node.attr].type
return Var(attr_name, attr_type)
aggregate_type = strip_reference(aggregate.type)
# reading a vector component
if type_is_vector(aggregate_type):
index = adj.vector_component_index(node.attr, aggregate_type)
return adj.add_builtin_call("extract", [aggregate, index])
else:
attr_type = Reference(aggregate_type.vars[node.attr].type)
attr = adj.add_var(attr_type)
if is_reference(aggregate.type):
adj.add_forward(f"{attr.emit()} = &({aggregate.emit()}->{node.attr});")
else:
adj.add_forward(f"{attr.emit()} = &({aggregate.emit()}.{node.attr});")
if adj.is_differentiable_value_type(strip_reference(attr_type)):
adj.add_reverse(f"{aggregate.emit_adj()}.{node.attr} += {attr.emit_adj()};")
else:
adj.add_reverse(f"{aggregate.emit_adj()}.{node.attr} = {attr.emit_adj()};")
return attr
except (KeyError, AttributeError) as e:
# Try resolving as type attribute
aggregate_type = strip_reference(aggregate.type) if isinstance(aggregate, Var) else aggregate
type_attribute = adj.resolve_type_attribute(aggregate_type, node.attr)
if type_attribute is not None:
return type_attribute
if isinstance(aggregate, Var):
raise WarpCodegenAttributeError(
f"Error, `{node.attr}` is not an attribute of '{node.value.id}' ({type_repr(aggregate.type)})"
) from e
raise WarpCodegenAttributeError(f"Error, `{node.attr}` is not an attribute of '{aggregate}'") from e
def emit_String(adj, node):
# string constant
return adj.add_constant(node.s)
def emit_Num(adj, node):
# lookup constant, if it has already been assigned then return existing var
key = (node.n, type(node.n))
if key in adj.symbols:
return adj.symbols[key]
else:
out = adj.add_constant(node.n)
adj.symbols[key] = out
return out
def emit_Ellipsis(adj, node):
# stubbed @wp.native_func
return
def emit_NameConstant(adj, node):
if node.value:
return adj.add_constant(True)
elif node.value is None:
raise WarpCodegenTypeError("None type unsupported")
else:
return adj.add_constant(False)
def emit_Constant(adj, node):
if isinstance(node, ast.Str):
return adj.emit_String(node)
elif isinstance(node, ast.Num):
return adj.emit_Num(node)
elif isinstance(node, ast.Ellipsis):
return adj.emit_Ellipsis(node)
else:
assert isinstance(node, ast.NameConstant)
return adj.emit_NameConstant(node)
def emit_BinOp(adj, node):
# evaluate binary operator arguments
left = adj.eval(node.left)
right = adj.eval(node.right)
name = builtin_operators[type(node.op)]
return adj.add_builtin_call(name, [left, right])
def emit_UnaryOp(adj, node):
# evaluate unary op arguments
arg = adj.eval(node.operand)
name = builtin_operators[type(node.op)]
return adj.add_builtin_call(name, [arg])
def materialize_redefinitions(adj, symbols):
# detect symbols with conflicting definitions (assigned inside the for loop)
for items in symbols.items():
sym = items[0]
var1 = items[1]
var2 = adj.symbols[sym]
if var1 != var2:
if warp.config.verbose and not adj.custom_reverse_mode:
lineno = adj.lineno + adj.fun_lineno
line = adj.source_lines[adj.lineno]
msg = f'Warning: detected mutated variable {sym} during a dynamic for-loop in function "{adj.fun_name}" at {adj.filename}:{lineno}: this may not be a differentiable operation.\n{line}\n'
print(msg)
if var1.constant is not None:
raise WarpCodegenError(
f"Error mutating a constant {sym} inside a dynamic loop, use the following syntax: pi = float(3.141) to declare a dynamic variable"
)
# overwrite the old variable value (violates SSA)
adj.add_builtin_call("assign", [var1, var2])
# reset the symbol to point to the original variable
adj.symbols[sym] = var1
def emit_While(adj, node):
adj.begin_while(node.test)
adj.loop_symbols.append(adj.symbols.copy())
# eval body
for s in node.body:
adj.eval(s)
adj.materialize_redefinitions(adj.loop_symbols[-1])
adj.loop_symbols.pop()
adj.end_while()
def eval_num(adj, a):
if isinstance(a, ast.Num):
return True, a.n
if isinstance(a, ast.UnaryOp) and isinstance(a.op, ast.USub) and isinstance(a.operand, ast.Num):
return True, -a.operand.n
# try and resolve the expression to an object
# e.g.: wp.constant in the globals scope
obj, _ = adj.resolve_static_expression(a)
if isinstance(obj, Var) and obj.constant is not None:
obj = obj.constant
return warp.types.is_int(obj), obj
# detects whether a loop contains a break (or continue) statement
def contains_break(adj, body):
for s in body:
if isinstance(s, ast.Break):
return True
elif isinstance(s, ast.Continue):
return True
elif isinstance(s, ast.If):
if adj.contains_break(s.body):
return True
if adj.contains_break(s.orelse):
return True
else:
# note that nested for or while loops containing a break statement
# do not affect the current loop
pass
return False
# returns a constant range() if unrollable, otherwise None
def get_unroll_range(adj, loop):
if (
not isinstance(loop.iter, ast.Call)
or not isinstance(loop.iter.func, ast.Name)
or loop.iter.func.id != "range"
or len(loop.iter.args) == 0
or len(loop.iter.args) > 3
):
return None
# if all range() arguments are numeric constants we will unroll
# note that this only handles trivial constants, it will not unroll
# constant compile-time expressions e.g.: range(0, 3*2)
# Evaluate the arguments and check that they are numeric constants
# It is important to do that in one pass, so that if evaluating these arguments have side effects
# the code does not get generated more than once
range_args = [adj.eval_num(arg) for arg in loop.iter.args]
arg_is_numeric, arg_values = zip(*range_args)
if all(arg_is_numeric):
# All argument are numeric constants
# range(end)
if len(loop.iter.args) == 1:
start = 0
end = arg_values[0]
step = 1
# range(start, end)
elif len(loop.iter.args) == 2:
start = arg_values[0]
end = arg_values[1]
step = 1
# range(start, end, step)
elif len(loop.iter.args) == 3:
start = arg_values[0]
end = arg_values[1]
step = arg_values[2]
# test if we're above max unroll count
max_iters = abs(end - start) // abs(step)
if "max_unroll" in adj.builder_options:
max_unroll = adj.builder_options["max_unroll"]
else:
max_unroll = warp.config.max_unroll
ok_to_unroll = True
if max_iters > max_unroll:
if warp.config.verbose:
print(
f"Warning: fixed-size loop count of {max_iters} is larger than the module 'max_unroll' limit of {max_unroll}, will generate dynamic loop."
)
ok_to_unroll = False
elif adj.contains_break(loop.body):
if warp.config.verbose:
print("Warning: 'break' or 'continue' found in loop body, will generate dynamic loop.")
ok_to_unroll = False
if ok_to_unroll:
return range(start, end, step)
# Unroll is not possible, range needs to be valuated dynamically
range_call = adj.add_builtin_call(
"range",
[adj.add_constant(val) if is_numeric else val for is_numeric, val in range_args],
)
return range_call
def emit_For(adj, node):
# try and unroll simple range() statements that use constant args
unroll_range = adj.get_unroll_range(node)
if isinstance(unroll_range, range):
for i in unroll_range:
const_iter = adj.add_constant(i)
var_iter = adj.add_builtin_call("int", [const_iter])
adj.symbols[node.target.id] = var_iter
# eval body
for s in node.body:
adj.eval(s)
# otherwise generate a dynamic loop
else:
# evaluate the Iterable -- only if not previously evaluated when trying to unroll
if unroll_range is not None:
# Range has already been evaluated when trying to unroll, do not re-evaluate
iter = unroll_range
else:
iter = adj.eval(node.iter)
adj.symbols[node.target.id] = adj.begin_for(iter)
# for loops should be side-effect free, here we store a copy
adj.loop_symbols.append(adj.symbols.copy())
# eval body
for s in node.body:
adj.eval(s)
adj.materialize_redefinitions(adj.loop_symbols[-1])
adj.loop_symbols.pop()
adj.end_for(iter)
def emit_Break(adj, node):
adj.materialize_redefinitions(adj.loop_symbols[-1])
adj.add_forward(f"goto end_{adj.loop_blocks[-1].label};")
def emit_Continue(adj, node):
adj.materialize_redefinitions(adj.loop_symbols[-1])
adj.add_forward(f"goto start_{adj.loop_blocks[-1].label};")
def emit_Expr(adj, node):
return adj.eval(node.value)
def check_tid_in_func_error(adj, node):
if adj.is_user_function:
if hasattr(node.func, "attr") and node.func.attr == "tid":
lineno = adj.lineno + adj.fun_lineno
line = adj.source_lines[adj.lineno]
raise WarpCodegenError(
"tid() may only be called from a Warp kernel, not a Warp function. "
"Instead, obtain the indices from a @wp.kernel and pass them as "
f"arguments to the function {adj.fun_name}, {adj.filename}:{lineno}:\n{line}\n"
)
def emit_Call(adj, node):
adj.check_tid_in_func_error(node)
# try and lookup function in globals by
# resolving path (e.g.: module.submodule.attr)
func, path = adj.resolve_static_expression(node.func)
templates = []
if not isinstance(func, warp.context.Function):
attr = path[-1]
caller = func
func = None
# try and lookup function name in builtins (e.g.: using `dot` directly without wp prefix)
if attr in warp.context.builtin_functions:
func = warp.context.builtin_functions[attr]
# vector class type e.g.: wp.vec3f constructor
if func is None and hasattr(caller, "_wp_generic_type_str_"):
templates = caller._wp_type_params_
func = warp.context.builtin_functions.get(caller._wp_constructor_)
# scalar class type e.g.: wp.int8 constructor
if func is None and hasattr(caller, "__name__") and caller.__name__ in warp.context.builtin_functions:
func = warp.context.builtin_functions.get(caller.__name__)
# struct constructor
if func is None and isinstance(caller, Struct):
adj.builder.build_struct_recursive(caller)
func = caller.initializer()
if func is None:
raise WarpCodegenError(
f"Could not find function {'.'.join(path)} as a built-in or user-defined function. Note that user functions must be annotated with a @wp.func decorator to be called from a kernel."
)
args = []
# eval all arguments
for arg in node.args:
var = adj.eval(arg)
args.append(var)
# eval all keyword args
def kwval(kw):
if isinstance(kw.value, ast.Num):
return kw.value.n
elif isinstance(kw.value, ast.Tuple):
arg_is_numeric, arg_values = zip(*(adj.eval_num(e) for e in kw.value.elts))
if not all(arg_is_numeric):
raise WarpCodegenError(
f"All elements of the tuple keyword argument '{kw.name}' must be numeric constants, got '{arg_values}'"
)
return arg_values
else:
return adj.resolve_static_expression(kw.value)[0]
kwds = {kw.arg: kwval(kw) for kw in node.keywords}
# get expected return count, e.g.: for multi-assignment
min_outputs = None
if hasattr(node, "expects"):
min_outputs = node.expects
# add var with value type from the function
out = adj.add_call(func=func, args=args, kwds=kwds, templates=templates, min_outputs=min_outputs)
return out
def emit_Index(adj, node):
# the ast.Index node appears in 3.7 versions
# when performing array slices, e.g.: x = arr[i]
# but in version 3.8 and higher it does not appear
if hasattr(node, "is_adjoint"):
node.value.is_adjoint = True
return adj.eval(node.value)
# returns the object being indexed, and the list of indices
def eval_subscript(adj, node):
# We want to coalesce multi-dimentional array indexing into a single operation. This needs to deal with expressions like `a[i][j][x][y]` where `a` is a 2D array of matrices,
# and essentially rewrite it into `a[i, j][x][y]`. Since the AST observes the indexing right-to-left, and we don't want to evaluate the index expressions prematurely,
# this requires a first loop to check if this `node` only performs indexing on the array, and a second loop to evaluate and collect index variables.
root = node
count = 0
array = None
while isinstance(root, ast.Subscript):
if isinstance(root.slice, ast.Tuple):
# handles the x[i, j] case (Python 3.8.x upward)
count += len(root.slice.elts)
elif isinstance(root.slice, ast.Index) and isinstance(root.slice.value, ast.Tuple):
# handles the x[i, j] case (Python 3.7.x)
count += len(root.slice.value.elts)
else:
# simple expression, e.g.: x[i]
count += 1
if isinstance(root.value, ast.Name):
symbol = adj.emit_Name(root.value)
symbol_type = strip_reference(symbol.type)
if is_array(symbol_type):
array = symbol
break
root = root.value
# If not all indices index into the array, just evaluate the right-most indexing operation.
if not array or (count > array.type.ndim):
count = 1
indices = []
root = node
while len(indices) < count:
if isinstance(root.slice, ast.Tuple):
ij = [adj.eval(arg) for arg in root.slice.elts]
elif isinstance(root.slice, ast.Index) and isinstance(root.slice.value, ast.Tuple):
ij = [adj.eval(arg) for arg in root.slice.value.elts]
else:
ij = [adj.eval(root.slice)]
indices = ij + indices # prepend
root = root.value
target = adj.eval(root)
return target, indices
def emit_Subscript(adj, node):
if hasattr(node.value, "attr") and node.value.attr == "adjoint":
# handle adjoint of a variable, i.e. wp.adjoint[var]
node.slice.is_adjoint = True
var = adj.eval(node.slice)
var_name = var.label
var = Var(f"adj_{var_name}", type=var.type, constant=None, prefix=False)
return var
target, indices = adj.eval_subscript(node)
target_type = strip_reference(target.type)
if is_array(target_type):
if len(indices) == target_type.ndim:
# handles array loads (where each dimension has an index specified)
out = adj.add_builtin_call("address", [target, *indices])
else:
# handles array views (fewer indices than dimensions)
out = adj.add_builtin_call("view", [target, *indices])
else:
# handles non-array type indexing, e.g: vec3, mat33, etc
out = adj.add_builtin_call("extract", [target, *indices])
return out
def emit_Assign(adj, node):
if len(node.targets) != 1:
raise WarpCodegenError("Assigning the same value to multiple variables is not supported")
lhs = node.targets[0]
# handle the case where we are assigning multiple output variables
if isinstance(lhs, ast.Tuple):
# record the expected number of outputs on the node
# we do this so we can decide which function to
# call based on the number of expected outputs
if isinstance(node.value, ast.Call):
node.value.expects = len(lhs.elts)
# evaluate values
if isinstance(node.value, ast.Tuple):
out = [adj.eval(v) for v in node.value.elts]
else:
out = adj.eval(node.value)
names = []
for v in lhs.elts:
if isinstance(v, ast.Name):
names.append(v.id)
else:
raise WarpCodegenError(
"Multiple return functions can only assign to simple variables, e.g.: x, y = func()"
)
if len(names) != len(out):
raise WarpCodegenError(
f"Multiple return functions need to receive all their output values, incorrect number of values to unpack (expected {len(out)}, got {len(names)})"
)
for name, rhs in zip(names, out):
if name in adj.symbols:
if not types_equal(rhs.type, adj.symbols[name].type):
raise WarpCodegenTypeError(
f"Error, assigning to existing symbol {name} ({adj.symbols[name].type}) with different type ({rhs.type})"
)
adj.symbols[name] = rhs
# handles the case where we are assigning to an array index (e.g.: arr[i] = 2.0)
elif isinstance(lhs, ast.Subscript):
rhs = adj.eval(node.value)
if hasattr(lhs.value, "attr") and lhs.value.attr == "adjoint":
# handle adjoint of a variable, i.e. wp.adjoint[var]
lhs.slice.is_adjoint = True
src_var = adj.eval(lhs.slice)
var = Var(f"adj_{src_var.label}", type=src_var.type, constant=None, prefix=False)
adj.add_forward(f"{var.emit()} = {rhs.emit()};")
return
target, indices = adj.eval_subscript(lhs)
target_type = strip_reference(target.type)
if is_array(target_type):
adj.add_builtin_call("array_store", [target, *indices, rhs])
elif type_is_vector(target_type) or type_is_matrix(target_type):
if is_reference(target.type):
attr = adj.add_builtin_call("indexref", [target, *indices])
else:
attr = adj.add_builtin_call("index", [target, *indices])
adj.add_builtin_call("store", [attr, rhs])
if warp.config.verbose and not adj.custom_reverse_mode:
lineno = adj.lineno + adj.fun_lineno
line = adj.source_lines[adj.lineno]
node_source = adj.get_node_source(lhs.value)
print(
f"Warning: mutating {node_source} in function {adj.fun_name} at {adj.filename}:{lineno}: this is a non-differentiable operation.\n{line}\n"
)
else:
raise WarpCodegenError("Can only subscript assign array, vector, and matrix types")
elif isinstance(lhs, ast.Name):
# symbol name
name = lhs.id
# evaluate rhs
rhs = adj.eval(node.value)
# check type matches if symbol already defined
if name in adj.symbols:
if not types_equal(strip_reference(rhs.type), adj.symbols[name].type):
raise WarpCodegenTypeError(
f"Error, assigning to existing symbol {name} ({adj.symbols[name].type}) with different type ({rhs.type})"
)
# handle simple assignment case (a = b), where we generate a value copy rather than reference
if isinstance(node.value, ast.Name) or is_reference(rhs.type):
out = adj.add_builtin_call("copy", [rhs])
else:
out = rhs
# update symbol map (assumes lhs is a Name node)
adj.symbols[name] = out
elif isinstance(lhs, ast.Attribute):
rhs = adj.eval(node.value)
aggregate = adj.eval(lhs.value)
aggregate_type = strip_reference(aggregate.type)
# assigning to a vector component
if type_is_vector(aggregate_type):
index = adj.vector_component_index(lhs.attr, aggregate_type)
if is_reference(aggregate.type):
attr = adj.add_builtin_call("indexref", [aggregate, index])
else:
attr = adj.add_builtin_call("index", [aggregate, index])
adj.add_builtin_call("store", [attr, rhs])
else:
attr = adj.emit_Attribute(lhs)
if is_reference(attr.type):
adj.add_builtin_call("store", [attr, rhs])
else:
adj.add_builtin_call("assign", [attr, rhs])
if warp.config.verbose and not adj.custom_reverse_mode:
lineno = adj.lineno + adj.fun_lineno
line = adj.source_lines[adj.lineno]
msg = f'Warning: detected mutated struct {attr.label} during function "{adj.fun_name}" at {adj.filename}:{lineno}: this is a non-differentiable operation.\n{line}\n'
print(msg)
else:
raise WarpCodegenError("Error, unsupported assignment statement.")
def emit_Return(adj, node):
if node.value is None:
var = None
elif isinstance(node.value, ast.Tuple):
var = tuple(adj.eval(arg) for arg in node.value.elts)
else:
var = (adj.eval(node.value),)
if adj.return_var is not None:
old_ctypes = tuple(v.ctype(value_type=True) for v in adj.return_var)
new_ctypes = tuple(v.ctype(value_type=True) for v in var)
if old_ctypes != new_ctypes:
raise WarpCodegenTypeError(
f"Error, function returned different types, previous: [{', '.join(old_ctypes)}], new [{', '.join(new_ctypes)}]"
)
if var is not None:
adj.return_var = ()
for ret in var:
if is_reference(ret.type):
ret = adj.add_builtin_call("copy", [ret])
adj.return_var += (ret,)
adj.add_return(adj.return_var)
def emit_AugAssign(adj, node):
# replace augmented assignment with assignment statement + binary op
new_node = ast.Assign(targets=[node.target], value=ast.BinOp(node.target, node.op, node.value))
adj.eval(new_node)
def emit_Tuple(adj, node):
# LHS for expressions, such as i, j, k = 1, 2, 3
for elem in node.elts:
adj.eval(elem)
def emit_Pass(adj, node):
pass
node_visitors = {
ast.FunctionDef: emit_FunctionDef,
ast.If: emit_If,
ast.Compare: emit_Compare,
ast.BoolOp: emit_BoolOp,
ast.Name: emit_Name,
ast.Attribute: emit_Attribute,
ast.Str: emit_String, # Deprecated in 3.8; use Constant
ast.Num: emit_Num, # Deprecated in 3.8; use Constant
ast.NameConstant: emit_NameConstant, # Deprecated in 3.8; use Constant
ast.Constant: emit_Constant,
ast.BinOp: emit_BinOp,
ast.UnaryOp: emit_UnaryOp,
ast.While: emit_While,
ast.For: emit_For,
ast.Break: emit_Break,
ast.Continue: emit_Continue,
ast.Expr: emit_Expr,
ast.Call: emit_Call,
ast.Index: emit_Index, # Deprecated in 3.8; Use the index value directly instead.
ast.Subscript: emit_Subscript,
ast.Assign: emit_Assign,
ast.Return: emit_Return,
ast.AugAssign: emit_AugAssign,
ast.Tuple: emit_Tuple,
ast.Pass: emit_Pass,
ast.Ellipsis: emit_Ellipsis,
}
def eval(adj, node):
if hasattr(node, "lineno"):
adj.set_lineno(node.lineno - 1)
emit_node = adj.node_visitors[type(node)]
return emit_node(adj, node)
# helper to evaluate expressions of the form
# obj1.obj2.obj3.attr in the function's global scope
def resolve_path(adj, path):
if len(path) == 0:
return None
# if root is overshadowed by local symbols, bail out
if path[0] in adj.symbols:
return None
if path[0] in __builtins__:
return __builtins__[path[0]]
# Look up the closure info and append it to adj.func.__globals__
# in case you want to define a kernel inside a function and refer
# to variables you've declared inside that function:
def extract_contents(contents):
return contents if isinstance(contents, warp.context.Function) or not callable(contents) else contents
capturedvars = dict(
zip(
adj.func.__code__.co_freevars, [extract_contents(c.cell_contents) for c in (adj.func.__closure__ or [])]
)
)
vars_dict = {**adj.func.__globals__, **capturedvars}
if path[0] in vars_dict:
func = vars_dict[path[0]]
# Support Warp types in kernels without the module suffix (e.g. v = vec3(0.0,0.2,0.4)):
else:
func = getattr(warp, path[0], None)
if func:
for i in range(1, len(path)):
if hasattr(func, path[i]):
func = getattr(func, path[i])
return func
# Evaluates a static expression that does not depend on runtime values
# if eval_types is True, try resolving the path using evaluated type information as well
def resolve_static_expression(adj, root_node, eval_types=True):
attributes = []
node = root_node
while isinstance(node, ast.Attribute):
attributes.append(node.attr)
node = node.value
if eval_types and isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
# support for operators returning modules
# i.e. operator_name(*operator_args).x.y.z
operator_args = node.args
operator_name = node.func.id
if operator_name == "type":
if len(operator_args) != 1:
raise WarpCodegenError(f"type() operator expects exactly one argument, got {len(operator_args)}")
# type() operator
var = adj.eval(operator_args[0])
if isinstance(var, Var):
var_type = strip_reference(var.type)
# Allow accessing type attributes, for instance array.dtype
while attributes:
attr_name = attributes.pop()
var_type, prev_type = adj.resolve_type_attribute(var_type, attr_name), var_type
if var_type is None:
raise WarpCodegenAttributeError(
f"{attr_name} is not an attribute of {type_repr(prev_type)}"
)
return var_type, [str(var_type)]
else:
raise WarpCodegenError(f"Cannot deduce the type of {var}")
# reverse list since ast presents it in backward order
path = [*reversed(attributes)]
if isinstance(node, ast.Name):
path.insert(0, node.id)
# Try resolving path from captured context
captured_obj = adj.resolve_path(path)
if captured_obj is not None:
return captured_obj, path
# Still nothing found, maybe this is a predefined type attribute like `dtype`
if eval_types:
val = adj.eval(root_node)
return [val, path]
return None, path
# annotate generated code with the original source code line
def set_lineno(adj, lineno):
if adj.lineno is None or adj.lineno != lineno:
line = lineno + adj.fun_lineno
source = adj.source_lines[lineno].strip().ljust(80 - len(adj.indentation), " ")
adj.add_forward(f"// {source} <L {line}>")
adj.add_reverse(f"// adj: {source} <L {line}>")
adj.lineno = lineno
def get_node_source(adj, node):
# return the Python code corresponding to the given AST node
return ast.get_source_segment(adj.source, node)
def get_constant_references(adj) -> Dict[str, Any]:
"""Traverses ``adj.tree`` and returns a dictionary containing constant variable names and values.
This function is meant to be used to populate a module's constants dictionary, which then feeds
into the computation of the module's ``content_hash``.
"""
local_variables = set() # Track local variables appearing on the LHS so we know when variables are shadowed
constants_dict = {}
for node in ast.walk(adj.tree):
if isinstance(node, ast.Name) and node.id not in local_variables:
# This node could be a reference to a wp.constant defined or imported into the current namespace
# try and resolve the name using the function's globals context (used to lookup constants + functions)
obj = adj.func.__globals__.get(node.id)
if obj is None:
# Lookup constant in captured contents
capturedvars = dict(
zip(adj.func.__code__.co_freevars, [c.cell_contents for c in (adj.func.__closure__ or [])])
)
obj = capturedvars.get(str(node.id), None)
if warp.types.is_value(obj):
constants_dict[node.id] = obj
elif isinstance(node, ast.Attribute):
obj, path = adj.resolve_static_expression(node, eval_types=False)
if warp.types.is_value(obj):
constants_dict[".".join(path)] = obj
elif isinstance(node, ast.Assign):
# Add the LHS names to the local_variables so we know any subsequent uses are shadowed
lhs = node.targets[0]
if isinstance(lhs, ast.Tuple):
for v in lhs.elts:
if isinstance(v, ast.Name):
local_variables.add(v.id)
elif isinstance(lhs, ast.Name):
local_variables.add(lhs.id)
return constants_dict
# ----------------
# code generation
cpu_module_header = """
#define WP_NO_CRT
#include "builtin.h"
// avoid namespacing of float type for casting to float type, this is to avoid wp::float(x), which is not valid in C++
#define float(x) cast_float(x)
#define adj_float(x, adj_x, adj_ret) adj_cast_float(x, adj_x, adj_ret)
#define int(x) cast_int(x)
#define adj_int(x, adj_x, adj_ret) adj_cast_int(x, adj_x, adj_ret)
#define builtin_tid1d() wp::tid(wp::s_threadIdx)
#define builtin_tid2d(x, y) wp::tid(x, y, wp::s_threadIdx, dim)
#define builtin_tid3d(x, y, z) wp::tid(x, y, z, wp::s_threadIdx, dim)
#define builtin_tid4d(x, y, z, w) wp::tid(x, y, z, w, wp::s_threadIdx, dim)
"""
cuda_module_header = """
#define WP_NO_CRT
#include "builtin.h"
// avoid namespacing of float type for casting to float type, this is to avoid wp::float(x), which is not valid in C++
#define float(x) cast_float(x)
#define adj_float(x, adj_x, adj_ret) adj_cast_float(x, adj_x, adj_ret)
#define int(x) cast_int(x)
#define adj_int(x, adj_x, adj_ret) adj_cast_int(x, adj_x, adj_ret)
#define builtin_tid1d() wp::tid(_idx)
#define builtin_tid2d(x, y) wp::tid(x, y, _idx, dim)
#define builtin_tid3d(x, y, z) wp::tid(x, y, z, _idx, dim)
#define builtin_tid4d(x, y, z, w) wp::tid(x, y, z, w, _idx, dim)
"""
struct_template = """
struct {name}
{{
{struct_body}
CUDA_CALLABLE {name}({forward_args})
{forward_initializers}
{{
}}
CUDA_CALLABLE {name}& operator += (const {name}& rhs)
{{{prefix_add_body}
return *this;}}
}};
static CUDA_CALLABLE void adj_{name}({reverse_args})
{{
{reverse_body}}}
CUDA_CALLABLE void adj_atomic_add({name}* p, {name} t)
{{
{atomic_add_body}}}
"""
cpu_forward_function_template = """
// {filename}:{lineno}
static {return_type} {name}(
{forward_args})
{{
{forward_body}}}
"""
cpu_reverse_function_template = """
// {filename}:{lineno}
static void adj_{name}(
{reverse_args})
{{
{reverse_body}}}
"""
cuda_forward_function_template = """
// {filename}:{lineno}
static CUDA_CALLABLE {return_type} {name}(
{forward_args})
{{
{forward_body}}}
"""
cuda_reverse_function_template = """
// {filename}:{lineno}
static CUDA_CALLABLE void adj_{name}(
{reverse_args})
{{
{reverse_body}}}
"""
cuda_kernel_template = """
extern "C" __global__ void {name}_cuda_kernel_forward(
{forward_args})
{{
for (size_t _idx = static_cast<size_t>(blockDim.x) * static_cast<size_t>(blockIdx.x) + static_cast<size_t>(threadIdx.x);
_idx < dim.size;
_idx += static_cast<size_t>(blockDim.x) * static_cast<size_t>(gridDim.x))
{{
{forward_body} }}
}}
extern "C" __global__ void {name}_cuda_kernel_backward(
{reverse_args})
{{
for (size_t _idx = static_cast<size_t>(blockDim.x) * static_cast<size_t>(blockIdx.x) + static_cast<size_t>(threadIdx.x);
_idx < dim.size;
_idx += static_cast<size_t>(blockDim.x) * static_cast<size_t>(gridDim.x))
{{
{reverse_body} }}
}}
"""
cpu_kernel_template = """
void {name}_cpu_kernel_forward(
{forward_args})
{{
{forward_body}}}
void {name}_cpu_kernel_backward(
{reverse_args})
{{
{reverse_body}}}
"""
cpu_module_template = """
extern "C" {{
// Python CPU entry points
WP_API void {name}_cpu_forward(
{forward_args})
{{
for (size_t i=0; i < dim.size; ++i)
{{
wp::s_threadIdx = i;
{name}_cpu_kernel_forward(
{forward_params});
}}
}}
WP_API void {name}_cpu_backward(
{reverse_args})
{{
for (size_t i=0; i < dim.size; ++i)
{{
wp::s_threadIdx = i;
{name}_cpu_kernel_backward(
{reverse_params});
}}
}}
}} // extern C
"""
cuda_module_header_template = """
extern "C" {{
// Python CUDA entry points
WP_API void {name}_cuda_forward(
void* stream,
{forward_args});
WP_API void {name}_cuda_backward(
void* stream,
{reverse_args});
}} // extern C
"""
cpu_module_header_template = """
extern "C" {{
// Python CPU entry points
WP_API void {name}_cpu_forward(
{forward_args});
WP_API void {name}_cpu_backward(
{reverse_args});
}} // extern C
"""
# converts a constant Python value to equivalent C-repr
def constant_str(value):
value_type = type(value)
if value_type == bool or value_type == builtins.bool:
if value:
return "true"
else:
return "false"
elif value_type == str:
# ensure constant strings are correctly escaped
return '"' + str(value.encode("unicode-escape").decode()) + '"'
elif isinstance(value, ctypes.Array):
if value_type._wp_scalar_type_ == float16:
# special case for float16, which is stored as uint16 in the ctypes.Array
from warp.context import runtime
scalar_value = runtime.core.half_bits_to_float
else:
def scalar_value(x):
return x
# list of scalar initializer values
initlist = []
for i in range(value._length_):
x = ctypes.Array.__getitem__(value, i)
initlist.append(str(scalar_value(x)).lower())
if value._wp_scalar_type_ is bool:
dtypestr = f"wp::initializer_array<{value._length_},{value._wp_scalar_type_.__name__}>"
else:
dtypestr = f"wp::initializer_array<{value._length_},wp::{value._wp_scalar_type_.__name__}>"
# construct value from initializer array, e.g. wp::initializer_array<4,wp::float32>{1.0, 2.0, 3.0, 4.0}
return f"{dtypestr}{{{', '.join(initlist)}}}"
elif value_type in warp.types.scalar_types:
# make sure we emit the value of objects, e.g. uint32
return str(value.value)
elif value == math.inf:
return "INFINITY"
elif math.isnan(value):
return "NAN"
else:
# otherwise just convert constant to string
return str(value)
def indent(args, stops=1):
sep = ",\n"
for _i in range(stops):
sep += " "
# return sep + args.replace(", ", "," + sep)
return sep.join(args)
# generates a C function name based on the python function name
def make_full_qualified_name(func):
if not isinstance(func, str):
func = func.__qualname__
return re.sub("[^0-9a-zA-Z_]+", "", func.replace(".", "__"))
def codegen_struct(struct, device="cpu", indent_size=4):
name = make_full_qualified_name(struct.cls)
body = []
indent_block = " " * indent_size
if len(struct.vars) > 0:
for label, var in struct.vars.items():
body.append(var.ctype() + " " + label + ";\n")
else:
# for empty structs, emit the dummy attribute to avoid any compiler-specific alignment issues
body.append("char _dummy_;\n")
forward_args = []
reverse_args = []
forward_initializers = []
reverse_body = []
atomic_add_body = []
prefix_add_body = []
# forward args
for label, var in struct.vars.items():
var_ctype = var.ctype()
forward_args.append(f"{var_ctype} const& {label} = {{}}")
reverse_args.append(f"{var_ctype} const&")
namespace = "wp::" if var_ctype.startswith("wp::") or var_ctype == "bool" else ""
atomic_add_body.append(f"{indent_block}{namespace}adj_atomic_add(&p->{label}, t.{label});\n")
prefix = f"{indent_block}," if forward_initializers else ":"
forward_initializers.append(f"{indent_block}{prefix} {label}{{{label}}}\n")
# prefix-add operator
for label, var in struct.vars.items():
if not is_array(var.type):
prefix_add_body.append(f"{indent_block}{label} += rhs.{label};\n")
# reverse args
for label, var in struct.vars.items():
reverse_args.append(var.ctype() + " & adj_" + label)
if is_array(var.type):
reverse_body.append(f"{indent_block}adj_{label} = adj_ret.{label};\n")
else:
reverse_body.append(f"{indent_block}adj_{label} += adj_ret.{label};\n")
reverse_args.append(name + " & adj_ret")
return struct_template.format(
name=name,
struct_body="".join([indent_block + l for l in body]),
forward_args=indent(forward_args),
forward_initializers="".join(forward_initializers),
reverse_args=indent(reverse_args),
reverse_body="".join(reverse_body),
prefix_add_body="".join(prefix_add_body),
atomic_add_body="".join(atomic_add_body),
)
def codegen_func_forward(adj, func_type="kernel", device="cpu"):
if device == "cpu":
indent = 4
elif device == "cuda":
if func_type == "kernel":
indent = 8
else:
indent = 4
else:
raise ValueError(f"Device {device} not supported for codegen")
indent_block = " " * indent
# primal vars
lines = []
lines += ["//---------\n"]
lines += ["// primal vars\n"]
for var in adj.variables:
if var.constant is None:
lines += [f"{var.ctype()} {var.emit()};\n"]
else:
lines += [f"const {var.ctype()} {var.emit()} = {constant_str(var.constant)};\n"]
# forward pass
lines += ["//---------\n"]
lines += ["// forward\n"]
for f in adj.blocks[0].body_forward:
lines += [f + "\n"]
return "".join([indent_block + l for l in lines])
def codegen_func_reverse(adj, func_type="kernel", device="cpu"):
if device == "cpu":
indent = 4
elif device == "cuda":
if func_type == "kernel":
indent = 8
else:
indent = 4
else:
raise ValueError(f"Device {device} not supported for codegen")
indent_block = " " * indent
lines = []
# primal vars
lines += ["//---------\n"]
lines += ["// primal vars\n"]
for var in adj.variables:
if var.constant is None:
lines += [f"{var.ctype()} {var.emit()};\n"]
else:
lines += [f"const {var.ctype()} {var.emit()} = {constant_str(var.constant)};\n"]
# dual vars
lines += ["//---------\n"]
lines += ["// dual vars\n"]
for var in adj.variables:
lines += [f"{var.ctype(value_type=True)} {var.emit_adj()} = {{}};\n"]
# forward pass
lines += ["//---------\n"]
lines += ["// forward\n"]
for f in adj.blocks[0].body_replay:
lines += [f + "\n"]
# reverse pass
lines += ["//---------\n"]
lines += ["// reverse\n"]
for l in reversed(adj.blocks[0].body_reverse):
lines += [l + "\n"]
# In grid-stride kernels the reverse body is in a for loop
if device == "cuda" and func_type == "kernel":
lines += ["continue;\n"]
else:
lines += ["return;\n"]
return "".join([indent_block + l for l in lines])
def codegen_func(adj, c_func_name: str, device="cpu", options=None):
if options is None:
options = {}
# forward header
if adj.return_var is not None and len(adj.return_var) == 1:
return_type = adj.return_var[0].ctype()
else:
return_type = "void"
has_multiple_outputs = adj.return_var is not None and len(adj.return_var) != 1
forward_args = []
reverse_args = []
# forward args
for i, arg in enumerate(adj.args):
s = f"{arg.ctype()} {arg.emit()}"
forward_args.append(s)
if not adj.custom_reverse_mode or i < adj.custom_reverse_num_input_args:
reverse_args.append(s)
if has_multiple_outputs:
for i, arg in enumerate(adj.return_var):
forward_args.append(arg.ctype() + " & ret_" + str(i))
reverse_args.append(arg.ctype() + " & ret_" + str(i))
# reverse args
for i, arg in enumerate(adj.args):
if adj.custom_reverse_mode and i >= adj.custom_reverse_num_input_args:
break
# indexed array gradients are regular arrays
if isinstance(arg.type, indexedarray):
_arg = Var(arg.label, array(dtype=arg.type.dtype, ndim=arg.type.ndim))
reverse_args.append(_arg.ctype() + " & adj_" + arg.label)
else:
reverse_args.append(arg.ctype() + " & adj_" + arg.label)
if has_multiple_outputs:
for i, arg in enumerate(adj.return_var):
reverse_args.append(arg.ctype() + " & adj_ret_" + str(i))
elif return_type != "void":
reverse_args.append(return_type + " & adj_ret")
# custom output reverse args (user-declared)
if adj.custom_reverse_mode:
for arg in adj.args[adj.custom_reverse_num_input_args :]:
reverse_args.append(f"{arg.ctype()} & {arg.emit()}")
if device == "cpu":
forward_template = cpu_forward_function_template
reverse_template = cpu_reverse_function_template
elif device == "cuda":
forward_template = cuda_forward_function_template
reverse_template = cuda_reverse_function_template
else:
raise ValueError(f"Device {device} is not supported")
# codegen body
forward_body = codegen_func_forward(adj, func_type="function", device=device)
s = ""
if not adj.skip_forward_codegen:
s += forward_template.format(
name=c_func_name,
return_type=return_type,
forward_args=indent(forward_args),
forward_body=forward_body,
filename=adj.filename,
lineno=adj.fun_lineno,
)
if not adj.skip_reverse_codegen:
if adj.custom_reverse_mode:
reverse_body = "\t// user-defined adjoint code\n" + forward_body
else:
if options.get("enable_backward", True):
reverse_body = codegen_func_reverse(adj, func_type="function", device=device)
else:
reverse_body = '\t// reverse mode disabled (module option "enable_backward" is False)\n'
s += reverse_template.format(
name=c_func_name,
return_type=return_type,
reverse_args=indent(reverse_args),
forward_body=forward_body,
reverse_body=reverse_body,
filename=adj.filename,
lineno=adj.fun_lineno,
)
return s
def codegen_snippet(adj, name, snippet, adj_snippet, replay_snippet):
if adj.return_var is not None and len(adj.return_var) == 1:
return_type = adj.return_var[0].ctype()
else:
return_type = "void"
forward_args = []
reverse_args = []
# forward args
for _i, arg in enumerate(adj.args):
s = f"{arg.ctype()} {arg.emit().replace('var_', '')}"
forward_args.append(s)
reverse_args.append(s)
# reverse args
for _i, arg in enumerate(adj.args):
if isinstance(arg.type, indexedarray):
_arg = Var(arg.label, array(dtype=arg.type.dtype, ndim=arg.type.ndim))
reverse_args.append(_arg.ctype() + " & adj_" + arg.label)
else:
reverse_args.append(arg.ctype() + " & adj_" + arg.label)
if return_type != "void":
reverse_args.append(return_type + " & adj_ret")
forward_template = cuda_forward_function_template
replay_template = cuda_forward_function_template
reverse_template = cuda_reverse_function_template
s = ""
s += forward_template.format(
name=name,
return_type=return_type,
forward_args=indent(forward_args),
forward_body=snippet,
filename=adj.filename,
lineno=adj.fun_lineno,
)
if replay_snippet is not None:
s += replay_template.format(
name="replay_" + name,
return_type=return_type,
forward_args=indent(forward_args),
forward_body=replay_snippet,
filename=adj.filename,
lineno=adj.fun_lineno,
)
if adj_snippet:
reverse_body = adj_snippet
else:
reverse_body = ""
s += reverse_template.format(
name=name,
return_type=return_type,
reverse_args=indent(reverse_args),
forward_body=snippet,
reverse_body=reverse_body,
filename=adj.filename,
lineno=adj.fun_lineno,
)
return s
def codegen_kernel(kernel, device, options):
# Update the module's options with the ones defined on the kernel, if any.
options = dict(options)
options.update(kernel.options)
adj = kernel.adj
forward_args = ["wp::launch_bounds_t dim"]
reverse_args = ["wp::launch_bounds_t dim"]
# forward args
for arg in adj.args:
forward_args.append(arg.ctype() + " var_" + arg.label)
reverse_args.append(arg.ctype() + " var_" + arg.label)
# reverse args
for arg in adj.args:
# indexed array gradients are regular arrays
if isinstance(arg.type, indexedarray):
_arg = Var(arg.label, array(dtype=arg.type.dtype, ndim=arg.type.ndim))
reverse_args.append(_arg.ctype() + " adj_" + arg.label)
else:
reverse_args.append(arg.ctype() + " adj_" + arg.label)
# codegen body
forward_body = codegen_func_forward(adj, func_type="kernel", device=device)
if options["enable_backward"]:
reverse_body = codegen_func_reverse(adj, func_type="kernel", device=device)
else:
reverse_body = ""
if device == "cpu":
template = cpu_kernel_template
elif device == "cuda":
template = cuda_kernel_template
else:
raise ValueError(f"Device {device} is not supported")
s = template.format(
name=kernel.get_mangled_name(),
forward_args=indent(forward_args),
reverse_args=indent(reverse_args),
forward_body=forward_body,
reverse_body=reverse_body,
)
return s
def codegen_module(kernel, device="cpu"):
if device != "cpu":
return ""
adj = kernel.adj
# build forward signature
forward_args = ["wp::launch_bounds_t dim"]
forward_params = ["dim"]
for arg in adj.args:
if hasattr(arg.type, "_wp_generic_type_str_"):
# vectors and matrices are passed from Python by pointer
forward_args.append(f"const {arg.ctype()}* var_" + arg.label)
forward_params.append(f"*var_{arg.label}")
else:
forward_args.append(f"{arg.ctype()} var_{arg.label}")
forward_params.append("var_" + arg.label)
# build reverse signature
reverse_args = [*forward_args]
reverse_params = [*forward_params]
for arg in adj.args:
if isinstance(arg.type, indexedarray):
# indexed array gradients are regular arrays
_arg = Var(arg.label, array(dtype=arg.type.dtype, ndim=arg.type.ndim))
reverse_args.append(f"const {_arg.ctype()} adj_{arg.label}")
reverse_params.append(f"adj_{_arg.label}")
elif hasattr(arg.type, "_wp_generic_type_str_"):
# vectors and matrices are passed from Python by pointer
reverse_args.append(f"const {arg.ctype()}* adj_{arg.label}")
reverse_params.append(f"*adj_{arg.label}")
else:
reverse_args.append(f"{arg.ctype()} adj_{arg.label}")
reverse_params.append(f"adj_{arg.label}")
s = cpu_module_template.format(
name=kernel.get_mangled_name(),
forward_args=indent(forward_args),
reverse_args=indent(reverse_args),
forward_params=indent(forward_params, 3),
reverse_params=indent(reverse_params, 3),
)
return s
| 103,205 | Python | 34.272044 | 206 | 0.563296 |
NVIDIA/warp/warp/fabric.py | import ctypes
import math
from typing import Any
import warp
from warp.types import *
class fabricbucket_t(ctypes.Structure):
_fields_ = [
("index_start", ctypes.c_size_t),
("index_end", ctypes.c_size_t),
("ptr", ctypes.c_void_p),
("lengths", ctypes.c_void_p),
]
def __init__(self, index_start=0, index_end=0, ptr=None, lengths=None):
self.index_start = index_start
self.index_end = index_end
self.ptr = ctypes.c_void_p(ptr)
self.lengths = ctypes.c_void_p(lengths)
class fabricarray_t(ctypes.Structure):
_fields_ = [
("buckets", ctypes.c_void_p), # array of fabricbucket_t on the correct device
("nbuckets", ctypes.c_size_t),
("size", ctypes.c_size_t),
]
def __init__(self, buckets=None, nbuckets=0, size=0):
self.buckets = ctypes.c_void_p(buckets)
self.nbuckets = nbuckets
self.size = size
class indexedfabricarray_t(ctypes.Structure):
_fields_ = [
("fa", fabricarray_t),
("indices", ctypes.c_void_p),
("size", ctypes.c_size_t),
]
def __init__(self, fa=None, indices=None):
if fa is None:
self.fa = fabricarray_t()
else:
self.fa = fa.__ctype__()
if indices is None:
self.indices = ctypes.c_void_p(None)
self.size = 0
else:
self.indices = ctypes.c_void_p(indices.ptr)
self.size = indices.size
def fabric_to_warp_dtype(type_info, attrib_name):
if not type_info[0]:
raise RuntimeError(f"Attribute '{attrib_name}' cannot be used in Warp")
base_type_dict = {
"b": warp.bool, # boolean
"i1": warp.int8,
"i2": warp.int16,
"i4": warp.int32,
"i8": warp.int64,
"u1": warp.uint8,
"u2": warp.uint16,
"u4": warp.uint32,
"u8": warp.uint64,
"f2": warp.float16,
"f4": warp.float32,
"f8": warp.float64,
}
base_dtype = base_type_dict.get(type_info[1])
if base_dtype is None:
raise RuntimeError(f"Attribute '{attrib_name}' base data type '{type_info[1]}' is not supported in Warp")
elem_count = type_info[2]
role = type_info[4]
if role in ("text", "path"):
raise RuntimeError(f"Attribute '{attrib_name}' role '{role}' is not supported in Warp")
if elem_count > 1:
# vector or matrix type
if role == "quat" and elem_count == 4:
return quaternion(base_dtype)
elif role in ("matrix", "transform", "frame"):
# only square matrices are currently supported
mat_size = int(math.sqrt(elem_count))
assert mat_size * mat_size == elem_count
return matrix((mat_size, mat_size), base_dtype)
else:
return vector(elem_count, base_dtype)
else:
# scalar type
return base_dtype
class fabricarray(noncontiguous_array_base[T]):
# member attributes available during code-gen (e.g.: d = arr.shape[0])
# (initialized when needed)
_vars = None
def __init__(self, data=None, attrib=None, dtype=Any, ndim=None):
super().__init__(ARRAY_TYPE_FABRIC)
self.deleter = None
if data is not None:
from .context import runtime
# ensure the attribute name was also specified
if not isinstance(attrib, str):
raise ValueError(f"Invalid attribute name: {attrib}")
# get the fabric interface dictionary
if isinstance(data, dict):
iface = data
elif hasattr(data, "__fabric_arrays_interface__"):
iface = data.__fabric_arrays_interface__
else:
raise ValueError(
"Invalid data argument for fabricarray: expected dict or object with __fabric_arrays_interface__"
)
version = iface.get("version")
if version != 1:
raise ValueError(f"Unsupported Fabric interface version: {version}")
device = iface.get("device")
if not isinstance(device, str):
raise ValueError(f"Invalid Fabric interface device: {device}")
self.device = runtime.get_device(device)
attribs = iface.get("attribs")
if not isinstance(attribs, dict):
raise ValueError("Failed to get Fabric interface attributes")
# look up attribute info by name
attrib_info = attribs.get(attrib)
if not isinstance(attrib_info, dict):
raise ValueError(f"Failed to get attribute '{attrib}'")
type_info = attrib_info["type"]
assert len(type_info) == 5
self.dtype = fabric_to_warp_dtype(type_info, attrib)
self.access = attrib_info["access"]
pointers = attrib_info["pointers"]
counts = attrib_info["counts"]
if not (hasattr(pointers, "__len__") and hasattr(counts, "__len__") and len(pointers) == len(counts)):
raise RuntimeError("Attribute pointers and counts must be lists of the same size")
# check whether it's an array
array_depth = type_info[3]
if array_depth == 0:
self.ndim = 1
array_lengths = None
elif array_depth == 1:
self.ndim = 2
array_lengths = attrib_info["array_lengths"]
if not hasattr(array_lengths, "__len__") or len(array_lengths) != len(pointers):
raise RuntimeError(
"Attribute `array_lengths` must be a list of the same size as `pointers` and `counts`"
)
else:
raise ValueError(f"Invalid attribute array depth: {array_depth}")
num_buckets = len(pointers)
size = 0
buckets = (fabricbucket_t * num_buckets)()
if num_buckets > 0:
for i in range(num_buckets):
buckets[i].index_start = size
buckets[i].index_end = size + counts[i]
buckets[i].ptr = pointers[i]
if array_lengths:
buckets[i].lengths = array_lengths[i]
size += counts[i]
if self.device.is_cuda:
# copy bucket info to device
buckets_size = ctypes.sizeof(buckets)
allocator = self.device.get_allocator()
buckets_ptr = allocator.alloc(buckets_size)
cuda_stream = self.device.stream.cuda_stream
runtime.core.memcpy_h2d(
self.device.context, buckets_ptr, ctypes.addressof(buckets), buckets_size, cuda_stream
)
self.deleter = allocator.deleter
else:
buckets_ptr = ctypes.addressof(buckets)
else:
buckets_ptr = None
self.buckets = buckets
self.size = size
self.shape = (size,)
self.ctype = fabricarray_t(buckets_ptr, num_buckets, size)
else:
# empty array or type annotation
self.dtype = dtype
self.ndim = ndim or 1
self.device = None
self.access = None
self.buckets = None
self.size = 0
self.shape = (0,)
self.ctype = fabricarray_t()
def __del__(self):
# release the bucket info if needed
if self.deleter is None:
return
buckets_size = ctypes.sizeof(self.buckets)
with self.device.context_guard:
self.deleter(self.ctype.buckets, buckets_size)
def __ctype__(self):
return self.ctype
def __len__(self):
return self.size
def __str__(self):
if self.device is None:
# type annotation
return f"fabricarray{self.dtype}"
else:
return str(self.numpy())
def __getitem__(self, key):
if isinstance(key, array):
return indexedfabricarray(fa=self, indices=key)
else:
raise ValueError(f"Fabric arrays only support indexing using index arrays, got key of type {type(key)}")
@property
def vars(self):
# member attributes available during code-gen (e.g.: d = arr.shape[0])
# Note: we use a shared dict for all fabricarray instances
if fabricarray._vars is None:
fabricarray._vars = {"size": warp.codegen.Var("size", uint64)}
return fabricarray._vars
def fill_(self, value):
# TODO?
# filling Fabric arrays of arrays is not supported, because they are jagged arrays of arbitrary lengths
if self.ndim > 1:
raise RuntimeError("Filling Fabric arrays of arrays is not supported")
super().fill_(value)
# special case for fabric array of arrays
# equivalent to calling fabricarray(..., ndim=2)
def fabricarrayarray(**kwargs):
kwargs["ndim"] = 2
return fabricarray(**kwargs)
class indexedfabricarray(noncontiguous_array_base[T]):
# member attributes available during code-gen (e.g.: d = arr.shape[0])
# (initialized when needed)
_vars = None
def __init__(self, fa=None, indices=None, dtype=None, ndim=None):
super().__init__(ARRAY_TYPE_FABRIC_INDEXED)
if fa is not None:
check_index_array(indices, fa.device)
self.fa = fa
self.indices = indices
self.dtype = fa.dtype
self.ndim = fa.ndim
self.device = fa.device
self.size = indices.size
self.shape = (indices.size,)
self.ctype = indexedfabricarray_t(fa, indices)
else:
# allow empty indexedarrays in type annotations
self.fa = None
self.indices = None
self.dtype = dtype
self.ndim = ndim or 1
self.device = None
self.size = 0
self.shape = (0,)
self.ctype = indexedfabricarray_t()
def __ctype__(self):
return self.ctype
def __len__(self):
return self.size
def __str__(self):
if self.device is None:
# type annotation
return f"indexedfabricarray{self.dtype}"
else:
return str(self.numpy())
@property
def vars(self):
# member attributes available during code-gen (e.g.: d = arr.shape[0])
# Note: we use a shared dict for all indexedfabricarray instances
if indexedfabricarray._vars is None:
indexedfabricarray._vars = {"size": warp.codegen.Var("size", uint64)}
return indexedfabricarray._vars
def fill_(self, value):
# TODO?
# filling Fabric arrays of arrays is not supported, because they are jagged arrays of arbitrary lengths
if self.ndim > 1:
raise RuntimeError("Filling indexed Fabric arrays of arrays is not supported")
super().fill_(value)
# special case for indexed fabric array of arrays
# equivalent to calling fabricarray(..., ndim=2)
def indexedfabricarrayarray(**kwargs):
kwargs["ndim"] = 2
return indexedfabricarray(**kwargs)
| 11,316 | Python | 32.482248 | 117 | 0.556645 |
NVIDIA/warp/warp/examples/__init__.py | # Copyright (c) 2024 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
def get_source_directory():
return os.path.realpath(os.path.dirname(__file__))
def get_asset_directory():
return os.path.join(get_source_directory(), "assets")
| 606 | Python | 34.70588 | 76 | 0.778878 |
NVIDIA/warp/warp/examples/browse.py | # Copyright (c) 2024 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 subprocess
import sys
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
subprocess.call(["xdg-open", filename])
if __name__ == "__main__":
import warp.examples
source_dir = warp.examples.get_source_directory()
print(f"Example source directory: {source_dir}")
try:
open_file(source_dir)
except Exception:
pass
| 848 | Python | 27.299999 | 76 | 0.720519 |
NVIDIA/warp/warp/examples/optim/example_bounce.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.
###########################################################################
# Example Sim Grad Bounce
#
# Shows how to use Warp to optimize the initial velocity of a particle
# such that it bounces off the wall and floor in order to hit a target.
#
# This example uses the built-in wp.Tape() object to compute gradients of
# the distance to target (loss) w.r.t the initial velocity, followed by
# a simple gradient-descent optimization step.
#
###########################################################################
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
@wp.kernel
def loss_kernel(pos: wp.array(dtype=wp.vec3), target: wp.vec3, loss: wp.array(dtype=float)):
# distance to target
delta = pos[0] - target
loss[0] = wp.dot(delta, delta)
@wp.kernel
def step_kernel(x: wp.array(dtype=wp.vec3), grad: wp.array(dtype=wp.vec3), alpha: float):
tid = wp.tid()
# gradient descent step
x[tid] = x[tid] - grad[tid] * alpha
class Example:
def __init__(self, stage_path="example_bounce.usd", verbose=False):
self.verbose = verbose
# seconds
sim_duration = 0.6
# control frequency
fps = 60
self.frame_dt = 1.0 / fps
frame_steps = int(sim_duration / self.frame_dt)
# sim frequency
self.sim_substeps = 8
self.sim_steps = frame_steps * self.sim_substeps
self.sim_dt = self.frame_dt / self.sim_substeps
self.iter = 0
self.render_time = 0.0
self.train_rate = 0.02
ke = 1.0e4
kf = 0.0
kd = 1.0e1
mu = 0.2
builder = wp.sim.ModelBuilder()
builder.add_particle(pos=wp.vec3(-0.5, 1.0, 0.0), vel=wp.vec3(5.0, -5.0, 0.0), mass=1.0)
builder.add_shape_box(body=-1, pos=wp.vec3(2.0, 1.0, 0.0), hx=0.25, hy=1.0, hz=1.0, ke=ke, kf=kf, kd=kd, mu=mu)
# use `requires_grad=True` to create a model for differentiable simulation
self.model = builder.finalize(requires_grad=True)
self.model.ground = True
self.model.soft_contact_ke = ke
self.model.soft_contact_kf = kf
self.model.soft_contact_kd = kd
self.model.soft_contact_mu = mu
self.model.soft_contact_margin = 10.0
self.model.soft_contact_restitution = 1.0
self.integrator = wp.sim.SemiImplicitIntegrator()
self.target = (-2.0, 1.5, 0.0)
self.loss = wp.zeros(1, dtype=wp.float32, requires_grad=True)
# allocate sim states for trajectory
self.states = []
for _i in range(self.sim_steps + 1):
self.states.append(self.model.state())
# one-shot contact creation (valid if we're doing simple collision against a constant normal plane)
wp.sim.collide(self.model, self.states[0])
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=1.0)
else:
self.renderer = None
# capture forward/backward passes
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(self.loss)
self.graph = capture.graph
def forward(self):
# run control loop
for i in range(self.sim_steps):
self.states[i].clear_forces()
self.integrator.simulate(self.model, self.states[i], self.states[i + 1], self.sim_dt)
# compute loss on final state
wp.launch(loss_kernel, dim=1, inputs=[self.states[-1].particle_q, self.target, self.loss])
return self.loss
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(self.loss)
# gradient descent step
x = self.states[0].particle_qd
wp.launch(step_kernel, dim=len(x), inputs=[x, x.grad, self.train_rate])
x_grad = self.tape.gradients[self.states[0].particle_qd]
if self.verbose:
print(f"Iter: {self.iter} Loss: {self.loss}")
print(f" x: {x} g: {x_grad}")
# clear grads for next iteration
self.tape.zero()
self.iter = self.iter + 1
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
# draw trajectory
traj_verts = [self.states[0].particle_q.numpy()[0].tolist()]
for i in range(0, self.sim_steps, self.sim_substeps):
traj_verts.append(self.states[i].particle_q.numpy()[0].tolist())
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.states[i])
self.renderer.render_box(
pos=self.target,
rot=wp.quat_identity(),
extents=(0.1, 0.1, 0.1),
name="target",
color=(0.0, 0.0, 0.0),
)
self.renderer.render_line_strip(
vertices=traj_verts,
color=wp.render.bourke_color_map(0.0, 7.0, self.loss.numpy()[0]),
radius=0.02,
name=f"traj_{self.iter-1}",
)
self.renderer.end_frame()
from pxr import Gf, UsdGeom
particles_prim = self.renderer.stage.GetPrimAtPath("/root/particles")
particles = UsdGeom.Points.Get(self.renderer.stage, particles_prim.GetPath())
particles.CreateDisplayColorAttr().Set([Gf.Vec3f(1.0, 1.0, 1.0)], time=self.renderer.time)
self.render_time += self.frame_dt
def check_grad(self):
param = self.states[0].particle_qd
# initial value
x_c = param.numpy().flatten()
# compute numeric gradient
x_grad_numeric = np.zeros_like(x_c)
for i in range(len(x_c)):
eps = 1.0e-3
step = np.zeros_like(x_c)
step[i] = eps
x_1 = x_c + step
x_0 = x_c - step
param.assign(x_1)
l_1 = self.forward().numpy()[0]
param.assign(x_0)
l_0 = self.forward().numpy()[0]
dldx = (l_1 - l_0) / (eps * 2.0)
x_grad_numeric[i] = dldx
# reset initial state
param.assign(x_c)
# compute analytic gradient
tape = wp.Tape()
with tape:
l = self.forward()
tape.backward(l)
x_grad_analytic = tape.gradients[param]
print(f"numeric grad: {x_grad_numeric}")
print(f"analytic grad: {x_grad_analytic}")
tape.zero()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_bounce.usd",
help="Path to the output USD file.",
)
parser.add_argument("--train_iters", type=int, default=250, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, verbose=args.verbose)
example.check_grad()
# replay and optimize
for i in range(args.train_iters):
example.step()
if i % 16 == 0:
example.render()
if example.renderer:
example.renderer.save()
| 8,470 | Python | 31.706564 | 120 | 0.563518 |
NVIDIA/warp/warp/examples/optim/example_inverse_kinematics_torch.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
###########################################################################
# Example Sim Rigid Kinematics
#
# Tests rigid body forward and backwards kinematics through the
# wp.sim.eval_ik() and wp.sim.eval_fk() methods. Shows how to connect
# gradients from Warp to PyTorch, through custom autograd nodes.
#
###########################################################################
import numpy as np
import torch
import warp as wp
import warp.sim
import warp.sim.render
class ForwardKinematics(torch.autograd.Function):
@staticmethod
def forward(ctx, joint_q, joint_qd, model):
ctx.tape = wp.Tape()
ctx.model = model
ctx.joint_q = wp.from_torch(joint_q)
ctx.joint_qd = wp.from_torch(joint_qd)
# allocate output
ctx.state = model.state()
with ctx.tape:
wp.sim.eval_fk(model, ctx.joint_q, ctx.joint_qd, None, ctx.state)
return (wp.to_torch(ctx.state.body_q), wp.to_torch(ctx.state.body_qd))
@staticmethod
def backward(ctx, adj_body_q, adj_body_qd):
# map incoming Torch grads to our output variables
ctx.state.body_q.grad = wp.from_torch(adj_body_q, dtype=wp.transform)
ctx.state.body_qd.grad = wp.from_torch(adj_body_qd, dtype=wp.spatial_vector)
ctx.tape.backward()
# return adjoint w.r.t. inputs
return (wp.to_torch(ctx.tape.gradients[ctx.joint_q]), wp.to_torch(ctx.tape.gradients[ctx.joint_qd]), None)
class Example:
def __init__(self, stage_path="example_inverse_kinematics_torch.usd", verbose=False):
self.verbose = verbose
fps = 60
self.frame_dt = 1.0 / fps
self.render_time = 0.0
builder = wp.sim.ModelBuilder()
builder.add_articulation()
chain_length = 4
chain_width = 1.0
for i in range(chain_length):
if i == 0:
parent = -1
parent_joint_xform = wp.transform([0.0, 0.0, 0.0], wp.quat_identity())
else:
parent = builder.joint_count - 1
parent_joint_xform = wp.transform([chain_width, 0.0, 0.0], wp.quat_identity())
# create body
b = builder.add_body(origin=wp.transform([i, 0.0, 0.0], wp.quat_identity()), armature=0.1)
builder.add_joint_revolute(
parent=parent,
child=b,
axis=wp.vec3(0.0, 0.0, 1.0),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
limit_lower=-np.deg2rad(60.0),
limit_upper=np.deg2rad(60.0),
target_ke=0.0,
target_kd=0.0,
limit_ke=30.0,
limit_kd=30.0,
)
if i == chain_length - 1:
# create end effector
builder.add_shape_sphere(pos=wp.vec3(0.0, 0.0, 0.0), radius=0.1, density=10.0, body=b)
else:
# create shape
builder.add_shape_box(
pos=wp.vec3(chain_width * 0.5, 0.0, 0.0), hx=chain_width * 0.5, hy=0.1, hz=0.1, density=10.0, body=b
)
# finalize model
self.model = builder.finalize()
self.model.ground = False
self.torch_device = wp.device_to_torch(wp.get_device())
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=50.0)
else:
self.renderer = None
self.target = torch.from_numpy(np.array((2.0, 1.0, 0.0))).to(self.torch_device)
self.body_q = None
self.body_qd = None
# optimization variable
self.joint_q = torch.zeros(len(self.model.joint_q), requires_grad=True, device=self.torch_device)
self.joint_qd = torch.zeros(len(self.model.joint_qd), requires_grad=True, device=self.torch_device)
self.train_rate = 0.01
def forward(self):
(self.body_q, self.body_qd) = ForwardKinematics.apply(self.joint_q, self.joint_qd, self.model)
self.loss = torch.norm(self.body_q[self.model.body_count - 1][0:3] - self.target) ** 2.0
def step(self):
with wp.ScopedTimer("step"):
self.forward()
self.loss.backward()
if self.verbose:
print(f"loss: {self.loss}")
print(f"loss: {self.joint_q.grad}")
with torch.no_grad():
self.joint_q -= self.joint_q.grad * self.train_rate
self.joint_q.grad.zero_()
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
s = self.model.state()
s.body_q = wp.from_torch(self.body_q, dtype=wp.transform, requires_grad=False)
s.body_qd = wp.from_torch(self.body_qd, dtype=wp.spatial_vector, requires_grad=False)
self.renderer.begin_frame(self.render_time)
self.renderer.render(s)
self.renderer.render_sphere(
name="target", pos=self.target, rot=wp.quat_identity(), radius=0.1, color=(1.0, 0.0, 0.0)
)
self.renderer.end_frame()
self.render_time += self.frame_dt
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_inverse_kinematics_torch.usd",
help="Path to the output USD file.",
)
parser.add_argument("--train_iters", type=int, default=512, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, verbose=args.verbose)
for _ in range(args.train_iters):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 6,635 | Python | 35.065217 | 120 | 0.581914 |
NVIDIA/warp/warp/examples/optim/example_trajectory.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.
###########################################################################
# Example Trajectory Optimization
#
# Shows how to optimize torque trajectories for a simple planar environment
# using Warp's provided Adam optimizer.
#
###########################################################################
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
from warp.optim import Adam
@wp.kernel
def loss_l2(
states: wp.array2d(dtype=wp.float32), targets: wp.array2d(dtype=wp.float32), loss: wp.array(dtype=wp.float32)
):
i, j = wp.tid()
diff = states[i, j] - targets[i, j]
l = diff * diff
wp.atomic_add(loss, 0, l)
@wp.kernel
def apply_torque(torques: wp.array(dtype=wp.float32), start_index: int, body_f: wp.array(dtype=wp.spatial_vector)):
fx = torques[start_index + 0]
fz = torques[start_index + 1]
body_f[0] = wp.spatial_vector(0.0, 0.0, 0.0, fx, 0.0, fz)
@wp.kernel
def save_state(body_q: wp.array(dtype=wp.transform), write_index: int, states: wp.array2d(dtype=wp.float32)):
pos = wp.transform_get_translation(body_q[0])
states[write_index, 0] = pos[0]
states[write_index, 1] = pos[2]
class Example:
def __init__(self, stage_path="example_trajectory.usd", verbose=False, num_frames=100):
self.verbose = verbose
fps = 60
self.frame_dt = 1.0 / fps
self.num_frames = num_frames
self.sim_substeps = 1
self.sim_dt = self.frame_dt / self.sim_substeps
self.render_time = 0.0
self.iter = 0
builder = wp.sim.ModelBuilder()
# add planar joints
builder = wp.sim.ModelBuilder(gravity=0.0)
builder.add_articulation()
b = builder.add_body(origin=wp.transform())
builder.add_shape_sphere(pos=wp.vec3(0.0, 0.0, 0.0), radius=0.1, density=100.0, body=b)
# compute reference trajectory
rad = np.linspace(0.0, np.pi * 2, self.num_frames)
self.ref_traj = np.stack([np.cos(rad), np.sin(rad)], axis=1)
# set initial joint configuration to first reference state
builder.body_q[0] = wp.transform(p=[self.ref_traj[0][0], 0.0, self.ref_traj[0][1]])
self.ref_traj = wp.array(self.ref_traj, dtype=wp.float32, requires_grad=True)
self.last_traj = wp.empty_like(self.ref_traj)
# finalize model
self.model = builder.finalize(requires_grad=True)
self.builder = builder
self.model.ground = False
self.dof_q = self.model.joint_coord_count
self.dof_qd = self.model.joint_dof_count
self.num_bodies = self.model.body_count
self.action_dim = 2
self.state_dim = 2
assert self.ref_traj.shape == (self.num_frames, self.state_dim)
self.integrator = wp.sim.SemiImplicitIntegrator()
# initial guess
self.actions = wp.array(
np.zeros(self.num_frames * self.action_dim) * 100.0, dtype=wp.float32, requires_grad=True
)
self.optimizer = Adam([self.actions], lr=1e2)
self.loss = wp.zeros(1, dtype=wp.float32, requires_grad=True)
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=100.0)
else:
self.renderer = None
# allocate sim states for trajectory
self.states = []
for _ in range(self.num_frames + 1):
self.states.append(self.model.state())
def forward(self):
"""
Advances the system dynamics given the rigid-body state in maximal coordinates and generalized joint torques
[body_q, body_qd, tau].
"""
self.last_traj.zero_()
for i in range(self.num_frames):
state = self.states[i]
for _ in range(self.sim_substeps):
next_state = self.model.state(requires_grad=True)
wp.sim.collide(self.model, state)
# apply generalized torques to rigid body here, instead of planar joints
wp.launch(apply_torque, 1, inputs=[self.actions, i * self.action_dim], outputs=[state.body_f])
state = self.integrator.simulate(self.model, state, next_state, self.sim_dt)
self.states[i + 1] = state
# save state
wp.launch(save_state, dim=1, inputs=[self.states[i + 1].body_q, i], outputs=[self.last_traj])
# compute loss
wp.launch(loss_l2, dim=self.last_traj.shape, inputs=[self.last_traj, self.ref_traj], outputs=[self.loss])
def step(self):
"""Runs a single optimizer iteration"""
with wp.ScopedTimer("step"):
self.loss.zero_()
tape = wp.Tape()
with tape:
self.forward()
tape.backward(loss=self.loss)
if self.verbose and (self.iter + 1) % 10 == 0:
print(f"Iter {self.iter+1} Loss: {self.loss.numpy()[0]:.3f}")
assert not np.isnan(self.actions.grad.numpy()).any(), "NaN in gradient"
self.optimizer.step([self.actions.grad])
tape.zero()
self.iter = self.iter + 1
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
for i in range(self.num_frames):
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.states[i + 1])
self.renderer.end_frame()
self.render_time += self.frame_dt
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_trajectory.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=100, help="Total number of frames per training iteration.")
parser.add_argument("--train_iters", type=int, default=250, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, verbose=args.verbose, num_frames=args.num_frames)
for i in range(args.train_iters):
example.step()
if i % 25 == 0:
example.render()
if example.renderer:
example.renderer.save()
np_states = example.last_traj.numpy()
np_ref = example.ref_traj.numpy()
if not args.headless:
import matplotlib.pyplot as plt
plt.plot(np_ref[:, 0], np_ref[:, 1], label="Reference Trajectory")
plt.plot(np_states[:, 0], np_states[:, 1], label="Optimized Trajectory")
plt.grid()
plt.legend()
plt.axis("equal")
plt.show()
| 7,670 | Python | 33.554054 | 120 | 0.601695 |
NVIDIA/warp/warp/examples/optim/example_cloth_throw.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.
###########################################################################
# Example Sim Grad Cloth
#
# Shows how to use Warp to optimize the initial velocities of a piece of
# cloth such that its center of mass hits a target after a specified time.
#
# This example uses the built-in wp.Tape() object to compute gradients of
# the distance to target (loss) w.r.t the initial velocity, followed by
# a simple gradient-descent optimization step.
#
###########################################################################
import math
import warp as wp
import warp.sim
import warp.sim.render
@wp.kernel
def com_kernel(positions: wp.array(dtype=wp.vec3), n: int, com: wp.array(dtype=wp.vec3)):
tid = wp.tid()
# compute center of mass
wp.atomic_add(com, 0, positions[tid] / float(n))
@wp.kernel
def loss_kernel(com: wp.array(dtype=wp.vec3), target: wp.vec3, loss: wp.array(dtype=float)):
# sq. distance to target
delta = com[0] - target
loss[0] = wp.dot(delta, delta)
@wp.kernel
def step_kernel(x: wp.array(dtype=wp.vec3), grad: wp.array(dtype=wp.vec3), alpha: float):
tid = wp.tid()
# gradient descent step
x[tid] = x[tid] - grad[tid] * alpha
class Example:
def __init__(self, stage_path="example_cloth_throw.usd", verbose=False):
self.verbose = verbose
# seconds
sim_duration = 2.0
# control frequency
fps = 60
self.frame_dt = 1.0 / fps
frame_steps = int(sim_duration / self.frame_dt)
# sim frequency
self.sim_substeps = 16
self.sim_steps = frame_steps * self.sim_substeps
self.sim_dt = self.frame_dt / self.sim_substeps
self.iter = 0
self.render_time = 0.0
self.train_rate = 5.0
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = 0.01
dim_x = 16
dim_y = 16
builder.add_cloth_grid(
pos=wp.vec3(0.0, 0.0, 0.0),
vel=wp.vec3(0.1, 0.1, 0.0),
rot=wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), -math.pi * 0.25),
dim_x=dim_x,
dim_y=dim_y,
cell_x=1.0 / dim_x,
cell_y=1.0 / dim_y,
mass=1.0,
tri_ke=10000.0,
tri_ka=10000.0,
tri_kd=100.0,
tri_lift=10.0,
tri_drag=5.0,
)
self.model = builder.finalize()
self.model.ground = False
self.integrator = wp.sim.SemiImplicitIntegrator()
self.target = (8.0, 0.0, 0.0)
self.com = wp.zeros(1, dtype=wp.vec3, requires_grad=True)
self.loss = wp.zeros(1, dtype=wp.float32, requires_grad=True)
# allocate sim states for trajectory
self.states = []
for _i in range(self.sim_steps + 1):
self.states.append(self.model.state(requires_grad=True))
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=4.0)
else:
self.renderer = None
# capture forward/backward passes
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(self.loss)
self.graph = capture.graph
def forward(self):
# run control loop
for i in range(self.sim_steps):
self.states[i].clear_forces()
self.integrator.simulate(self.model, self.states[i], self.states[i + 1], self.sim_dt)
# compute loss on final state
self.com.zero_()
wp.launch(
com_kernel,
dim=self.model.particle_count,
inputs=[self.states[-1].particle_q, self.model.particle_count, self.com],
)
wp.launch(loss_kernel, dim=1, inputs=[self.com, self.target, self.loss])
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(self.loss)
# gradient descent step
x = self.states[0].particle_qd
if self.verbose:
print(f"Iter: {self.iter} Loss: {self.loss}")
wp.launch(step_kernel, dim=len(x), inputs=[x, x.grad, self.train_rate])
# clear grads for next iteration
self.tape.zero()
self.iter = self.iter + 1
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
# draw trajectory
traj_verts = [self.states[0].particle_q.numpy().mean(axis=0)]
for i in range(0, self.sim_steps, self.sim_substeps):
traj_verts.append(self.states[i].particle_q.numpy().mean(axis=0))
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.states[i])
self.renderer.render_box(
pos=self.target,
rot=wp.quat_identity(),
extents=(0.1, 0.1, 0.1),
name="target",
color=(1.0, 0.0, 0.0),
)
self.renderer.render_line_strip(
vertices=traj_verts,
color=wp.render.bourke_color_map(0.0, 269.0, self.loss.numpy()[0]),
radius=0.02,
name=f"traj_{self.iter-1}",
)
self.renderer.end_frame()
self.render_time += self.frame_dt
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_cloth_throw.usd",
help="Path to the output USD file.",
)
parser.add_argument("--train_iters", type=int, default=64, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, verbose=args.verbose)
# replay and optimize
for i in range(args.train_iters):
example.step()
if i % 4 == 0:
example.render()
if example.renderer:
example.renderer.save()
| 7,213 | Python | 31.642534 | 120 | 0.56107 |
NVIDIA/warp/warp/examples/optim/example_diffray.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.
#############################################################################
# Example Differentiable Ray Caster
#
# Shows how to use the built-in wp.Mesh data structure and wp.mesh_query_ray()
# function to implement a basic differentiable ray caster
#
##############################################################################
import math
import os
import numpy as np
from pxr import Usd, UsdGeom
import warp as wp
import warp.examples
from warp.optim import SGD
class RenderMode:
"""Rendering modes
grayscale: Lambertian shading from multiple directional lights
texture: 2D texture map
normal_map: mesh normal computed from interpolated vertex normals
"""
grayscale = 0
texture = 1
normal_map = 2
@wp.struct
class RenderMesh:
"""Mesh to be ray casted.
Assumes a triangle mesh as input.
Per-vertex normals are computed with compute_vertex_normals()
"""
id: wp.uint64
vertices: wp.array(dtype=wp.vec3)
indices: wp.array(dtype=int)
tex_coords: wp.array(dtype=wp.vec2)
tex_indices: wp.array(dtype=int)
vertex_normals: wp.array(dtype=wp.vec3)
pos: wp.array(dtype=wp.vec3)
rot: wp.array(dtype=wp.quat)
@wp.struct
class Camera:
"""Basic camera for ray casting"""
horizontal: float
vertical: float
aspect: float
e: float
tan: float
pos: wp.vec3
rot: wp.quat
@wp.struct
class DirectionalLights:
"""Stores arrays of directional light directions and intensities."""
dirs: wp.array(dtype=wp.vec3)
intensities: wp.array(dtype=float)
num_lights: int
@wp.kernel
def vertex_normal_sum_kernel(
verts: wp.array(dtype=wp.vec3), indices: wp.array(dtype=int), normal_sums: wp.array(dtype=wp.vec3)
):
tid = wp.tid()
i = indices[tid * 3]
j = indices[tid * 3 + 1]
k = indices[tid * 3 + 2]
a = verts[i]
b = verts[j]
c = verts[k]
ab = b - a
ac = c - a
area_normal = wp.cross(ab, ac)
wp.atomic_add(normal_sums, i, area_normal)
wp.atomic_add(normal_sums, j, area_normal)
wp.atomic_add(normal_sums, k, area_normal)
@wp.kernel
def normalize_kernel(
normal_sums: wp.array(dtype=wp.vec3),
vertex_normals: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
vertex_normals[tid] = wp.normalize(normal_sums[tid])
@wp.func
def texture_interpolation(tex_interp: wp.vec2, texture: wp.array2d(dtype=wp.vec3)):
tex_width = texture.shape[1]
tex_height = texture.shape[0]
tex = wp.vec2(tex_interp[0] * float(tex_width - 1), (1.0 - tex_interp[1]) * float(tex_height - 1))
x0 = int(tex[0])
x1 = x0 + 1
alpha_x = tex[0] - float(x0)
y0 = int(tex[1])
y1 = y0 + 1
alpha_y = tex[1] - float(y0)
c00 = texture[y0, x0]
c10 = texture[y0, x1]
c01 = texture[y1, x0]
c11 = texture[y1, x1]
lower = (1.0 - alpha_x) * c00 + alpha_x * c10
upper = (1.0 - alpha_x) * c01 + alpha_x * c11
color = (1.0 - alpha_y) * lower + alpha_y * upper
return color
@wp.kernel
def draw_kernel(
mesh: RenderMesh,
camera: Camera,
texture: wp.array2d(dtype=wp.vec3),
rays_width: int,
rays_height: int,
rays: wp.array(dtype=wp.vec3),
lights: DirectionalLights,
mode: int,
):
tid = wp.tid()
x = tid % rays_width
y = rays_height - tid // rays_width
sx = 2.0 * float(x) / float(rays_width) - 1.0
sy = 2.0 * float(y) / float(rays_height) - 1.0
# compute view ray in world space
ro_world = camera.pos
rd_world = wp.normalize(wp.quat_rotate(camera.rot, wp.vec3(sx * camera.tan * camera.aspect, sy * camera.tan, -1.0)))
# compute view ray in mesh space
inv = wp.transform_inverse(wp.transform(mesh.pos[0], mesh.rot[0]))
ro = wp.transform_point(inv, ro_world)
rd = wp.transform_vector(inv, rd_world)
color = wp.vec3(0.0, 0.0, 0.0)
query = wp.mesh_query_ray(mesh.id, ro, rd, 1.0e6)
if query.result:
i = mesh.indices[query.face * 3]
j = mesh.indices[query.face * 3 + 1]
k = mesh.indices[query.face * 3 + 2]
a = mesh.vertices[i]
b = mesh.vertices[j]
c = mesh.vertices[k]
p = wp.mesh_eval_position(mesh.id, query.face, query.u, query.v)
# barycentric coordinates
tri_area = wp.length(wp.cross(b - a, c - a))
w = wp.length(wp.cross(b - a, p - a)) / tri_area
v = wp.length(wp.cross(p - a, c - a)) / tri_area
u = 1.0 - w - v
a_n = mesh.vertex_normals[i]
b_n = mesh.vertex_normals[j]
c_n = mesh.vertex_normals[k]
# vertex normal interpolation
normal = u * a_n + v * b_n + w * c_n
if mode == 0 or mode == 1:
if mode == 0: # grayscale
color = wp.vec3(1.0)
elif mode == 1: # texture interpolation
tex_a = mesh.tex_coords[mesh.tex_indices[query.face * 3]]
tex_b = mesh.tex_coords[mesh.tex_indices[query.face * 3 + 1]]
tex_c = mesh.tex_coords[mesh.tex_indices[query.face * 3 + 2]]
tex = u * tex_a + v * tex_b + w * tex_c
color = texture_interpolation(tex, texture)
# lambertian directional lighting
lambert = float(0.0)
for i in range(lights.num_lights):
dir = wp.transform_vector(inv, lights.dirs[i])
val = lights.intensities[i] * wp.dot(normal, dir)
if val < 0.0:
val = 0.0
lambert = lambert + val
color = lambert * color
elif mode == 2: # normal map
color = normal * 0.5 + wp.vec3(0.5, 0.5, 0.5)
if color[0] > 1.0:
color = wp.vec3(1.0, color[1], color[2])
if color[1] > 1.0:
color = wp.vec3(color[0], 1.0, color[2])
if color[2] > 1.0:
color = wp.vec3(color[0], color[1], 1.0)
rays[tid] = color
@wp.kernel
def downsample_kernel(
rays: wp.array(dtype=wp.vec3), pixels: wp.array(dtype=wp.vec3), rays_width: int, num_samples: int
):
tid = wp.tid()
pixels_width = rays_width / num_samples
px = tid % pixels_width
py = tid // pixels_width
start_idx = py * num_samples * rays_width + px * num_samples
color = wp.vec3(0.0, 0.0, 0.0)
for i in range(0, num_samples):
for j in range(0, num_samples):
ray = rays[start_idx + i * rays_width + j]
color = wp.vec3(color[0] + ray[0], color[1] + ray[1], color[2] + ray[2])
num_samples_sq = float(num_samples * num_samples)
color = wp.vec3(color[0] / num_samples_sq, color[1] / num_samples_sq, color[2] / num_samples_sq)
pixels[tid] = color
@wp.kernel
def loss_kernel(pixels: wp.array(dtype=wp.vec3), target_pixels: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float)):
tid = wp.tid()
pixel = pixels[tid]
target_pixel = target_pixels[tid]
diff = target_pixel - pixel
# pseudo Huber loss
delta = 1.0
x = delta * delta * (wp.sqrt(1.0 + (diff[0] / delta) * (diff[0] / delta)) - 1.0)
y = delta * delta * (wp.sqrt(1.0 + (diff[1] / delta) * (diff[1] / delta)) - 1.0)
z = delta * delta * (wp.sqrt(1.0 + (diff[2] / delta) * (diff[2] / delta)) - 1.0)
sum = x + y + z
wp.atomic_add(loss, 0, sum)
@wp.kernel
def normalize(x: wp.array(dtype=wp.quat)):
tid = wp.tid()
x[tid] = wp.normalize(x[tid])
class Example:
"""
Non-differentiable variables:
camera.horizontal: camera horizontal aperture size
camera.vertical: camera vertical aperture size
camera.aspect: camera aspect ratio
camera.e: focal length
camera.pos: camera displacement
camera.rot: camera rotation (quaternion)
pix_width: final image width in pixels
pix_height: final image height in pixels
num_samples: anti-aliasing. calculated as pow(2, num_samples)
directional_lights: characterized by intensity (scalar) and direction (vec3)
render_mesh.indices: mesh vertex indices
render_mesh.tex_indices: texture indices
Differentiable variables:
render_mesh.pos: parent transform displacement
render_mesh.quat: parent transform rotation (quaternion)
render_mesh.vertices: mesh vertex positions
render_mesh.vertex_normals: mesh vertex normals
render_mesh.tex_coords: 2D texture coordinates
"""
def __init__(self, height=1024, train_iters=150, rot_array=None):
cam_pos = wp.vec3(0.0, 0.75, 7.0)
cam_rot = wp.quat(0.0, 0.0, 0.0, 1.0)
horizontal_aperture = 36.0
vertical_aperture = 20.25
aspect = horizontal_aperture / vertical_aperture
focal_length = 50.0
self.height = height
self.width = int(aspect * self.height)
self.num_pixels = self.width * self.height
if rot_array is None:
rot_array = [0.0, 0.0, 0.0, 1.0]
asset_stage = Usd.Stage.Open(os.path.join(warp.examples.get_asset_directory(), "bunny.usd"))
mesh_geom = UsdGeom.Mesh(asset_stage.GetPrimAtPath("/root/bunny"))
points = np.array(mesh_geom.GetPointsAttr().Get())
indices = np.array(mesh_geom.GetFaceVertexIndicesAttr().Get())
num_points = points.shape[0]
num_faces = int(indices.shape[0] / 3)
# manufacture texture coordinates + indices for this asset
distance = np.linalg.norm(points, axis=1)
radius = np.max(distance)
distance = distance / radius
tex_coords = np.stack((distance, distance), axis=1)
tex_indices = indices
# manufacture texture for this asset
x = np.arange(256.0)
xx, yy = np.meshgrid(x, x)
zz = np.zeros_like(xx)
texture_host = np.stack((xx, yy, zz), axis=2) / 255.0
# set anti-aliasing
self.num_samples = 1
# set render mode
self.render_mode = RenderMode.texture
# set training iterations
self.train_rate = 5.00e-8
self.momentum = 0.5
self.dampening = 0.1
self.weight_decay = 0.0
self.train_iters = train_iters
self.period = 10 # Training iterations between render() calls
self.iter = 0
# storage for training animation
self.images = np.zeros((self.height, self.width, 3, max(int(self.train_iters / self.period), 1)))
self.image_counter = 0
# construct RenderMesh
self.render_mesh = RenderMesh()
self.mesh = wp.Mesh(
points=wp.array(points, dtype=wp.vec3, requires_grad=True), indices=wp.array(indices, dtype=int)
)
self.render_mesh.id = self.mesh.id
self.render_mesh.vertices = self.mesh.points
self.render_mesh.indices = self.mesh.indices
self.render_mesh.tex_coords = wp.array(tex_coords, dtype=wp.vec2, requires_grad=True)
self.render_mesh.tex_indices = wp.array(tex_indices, dtype=int)
self.normal_sums = wp.zeros(num_points, dtype=wp.vec3, requires_grad=True)
self.render_mesh.vertex_normals = wp.zeros(num_points, dtype=wp.vec3, requires_grad=True)
self.render_mesh.pos = wp.zeros(1, dtype=wp.vec3, requires_grad=True)
self.render_mesh.rot = wp.array(np.array(rot_array), dtype=wp.quat, requires_grad=True)
# compute vertex normals
wp.launch(
kernel=vertex_normal_sum_kernel,
dim=num_faces,
inputs=[self.render_mesh.vertices, self.render_mesh.indices, self.normal_sums],
)
wp.launch(
kernel=normalize_kernel,
dim=num_points,
inputs=[self.normal_sums, self.render_mesh.vertex_normals],
)
# construct camera
self.camera = Camera()
self.camera.horizontal = horizontal_aperture
self.camera.vertical = vertical_aperture
self.camera.aspect = aspect
self.camera.e = focal_length
self.camera.tan = vertical_aperture / (2.0 * focal_length)
self.camera.pos = cam_pos
self.camera.rot = cam_rot
# construct texture
self.texture = wp.array2d(texture_host, dtype=wp.vec3, requires_grad=True)
# construct lights
self.lights = DirectionalLights()
self.lights.dirs = wp.array(np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]), dtype=wp.vec3, requires_grad=True)
self.lights.intensities = wp.array(np.array([2.0, 0.2]), dtype=float, requires_grad=True)
self.lights.num_lights = 2
# construct rays
self.rays_width = self.width * pow(2, self.num_samples)
self.rays_height = self.height * pow(2, self.num_samples)
self.num_rays = self.rays_width * self.rays_height
self.rays = wp.zeros(self.num_rays, dtype=wp.vec3, requires_grad=True)
# construct pixels
self.pixels = wp.zeros(self.num_pixels, dtype=wp.vec3, requires_grad=True)
self.target_pixels = wp.zeros(self.num_pixels, dtype=wp.vec3)
# loss array
self.loss = wp.zeros(1, dtype=float, requires_grad=True)
# capture graph
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(self.loss)
self.graph = capture.graph
self.optimizer = SGD(
[self.render_mesh.rot],
self.train_rate,
momentum=self.momentum,
dampening=self.dampening,
weight_decay=self.weight_decay,
)
def ray_cast(self):
# raycast
wp.launch(
kernel=draw_kernel,
dim=self.num_rays,
inputs=[
self.render_mesh,
self.camera,
self.texture,
self.rays_width,
self.rays_height,
self.rays,
self.lights,
self.render_mode,
],
)
# downsample
wp.launch(
kernel=downsample_kernel,
dim=self.num_pixels,
inputs=[self.rays, self.pixels, self.rays_width, pow(2, self.num_samples)],
)
def forward(self):
self.ray_cast()
# compute pixel loss
wp.launch(loss_kernel, dim=self.num_pixels, inputs=[self.pixels, self.target_pixels, self.loss])
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(self.loss)
rot_grad = self.tape.gradients[self.render_mesh.rot]
self.optimizer.step([rot_grad])
wp.launch(normalize, dim=1, inputs=[self.render_mesh.rot])
if self.iter % self.period == 0:
print(f"Iter: {self.iter} Loss: {self.loss}")
self.tape.zero()
self.loss.zero_()
self.iter = self.iter + 1
def render(self):
with wp.ScopedTimer("render"):
self.images[:, :, :, self.image_counter] = self.get_image()
self.image_counter += 1
def get_image(self):
return self.pixels.numpy().reshape((self.height, self.width, 3))
def get_animation(self):
fig, ax = plt.subplots()
plt.axis("off")
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
plt.margins(0, 0)
frames = []
for i in range(self.images.shape[3]):
frame = ax.imshow(self.images[:, :, :, i], animated=True)
frames.append([frame])
ani = animation.ArtistAnimation(fig, frames, interval=50, blit=True, repeat_delay=1000)
return ani
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--train_iters", type=int, default=150, help="Total number of training iterations.")
parser.add_argument("--height", type=int, default=1024, help="Height of rendered image in pixels.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
reference_example = Example(height=args.height)
# render target rotation
reference_example.ray_cast()
# offset mesh rotation
example = Example(
train_iters=args.train_iters,
height=args.height,
rot_array=[
0.0,
(math.sqrt(3) - 1) / (2.0 * math.sqrt(2.0)),
0.0,
(math.sqrt(3) + 1) / (2.0 * math.sqrt(2.0)),
],
)
wp.copy(example.target_pixels, reference_example.pixels)
# recover target rotation
for i in range(example.train_iters):
example.step()
if i % example.period == 0:
example.render()
if not args.headless:
import matplotlib.animation as animation
import matplotlib.image as img
import matplotlib.pyplot as plt
target_image = reference_example.get_image()
target_image_filename = "example_diffray_target_image.png"
img.imsave(target_image_filename, target_image)
print(f"Saved the target image at `{target_image_filename}`")
final_image = example.get_image()
final_image_filename = "example_diffray_final_image.png"
img.imsave(final_image_filename, final_image)
print(f"Saved the final image at `{final_image_filename}`")
anim = example.get_animation()
anim_filename = "example_diffray_animation.gif"
anim.save(anim_filename, dpi=300, writer=animation.PillowWriter(fps=5))
print(f"Saved the animation at `{anim_filename}`")
| 18,545 | Python | 31.824779 | 120 | 0.588137 |
NVIDIA/warp/warp/examples/optim/example_spring_cage.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.
###########################################################################
# Example Diff Sim Spring Cage
#
# A single particle is attached with springs to each point of a cage.
# The objective is to optimize the rest length of the springs in order
# for the particle to be pulled towards a target position.
#
###########################################################################
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
@wp.kernel
def compute_loss_kernel(
pos: wp.array(dtype=wp.vec3),
target_pos: wp.vec3,
loss: wp.array(dtype=float),
):
loss[0] = wp.length_sq(pos[0] - target_pos)
@wp.kernel(enable_backward=False)
def apply_gradient_kernel(
spring_rest_lengths_grad: wp.array(dtype=float),
train_rate: float,
spring_rest_lengths: wp.array(dtype=float),
):
tid = wp.tid()
spring_rest_lengths[tid] -= spring_rest_lengths_grad[tid] * train_rate
class Example:
def __init__(self, stage_path="example_spring_cage.usd", num_frames=30, train_iters=25):
# Number of frames per second.
self.fps = 30
# Duration of a single simulation iteration in number of frames.
self.num_frames = num_frames
# Number of simulation steps to take per frame.
self.sim_substep_count = 1
# Delta time between each simulation substep.
self.sim_dt = 1.0 / (self.fps * self.sim_substep_count)
# Target position that we want the main particle to reach by optimising
# the rest lengths of the springs.
self.target_pos = (0.125, 0.25, 0.375)
# Number of training iterations.
self.train_iters = train_iters
# Factor by which the rest lengths of the springs are adjusted after each
# iteration, relatively to the corresponding gradients. Lower values
# converge more slowly but have less chances to miss the local minimum.
self.train_rate = 0.5
# Initialize the helper to build a physics scene.
builder = wp.sim.ModelBuilder()
# Define the main particle at the origin.
particle_mass = 1.0
builder.add_particle((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), particle_mass)
# Define the cage made of points that will be pulling our main particle
# using springs.
# fmt: off
builder.add_particle((-0.7, 0.8, 0.2), (0.0, 0.0, 0.0), 0.0)
builder.add_particle(( 0.0, 0.2, 1.1), (0.0, 0.0, 0.0), 0.0)
builder.add_particle(( 0.1, 0.1, -1.2), (0.0, 0.0, 0.0), 0.0)
builder.add_particle(( 0.6, 0.4, 0.4), (0.0, 0.0, 0.0), 0.0)
builder.add_particle(( 0.7, -0.9, -0.2), (0.0, 0.0, 0.0), 0.0)
builder.add_particle((-0.8, -0.8, 0.1), (0.0, 0.0, 0.0), 0.0)
builder.add_particle((-0.9, 0.2, -0.8), (0.0, 0.0, 0.0), 0.0)
builder.add_particle(( 1.0, 0.4, -0.1), (0.0, 0.0, 0.0), 0.0)
# fmt: on
# Define the spring constraints between the main particle and the cage points.
spring_elastic_stiffness = 100.0
spring_elastic_damping = 10.0
for i in range(1, builder.particle_count):
builder.add_spring(0, i, spring_elastic_stiffness, spring_elastic_damping, 0)
# Build the model and set-up its properties.
self.model = builder.finalize(requires_grad=True)
self.model.gravity = np.array((0.0, 0.0, 0.0))
self.model.ground = False
# Use the Euler integrator for stepping through the simulation.
self.integrator = wp.sim.SemiImplicitIntegrator()
# Initialize a state for each simulation step.
self.states = tuple(self.model.state() for _ in range(self.num_frames * self.sim_substep_count + 1))
# Initialize a loss value that will represent the distance of the main
# particle to the target position. It needs to be defined as an array
# so that it can be written out by a kernel.
self.loss = wp.zeros(1, dtype=float, requires_grad=True)
if stage_path:
# Helper to render the physics scene as a USD file.
self.renderer = warp.sim.render.SimRenderer(self.model, stage_path, fps=self.fps, scaling=10.0)
# Allows rendering one simulation to USD every N training iterations.
self.render_iteration_steps = 2
# Frame number used to render the simulation iterations onto the USD file.
self.render_frame = 0
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
# Capture all the kernel launches into a CUDA graph so that they can
# all be run in a single graph launch, which helps with performance.
with wp.ScopedCapture() as capture:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(loss=self.loss)
self.graph = capture.graph
def forward(self):
for i in range(1, len(self.states)):
prev = self.states[i - 1]
curr = self.states[i]
prev.clear_forces()
self.integrator.simulate(
self.model,
prev,
curr,
self.sim_dt,
)
last_state = self.states[-1]
wp.launch(
compute_loss_kernel,
dim=1,
inputs=(
last_state.particle_q,
self.target_pos,
),
outputs=(self.loss,),
)
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.tape.backward(loss=self.loss)
wp.launch(
apply_gradient_kernel,
dim=self.model.spring_count,
inputs=(
self.model.spring_rest_length.grad,
self.train_rate,
),
outputs=(self.model.spring_rest_length,),
)
self.tape.zero()
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(0.0)
self.renderer.render_box(
name="target",
pos=self.target_pos,
rot=wp.quat_identity(),
extents=(0.1, 0.1, 0.1),
color=(1.0, 0.0, 0.0),
)
self.renderer.end_frame()
for frame in range(self.num_frames):
self.renderer.begin_frame(self.render_frame / self.fps)
self.renderer.render(self.states[frame * self.sim_substep_count])
self.renderer.end_frame()
self.render_frame += 1
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_spring_cage.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=30, help="Total number of frames per training iteration.")
parser.add_argument("--train_iters", type=int, default=25, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, num_frames=args.num_frames, train_iters=args.train_iters)
for iteration in range(args.train_iters):
example.step()
loss = example.loss.numpy()[0]
if args.verbose:
print(f"[{iteration:3d}] loss={loss:.8f}")
if example.renderer and (
iteration == example.train_iters - 1 or iteration % example.render_iteration_steps == 0
):
example.render()
if example.renderer:
example.renderer.save()
| 8,824 | Python | 36.079832 | 120 | 0.579896 |
NVIDIA/warp/warp/examples/optim/example_drone.py | # Copyright (c) 2024 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.
###########################################################################
# Example Drone
#
# A drone and its 4 propellers is simulated with the goal of reaching
# different targets via model-predictive control (MPC) that continuously
# optimizes the control trajectory.
#
###########################################################################
import os
from typing import Optional, Tuple
import numpy as np
import warp as wp
import warp.examples
import warp.optim
import warp.sim
import warp.sim.render
from warp.sim.collide import box_sdf, capsule_sdf, cone_sdf, cylinder_sdf, mesh_sdf, plane_sdf, sphere_sdf
DEFAULT_DRONE_PATH = os.path.join(warp.examples.get_asset_directory(), "crazyflie.usd") # Path to input drone asset
@wp.struct
class Propeller:
body: int
pos: wp.vec3
dir: wp.vec3
thrust: float
power: float
diameter: float
height: float
max_rpm: float
max_thrust: float
max_torque: float
turning_direction: float
max_speed_square: float
@wp.kernel
def increment_seed(
seed: wp.array(dtype=int),
):
seed[0] += 1
@wp.kernel
def sample_gaussian(
mean_trajectory: wp.array(dtype=float, ndim=3),
noise_scale: float,
num_control_points: int,
control_dim: int,
control_limits: wp.array(dtype=float, ndim=2),
seed: wp.array(dtype=int),
rollout_trajectories: wp.array(dtype=float, ndim=3),
):
env_id, point_id, control_id = wp.tid()
unique_id = (env_id * num_control_points + point_id) * control_dim + control_id
r = wp.rand_init(seed[0], unique_id)
mean = mean_trajectory[0, point_id, control_id]
lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
sample = mean + noise_scale * wp.randn(r)
for _i in range(10):
if sample < lo or sample > hi:
sample = mean + noise_scale * wp.randn(r)
else:
break
rollout_trajectories[env_id, point_id, control_id] = wp.clamp(sample, lo, hi)
@wp.kernel
def replicate_states(
body_q_in: wp.array(dtype=wp.transform),
body_qd_in: wp.array(dtype=wp.spatial_vector),
bodies_per_env: int,
body_q_out: wp.array(dtype=wp.transform),
body_qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
env_offset = tid * bodies_per_env
for i in range(bodies_per_env):
body_q_out[env_offset + i] = body_q_in[i]
body_qd_out[env_offset + i] = body_qd_in[i]
@wp.kernel
def drone_cost(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
targets: wp.array(dtype=wp.vec3),
prop_control: wp.array(dtype=float),
step: int,
horizon_length: int,
weighting: float,
cost: wp.array(dtype=wp.float32),
):
env_id = wp.tid()
tf = body_q[env_id]
target = targets[0]
pos_drone = wp.transform_get_translation(tf)
pos_cost = wp.length_sq(pos_drone - target)
altitude_cost = wp.max(pos_drone[1] - 0.75, 0.0) + wp.max(0.25 - pos_drone[1], 0.0)
upvector = wp.vec3(0.0, 1.0, 0.0)
drone_up = wp.transform_vector(tf, upvector)
upright_cost = 1.0 - wp.dot(drone_up, upvector)
vel_drone = body_qd[env_id]
# Encourage zero velocity.
vel_cost = wp.length_sq(vel_drone)
control = wp.vec4(
prop_control[env_id * 4 + 0],
prop_control[env_id * 4 + 1],
prop_control[env_id * 4 + 2],
prop_control[env_id * 4 + 3],
)
control_cost = wp.dot(control, control)
discount = 0.8 ** wp.float(horizon_length - step - 1) / wp.float(horizon_length) ** 2.0
pos_weight = 1000.0
altitude_weight = 100.0
control_weight = 0.05
vel_weight = 0.1
upright_weight = 10.0
total_weight = pos_weight + altitude_weight + control_weight + vel_weight + upright_weight
wp.atomic_add(
cost,
env_id,
(
pos_cost * pos_weight
+ altitude_cost * altitude_weight
+ control_cost * control_weight
+ vel_cost * vel_weight
+ upright_cost * upright_weight
)
* (weighting / total_weight)
* discount,
)
@wp.kernel
def collision_cost(
body_q: wp.array(dtype=wp.transform),
obstacle_ids: wp.array(dtype=int, ndim=2),
shape_X_bs: wp.array(dtype=wp.transform),
geo: wp.sim.ModelShapeGeometry,
margin: float,
weighting: float,
cost: wp.array(dtype=wp.float32),
):
env_id, obs_id = wp.tid()
shape_index = obstacle_ids[env_id, obs_id]
px = wp.transform_get_translation(body_q[env_id])
X_bs = shape_X_bs[shape_index]
# transform particle position to shape local space
x_local = wp.transform_point(wp.transform_inverse(X_bs), px)
# geo description
geo_type = geo.type[shape_index]
geo_scale = geo.scale[shape_index]
# evaluate shape sdf
d = 1e6
if geo_type == wp.sim.GEO_SPHERE:
d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
elif geo_type == wp.sim.GEO_BOX:
d = box_sdf(geo_scale, x_local)
elif geo_type == wp.sim.GEO_CAPSULE:
d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
elif geo_type == wp.sim.GEO_CYLINDER:
d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
elif geo_type == wp.sim.GEO_CONE:
d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
elif geo_type == wp.sim.GEO_MESH:
mesh = geo.source[shape_index]
min_scale = wp.min(geo_scale)
max_dist = margin / min_scale
d = mesh_sdf(mesh, wp.cw_div(x_local, geo_scale), max_dist)
d *= min_scale # TODO fix this, mesh scaling needs to be handled properly
elif 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)
elif geo_type == wp.sim.GEO_PLANE:
d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
d = wp.max(d, 0.0)
if d < margin:
c = margin - d
wp.atomic_add(cost, env_id, weighting * c)
@wp.kernel
def enforce_control_limits(
control_limits: wp.array(dtype=float, ndim=2),
control_points: wp.array(dtype=float, ndim=3),
):
env_id, t_id, control_id = wp.tid()
lo, hi = control_limits[control_id, 0], control_limits[control_id, 1]
control_points[env_id, t_id, control_id] = wp.clamp(control_points[env_id, t_id, control_id], lo, hi)
@wp.kernel
def pick_best_trajectory(
rollout_trajectories: wp.array(dtype=float, ndim=3),
lowest_cost_id: int,
best_traj: wp.array(dtype=float, ndim=3),
):
t_id, control_id = wp.tid()
best_traj[0, t_id, control_id] = rollout_trajectories[lowest_cost_id, t_id, control_id]
@wp.kernel
def interpolate_control_linear(
control_points: wp.array(dtype=float, ndim=3),
control_dofs: wp.array(dtype=int),
control_gains: wp.array(dtype=float),
t: float,
torque_dim: int,
torques: wp.array(dtype=float),
):
env_id, control_id = wp.tid()
t_id = int(t)
frac = t - wp.floor(t)
control_left = control_points[env_id, t_id, control_id]
control_right = control_points[env_id, t_id + 1, control_id]
torque_id = env_id * torque_dim + control_dofs[control_id]
action = control_left * (1.0 - frac) + control_right * frac
torques[torque_id] = action * control_gains[control_id]
@wp.kernel
def compute_prop_wrenches(
props: wp.array(dtype=Propeller),
controls: wp.array(dtype=float),
body_q: wp.array(dtype=wp.transform),
body_com: wp.array(dtype=wp.vec3),
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
prop = props[tid]
control = controls[tid]
tf = body_q[prop.body]
dir = wp.transform_vector(tf, prop.dir)
force = dir * prop.max_thrust * control
torque = dir * prop.max_torque * control * prop.turning_direction
moment_arm = wp.transform_point(tf, prop.pos) - wp.transform_point(tf, body_com[prop.body])
torque += wp.cross(moment_arm, force)
# Apply angular damping.
torque *= 0.8
wp.atomic_add(body_f, prop.body, wp.spatial_vector(torque, force))
def define_propeller(
drone: int,
pos: wp.vec3,
fps: float,
thrust: float = 0.109919,
power: float = 0.040164,
diameter: float = 0.2286,
height: float = 0.01,
max_rpm: float = 6396.667,
turning_direction: float = 1.0,
):
# Air density at sea level.
air_density = 1.225 # kg / m^3
rps = max_rpm / fps
max_speed = rps * wp.TAU # radians / sec
rps_square = rps**2
prop = Propeller()
prop.body = drone
prop.pos = pos
prop.dir = wp.vec3(0.0, 1.0, 0.0)
prop.thrust = thrust
prop.power = power
prop.diameter = diameter
prop.height = height
prop.max_rpm = max_rpm
prop.max_thrust = thrust * air_density * rps_square * diameter**4
prop.max_torque = power * air_density * rps_square * diameter**5 / wp.TAU
prop.turning_direction = turning_direction
prop.max_speed_square = max_speed**2
return prop
class Drone:
def __init__(
self,
name: str,
fps: float,
trajectory_shape: Tuple[int, int],
variation_count: int = 1,
size: float = 1.0,
requires_grad: bool = False,
state_count: Optional[int] = None,
) -> None:
self.variation_count = variation_count
self.requires_grad = requires_grad
# Current tick of the simulation, including substeps.
self.sim_tick = 0
# Initialize the helper to build a physics scene.
builder = wp.sim.ModelBuilder()
builder.rigid_contact_margin = 0.05
# Initialize the rigid bodies, propellers, and colliders.
props = []
colliders = []
crossbar_length = size
crossbar_height = size * 0.05
crossbar_width = size * 0.05
carbon_fiber_density = 1750.0 # kg / m^3
for i in range(variation_count):
# Register the drone as a rigid body in the simulation model.
body = builder.add_body(name=f"{name}_{i}")
# Define the shapes making up the drone's rigid body.
builder.add_shape_box(
body,
hx=crossbar_length,
hy=crossbar_height,
hz=crossbar_width,
density=carbon_fiber_density,
collision_group=i,
)
builder.add_shape_box(
body,
hx=crossbar_width,
hy=crossbar_height,
hz=crossbar_length,
density=carbon_fiber_density,
collision_group=i,
)
# Initialize the propellers.
props.extend(
(
define_propeller(
body,
wp.vec3(crossbar_length, 0.0, 0.0),
fps,
turning_direction=-1.0,
),
define_propeller(
body,
wp.vec3(-crossbar_length, 0.0, 0.0),
fps,
turning_direction=1.0,
),
define_propeller(
body,
wp.vec3(0.0, 0.0, crossbar_length),
fps,
turning_direction=1.0,
),
define_propeller(
body,
wp.vec3(0.0, 0.0, -crossbar_length),
fps,
turning_direction=-1.0,
),
),
)
# Initialize the colliders.
colliders.append(
(
builder.add_shape_capsule(
-1,
pos=(0.5, 2.0, 0.5),
radius=0.15,
half_height=2.0,
collision_group=i,
),
),
)
self.props = wp.array(props, dtype=Propeller)
self.colliders = wp.array(colliders, dtype=int)
# Build the model and set-up its properties.
self.model = builder.finalize(requires_grad=requires_grad)
self.model.ground = False
# Initialize the required simulation states.
if requires_grad:
self.states = tuple(self.model.state() for _ in range(state_count + 1))
self.controls = tuple(self.model.control() for _ in range(state_count))
else:
# When only running a forward simulation, we don't need to store
# the history of the states at each step, instead we use double
# buffering to represent the previous and next states.
self.states = [self.model.state(), self.model.state()]
self.controls = (self.model.control(),)
# create array for the propeller controls
for control in self.controls:
control.prop_controls = wp.zeros(len(self.props), dtype=float, requires_grad=requires_grad)
# Define the trajectories as arrays of control points.
# The point data has an additional item to support linear interpolation.
self.trajectories = wp.zeros(
(variation_count, trajectory_shape[0], trajectory_shape[1]),
dtype=float,
requires_grad=requires_grad,
)
# Store some miscellaneous info.
self.body_count = len(builder.body_q)
self.collider_count = self.colliders.shape[1]
self.collision_radius = crossbar_length
@property
def state(self) -> wp.sim.State:
return self.states[self.sim_tick if self.requires_grad else 0]
@property
def next_state(self) -> wp.sim.State:
return self.states[self.sim_tick + 1 if self.requires_grad else 1]
@property
def control(self) -> wp.sim.Control:
return self.controls[min(len(self.controls) - 1, self.sim_tick) if self.requires_grad else 0]
class Example:
def __init__(
self,
stage_path="example_drone.usd",
verbose=False,
render_rollouts=False,
drone_path=DEFAULT_DRONE_PATH,
num_frames=360,
num_rollouts=16,
headless=True,
) -> None:
# Number of frames per second.
self.fps = 60
# Duration of the simulation in number of frames.
self.num_frames = num_frames
# Number of simulation substeps to take per step.
self.sim_substep_count = 1
# Delta time between each simulation substep.
self.frame_dt = 1.0 / self.fps
# Delta time between each simulation substep.
self.sim_dt = self.frame_dt / self.sim_substep_count
# Frame number used for simulation and rendering.
self.frame = 0
# Targets positions that the drone will try to reach in turn.
self.targets = (
wp.vec3(0.0, 0.5, 1.0),
wp.vec3(1.0, 0.5, 0.0),
)
# Define the index of the active target.
# We start with -1 since it'll be incremented on the first frame.
self.target_idx = -1
# use a Warp array to store the current target so that we can assign
# a new target to it while retaining the original CUDA graph.
self.current_target = wp.array([self.targets[self.target_idx + 1]], dtype=wp.vec3)
# Number of steps to run at each frame for the optimisation pass.
self.optim_step_count = 20
# Time steps between control points.
self.control_point_step = 10
# Number of control horizon points to interpolate between.
self.control_point_count = 3
self.control_point_data_count = self.control_point_count + 1
self.control_dofs = wp.array((0, 1, 2, 3), dtype=int)
self.control_dim = len(self.control_dofs)
self.control_gains = wp.array((0.8,) * self.control_dim, dtype=float)
self.control_limits = wp.array(((0.1, 1.0),) * self.control_dim, dtype=float)
drone_size = 0.2
# Declare the reference drone.
self.drone = Drone(
"drone",
self.fps,
(self.control_point_data_count, self.control_dim),
size=drone_size,
)
# Declare the drone's rollouts.
# These allow to run parallel simulations in order to find the best
# trajectory at each control point.
self.rollout_count = num_rollouts
self.rollout_step_count = self.control_point_step * self.control_point_count
self.rollouts = Drone(
"rollout",
self.fps,
(self.control_point_data_count, self.control_dim),
variation_count=self.rollout_count,
size=drone_size,
requires_grad=True,
state_count=self.rollout_step_count * self.sim_substep_count,
)
self.seed = wp.zeros(1, dtype=int)
self.rollout_costs = wp.zeros(self.rollout_count, dtype=float, requires_grad=True)
# Use the Euler integrator for stepping through the simulation.
self.integrator = wp.sim.SemiImplicitIntegrator()
self.optimizer = wp.optim.SGD(
[self.rollouts.trajectories.flatten()],
lr=1e-2,
nesterov=False,
momentum=0.0,
)
self.tape = None
if stage_path:
if not headless:
self.renderer = wp.sim.render.SimRendererOpenGL(self.drone.model, stage_path, fps=self.fps)
else:
# Helper to render the physics scene as a USD file.
self.renderer = wp.sim.render.SimRenderer(self.drone.model, stage_path, fps=self.fps)
if isinstance(self.renderer, warp.sim.render.SimRendererUsd):
from pxr import UsdGeom
# Remove the default drone geometries.
drone_root_prim = self.renderer.stage.GetPrimAtPath("/root/body_0_drone_0")
for prim in drone_root_prim.GetChildren():
self.renderer.stage.RemovePrim(prim.GetPath())
# Add a reference to the drone geometry.
drone_prim = self.renderer.stage.OverridePrim(f"{drone_root_prim.GetPath()}/crazyflie")
drone_prim.GetReferences().AddReference(drone_path)
drone_xform = UsdGeom.Xform(drone_prim)
drone_xform.AddTranslateOp().Set((0.0, -0.05, 0.0))
drone_xform.AddRotateYOp().Set(45.0)
drone_xform.AddScaleOp().Set((drone_size * 20.0,) * 3)
# Get the propellers to spin
for turning_direction in ("cw", "ccw"):
spin = 100.0 * 360.0 * self.num_frames / self.fps
spin = spin if turning_direction == "ccw" else -spin
for side in ("back", "front"):
prop_prim = self.renderer.stage.OverridePrim(
f"{drone_prim.GetPath()}/propeller_{turning_direction}_{side}"
)
prop_xform = UsdGeom.Xform(prop_prim)
rot = prop_xform.AddRotateYOp()
rot.Set(0.0, 0.0)
rot.Set(spin, self.num_frames)
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
self.optim_graph = None
self.render_rollouts = render_rollouts
self.verbose = verbose
def update_drone(self, drone: Drone) -> None:
drone.state.clear_forces()
wp.launch(
interpolate_control_linear,
dim=(
drone.variation_count,
self.control_dim,
),
inputs=(
drone.trajectories,
self.control_dofs,
self.control_gains,
drone.sim_tick / (self.sim_substep_count * self.control_point_step),
self.control_dim,
),
outputs=(drone.control.prop_controls,),
)
wp.launch(
compute_prop_wrenches,
dim=len(drone.props),
inputs=(
drone.props,
drone.control.prop_controls,
drone.state.body_q,
drone.model.body_com,
),
outputs=(drone.state.body_f,),
)
self.integrator.simulate(
drone.model,
drone.state,
drone.next_state,
self.sim_dt,
drone.control,
)
drone.sim_tick += 1
def forward(self):
# Evaluate the rollouts with their costs.
self.rollouts.sim_tick = 0
self.rollout_costs.zero_()
wp.launch(
replicate_states,
dim=self.rollout_count,
inputs=(
self.drone.state.body_q,
self.drone.state.body_qd,
self.drone.body_count,
),
outputs=(
self.rollouts.state.body_q,
self.rollouts.state.body_qd,
),
)
for i in range(self.rollout_step_count):
for _ in range(self.sim_substep_count):
self.update_drone(self.rollouts)
wp.launch(
drone_cost,
dim=self.rollout_count,
inputs=(
self.rollouts.state.body_q,
self.rollouts.state.body_qd,
self.current_target,
self.rollouts.control.prop_controls,
i,
self.rollout_step_count,
1e3,
),
outputs=(self.rollout_costs,),
)
wp.launch(
collision_cost,
dim=(
self.rollout_count,
self.rollouts.collider_count,
),
inputs=(
self.rollouts.state.body_q,
self.rollouts.colliders,
self.rollouts.model.shape_transform,
self.rollouts.model.shape_geo,
self.rollouts.collision_radius,
1e4,
),
outputs=(self.rollout_costs,),
)
def step_optimizer(self):
if self.optim_graph is None:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.rollout_costs.grad.fill_(1.0)
self.tape.backward()
else:
wp.capture_launch(self.optim_graph)
self.optimizer.step([self.rollouts.trajectories.grad.flatten()])
# Enforce limits on the control points.
wp.launch(
enforce_control_limits,
dim=self.rollouts.trajectories.shape,
inputs=(self.control_limits,),
outputs=(self.rollouts.trajectories,),
)
self.tape.zero()
def step(self):
if self.frame % int((self.num_frames / len(self.targets))) == 0:
if self.verbose:
print(f"Choosing new flight target: {self.target_idx+1}")
self.target_idx += 1
self.target_idx %= len(self.targets)
# Assign the new target to the current target array.
self.current_target.assign([self.targets[self.target_idx]])
if self.use_cuda_graph and self.optim_graph is None:
with wp.ScopedCapture() as capture:
self.tape = wp.Tape()
with self.tape:
self.forward()
self.rollout_costs.grad.fill_(1.0)
self.tape.backward()
self.optim_graph = capture.graph
# Sample control waypoints around the nominal trajectory.
noise_scale = 0.15
wp.launch(
sample_gaussian,
dim=(
self.rollouts.trajectories.shape[0] - 1,
self.rollouts.trajectories.shape[1],
self.rollouts.trajectories.shape[2],
),
inputs=(
self.drone.trajectories,
noise_scale,
self.control_point_data_count,
self.control_dim,
self.control_limits,
self.seed,
),
outputs=(self.rollouts.trajectories,),
)
wp.launch(
increment_seed,
dim=1,
inputs=(),
outputs=(self.seed,),
)
for _ in range(self.optim_step_count):
self.step_optimizer()
# Pick the best trajectory.
wp.synchronize()
lowest_cost_id = np.argmin(self.rollout_costs.numpy())
wp.launch(
pick_best_trajectory,
dim=(
self.control_point_data_count,
self.control_dim,
),
inputs=(
self.rollouts.trajectories,
lowest_cost_id,
),
outputs=(self.drone.trajectories,),
)
self.rollouts.trajectories[-1].assign(self.drone.trajectories[0])
# Simulate the drone.
self.drone.sim_tick = 0
for _ in range(self.sim_substep_count):
self.update_drone(self.drone)
# Swap the drone's states.
(self.drone.states[0], self.drone.states[1]) = (self.drone.states[1], self.drone.states[0])
def render(self):
if self.renderer is None:
return
self.renderer.begin_frame(self.frame / self.fps)
self.renderer.render(self.drone.state)
# Render a sphere as the current target.
self.renderer.render_sphere(
"target",
self.targets[self.target_idx],
wp.quat_identity(),
0.05,
color=(1.0, 0.0, 0.0),
)
# Render the rollout trajectories.
if self.render_rollouts:
costs = self.rollout_costs.numpy()
positions = np.array([x.body_q.numpy()[:, :3] for x in self.rollouts.states])
min_cost = np.min(costs)
max_cost = np.max(costs)
for i in range(self.rollout_count):
# Flip colors, so red means best trajectory, blue worst.
color = wp.render.bourke_color_map(-max_cost, -min_cost, -costs[i])
self.renderer.render_line_strip(
name=f"rollout_{i}",
vertices=positions[:, i],
color=color,
radius=0.001,
)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_drone.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=360, help="Total number of frames.")
parser.add_argument("--num_rollouts", type=int, default=16, help="Number of drone rollouts.")
parser.add_argument(
"--drone_path",
type=str,
default=os.path.join(warp.examples.get_asset_directory(), "crazyflie.usd"),
help="Path to the USD file to use as the reference for the drone prim in the output stage.",
)
parser.add_argument("--render_rollouts", action="store_true", help="Add rollout trajectories to the output stage.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
stage_path=args.stage_path,
verbose=args.verbose,
render_rollouts=args.render_rollouts,
drone_path=args.drone_path,
num_frames=args.num_frames,
num_rollouts=args.num_rollouts,
headless=args.headless,
)
for _i in range(args.num_frames):
example.step()
example.render()
example.frame += 1
loss = np.min(example.rollout_costs.numpy())
print(f"[{example.frame:3d}/{example.num_frames}] loss={loss:.8f}")
if example.renderer is not None:
example.renderer.save()
| 29,179 | Python | 32.812283 | 120 | 0.557764 |
NVIDIA/warp/warp/examples/optim/example_inverse_kinematics.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.
###########################################################################
# Example Sim Rigid Kinematics
#
# Tests rigid body forward and backwards kinematics through the
# wp.sim.eval_ik() and wp.sim.eval_fk() methods.
#
###########################################################################
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
TARGET = wp.constant(wp.vec3(2.0, 1.0, 0.0))
@wp.kernel
def compute_loss(body_q: wp.array(dtype=wp.transform), body_index: int, loss: wp.array(dtype=float)):
x = wp.transform_get_translation(body_q[body_index])
delta = x - TARGET
loss[0] = wp.dot(delta, delta)
@wp.kernel
def step_kernel(x: wp.array(dtype=float), grad: wp.array(dtype=float), alpha: float):
tid = wp.tid()
# gradient descent step
x[tid] = x[tid] - grad[tid] * alpha
class Example:
def __init__(self, stage_path="example_inverse_kinematics.usd", verbose=False):
self.verbose = verbose
fps = 60
self.frame_dt = 1.0 / fps
self.render_time = 0.0
builder = wp.sim.ModelBuilder()
builder.add_articulation()
chain_length = 4
chain_width = 1.0
for i in range(chain_length):
if i == 0:
parent = -1
parent_joint_xform = wp.transform([0.0, 0.0, 0.0], wp.quat_identity())
else:
parent = builder.joint_count - 1
parent_joint_xform = wp.transform([chain_width, 0.0, 0.0], wp.quat_identity())
# create body
b = builder.add_body(origin=wp.transform([i, 0.0, 0.0], wp.quat_identity()), armature=0.1)
builder.add_joint_revolute(
parent=parent,
child=b,
axis=(0.0, 0.0, 1.0),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
limit_lower=-np.deg2rad(60.0),
limit_upper=np.deg2rad(60.0),
target_ke=0.0,
target_kd=0.0,
limit_ke=30.0,
limit_kd=30.0,
)
if i == chain_length - 1:
# create end effector
builder.add_shape_sphere(pos=wp.vec3(0.0, 0.0, 0.0), radius=0.1, density=10.0, body=b)
else:
# create shape
builder.add_shape_box(
pos=wp.vec3(chain_width * 0.5, 0.0, 0.0), hx=chain_width * 0.5, hy=0.1, hz=0.1, density=10.0, body=b
)
# finalize model
self.model = builder.finalize()
self.model.ground = False
self.state = self.model.state()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=50.0)
else:
self.renderer = None
# optimization variables
self.loss = wp.zeros(1, dtype=float)
self.model.joint_q.requires_grad = True
self.state.body_q.requires_grad = True
self.loss.requires_grad = True
self.train_rate = 0.01
def forward(self):
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state)
wp.launch(compute_loss, dim=1, inputs=[self.state.body_q, len(self.state.body_q) - 1, self.loss])
def step(self):
with wp.ScopedTimer("step"):
tape = wp.Tape()
with tape:
self.forward()
tape.backward(loss=self.loss)
if self.verbose:
print(f"loss: {self.loss}")
print(f"joint_grad: {tape.gradients[self.model.joint_q]}")
# gradient descent
wp.launch(
step_kernel,
dim=len(self.model.joint_q),
inputs=[self.model.joint_q, tape.gradients[self.model.joint_q], self.train_rate],
)
# zero gradients
tape.zero()
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.state)
self.renderer.render_sphere(
name="target", pos=TARGET, rot=wp.quat_identity(), radius=0.1, color=(1.0, 0.0, 0.0)
)
self.renderer.end_frame()
self.render_time += self.frame_dt
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_inverse_kinematics.usd",
help="Path to the output USD file.",
)
parser.add_argument("--train_iters", type=int, default=512, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, verbose=args.verbose)
for _ in range(args.train_iters):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 5,816 | Python | 32.24 | 120 | 0.565509 |
NVIDIA/warp/warp/examples/optim/example_walker.py | # Copyright (c) 2024 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.
###########################################################################
# Example Walker
#
# Trains a tetrahedral mesh quadruped to run. Feeds 8 time-varying input
# phases as inputs into a single layer fully connected network with a tanh
# activation function. Interprets the output of the network as tet
# activations, which are fed into the wp.sim soft mesh model. This is
# simulated forward in time and then evaluated based on the center of mass
# momentum of the mesh.
#
###########################################################################
import math
import os
import numpy as np
from pxr import Usd, UsdGeom
import warp as wp
import warp.examples
import warp.optim
import warp.sim
import warp.sim.render
@wp.kernel
def loss_kernel(com: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float)):
tid = wp.tid()
vx = com[tid][0]
vy = com[tid][1]
vz = com[tid][2]
delta = wp.sqrt(vx * vx) + wp.sqrt(vy * vy) - vz
wp.atomic_add(loss, 0, delta)
@wp.kernel
def com_kernel(velocities: wp.array(dtype=wp.vec3), n: int, com: wp.array(dtype=wp.vec3)):
tid = wp.tid()
v = velocities[tid]
a = v / wp.float32(n)
wp.atomic_add(com, 0, a)
@wp.kernel
def compute_phases(phases: wp.array(dtype=float), sim_time: float):
tid = wp.tid()
phases[tid] = wp.sin(phase_freq * sim_time + wp.float32(tid) * phase_step)
@wp.kernel
def activation_function(tet_activations: wp.array(dtype=float), activation_inputs: wp.array(dtype=float)):
tid = wp.tid()
activation = wp.tanh(activation_inputs[tid])
tet_activations[tid] = activation_strength * activation
phase_count = 8
phase_step = wp.constant((2.0 * math.pi) / phase_count)
phase_freq = wp.constant(5.0)
activation_strength = wp.constant(0.3)
class Example:
def __init__(self, stage_path="example_walker.usd", verbose=False, num_frames=300):
self.verbose = verbose
fps = 60
self.frame_dt = 1.0 / fps
self.num_frames = num_frames
self.sim_substeps = 80
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.iter = 0
self.train_rate = 0.025
self.phase_count = phase_count
self.render_time = 0.0
# bear
asset_stage = Usd.Stage.Open(os.path.join(warp.examples.get_asset_directory(), "bear.usd"))
geom = UsdGeom.Mesh(asset_stage.GetPrimAtPath("/root/bear"))
points = geom.GetPointsAttr().Get()
xform = geom.ComputeLocalToWorldTransform(0.0)
for i in range(len(points)):
points[i] = xform.Transform(points[i])
self.points = [wp.vec3(point) for point in points]
self.tet_indices = geom.GetPrim().GetAttribute("tetraIndices").Get()
# sim model
builder = wp.sim.ModelBuilder()
builder.add_soft_mesh(
pos=wp.vec3(0.0, 0.5, 0.0),
rot=wp.quat_identity(),
scale=1.0,
vel=wp.vec3(0.0, 0.0, 0.0),
vertices=self.points,
indices=self.tet_indices,
density=1.0,
k_mu=2000.0,
k_lambda=2000.0,
k_damp=2.0,
tri_ke=0.0,
tri_ka=1e-8,
tri_kd=0.0,
tri_drag=0.0,
tri_lift=0.0,
)
# finalize model
self.model = builder.finalize(requires_grad=True)
self.control = self.model.control()
self.model.soft_contact_ke = 2.0e3
self.model.soft_contact_kd = 0.1
self.model.soft_contact_kf = 10.0
self.model.soft_contact_mu = 0.7
radii = wp.zeros(self.model.particle_count, dtype=float)
radii.fill_(0.05)
self.model.particle_radius = radii
self.model.ground = True
# allocate sim states
self.states = []
for _i in range(self.num_frames * self.sim_substeps + 1):
self.states.append(self.model.state(requires_grad=True))
# initialize the integrator.
self.integrator = wp.sim.SemiImplicitIntegrator()
# model input
self.phases = []
for _i in range(self.num_frames):
self.phases.append(wp.zeros(self.phase_count, dtype=float, requires_grad=True))
# single layer linear network
rng = np.random.default_rng(42)
k = 1.0 / self.phase_count
weights = rng.uniform(-np.sqrt(k), np.sqrt(k), (self.model.tet_count, self.phase_count))
self.weights = wp.array(weights, dtype=float, requires_grad=True)
self.bias = wp.zeros(self.model.tet_count, dtype=float, requires_grad=True)
# tanh activation layer
self.activation_inputs = []
self.tet_activations = []
for _i in range(self.num_frames):
self.activation_inputs.append(wp.zeros(self.model.tet_count, dtype=float, requires_grad=True))
self.tet_activations.append(wp.zeros(self.model.tet_count, dtype=float, requires_grad=True))
# optimization
self.loss = wp.zeros(1, dtype=float, requires_grad=True)
self.coms = []
for _i in range(self.num_frames):
self.coms.append(wp.zeros(1, dtype=wp.vec3, requires_grad=True))
self.optimizer = warp.optim.Adam([self.weights.flatten()], lr=self.train_rate)
# rendering
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path)
else:
self.renderer = None
# capture forward/backward passes
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.tape = wp.Tape()
with self.tape:
for i in range(self.num_frames):
self.forward(i)
self.tape.backward(self.loss)
self.graph = capture.graph
def forward(self, frame):
with wp.ScopedTimer("network", active=self.verbose):
# build sinusoidal input phases
wp.launch(kernel=compute_phases, dim=self.phase_count, inputs=[self.phases[frame], self.sim_time])
# fully connected, linear transformation layer
wp.matmul(
self.weights,
self.phases[frame].reshape((self.phase_count, 1)),
self.bias.reshape((self.model.tet_count, 1)),
self.activation_inputs[frame].reshape((self.model.tet_count, 1)),
)
# tanh activation function
wp.launch(
kernel=activation_function,
dim=self.model.tet_count,
inputs=[self.tet_activations[frame], self.activation_inputs[frame]],
)
self.control.tet_activations = self.tet_activations[frame]
with wp.ScopedTimer("simulate", active=self.verbose):
# run simulation loop
for i in range(self.sim_substeps):
self.states[frame * self.sim_substeps + i].clear_forces()
self.integrator.simulate(
self.model,
self.states[frame * self.sim_substeps + i],
self.states[frame * self.sim_substeps + i + 1],
self.sim_dt,
self.control,
)
self.sim_time += self.sim_dt
with wp.ScopedTimer("loss", active=self.verbose):
# compute center of mass velocity
wp.launch(
com_kernel,
dim=self.model.particle_count,
inputs=[
self.states[(frame + 1) * self.sim_substeps].particle_qd,
self.model.particle_count,
self.coms[frame],
],
outputs=[],
)
# compute loss
wp.launch(loss_kernel, dim=1, inputs=[self.coms[frame], self.loss], outputs=[])
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.tape = wp.Tape()
with self.tape:
for i in range(self.num_frames):
self.forward(i)
self.tape.backward(self.loss)
# optimization
x = self.weights.grad.flatten()
self.optimizer.step([x])
loss = self.loss.numpy()
if self.verbose:
print(f"Iteration {self.iter}: {loss}")
# reset sim
self.sim_time = 0.0
self.states[0] = self.model.state(requires_grad=True)
# clear grads and zero arrays for next iteration
self.tape.zero()
self.loss.zero_()
for i in range(self.num_frames):
self.coms[i].zero_()
self.iter += 1
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
for i in range(self.num_frames + 1):
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.states[i * self.sim_substeps])
self.renderer.end_frame()
self.render_time += self.frame_dt
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_walker.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames per training iteration.")
parser.add_argument("--train_iters", type=int, default=30, help="Total number of training iterations.")
parser.add_argument("--verbose", action="store_true", help="Print out additional status messages during execution.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, verbose=args.verbose, num_frames=args.num_frames)
for _ in range(args.train_iters):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 10,731 | Python | 34.186885 | 120 | 0.581772 |
NVIDIA/warp/warp/examples/sim/example_granular_collision_sdf.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.
###########################################################################
# Example Sim Granular Collision SDF
#
# Shows how to set up a particle-based granular material model using the
# wp.sim.ModelBuilder(). This version shows how to create collision geometry
# objects from SDFs.
#
# Note: requires a CUDA-capable device
###########################################################################
import math
import os
import numpy as np
import warp as wp
import warp.examples
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_granular_collision_sdf.usd"):
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 64
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.radius = 0.1
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = self.radius
builder.add_particle_grid(
dim_x=16,
dim_y=32,
dim_z=16,
cell_x=self.radius * 2.0,
cell_y=self.radius * 2.0,
cell_z=self.radius * 2.0,
pos=wp.vec3(0.0, 20.0, 0.0),
rot=wp.quat_identity(),
vel=wp.vec3(2.0, 0.0, 0.0),
mass=0.1,
jitter=self.radius * 0.1,
)
with open(os.path.join(warp.examples.get_asset_directory(), "rocks.nvdb"), "rb") as rock_file:
rock_vdb = wp.Volume.load_from_nvdb(rock_file.read())
rock_sdf = wp.sim.SDF(rock_vdb)
builder.add_shape_sdf(
ke=1.0e4,
kd=1000.0,
kf=1000.0,
mu=0.5,
sdf=rock_sdf,
body=-1,
pos=wp.vec3(0.0, 0.0, 0.0),
rot=wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), -0.5 * math.pi),
scale=wp.vec3(0.01, 0.01, 0.01),
)
mins = np.array([-3.0, -3.0, -3.0])
voxel_size = 0.2
maxs = np.array([3.0, 3.0, 3.0])
nums = np.ceil((maxs - mins) / (voxel_size)).astype(dtype=int)
center = np.array([0.0, 0.0, 0.0])
rad = 2.5
sphere_sdf_np = np.zeros(tuple(nums))
for x in range(nums[0]):
for y in range(nums[1]):
for z in range(nums[2]):
pos = mins + voxel_size * np.array([x, y, z])
dis = np.linalg.norm(pos - center)
sphere_sdf_np[x, y, z] = dis - rad
sphere_vdb = wp.Volume.load_from_numpy(sphere_sdf_np, mins, voxel_size, rad + 3.0 * voxel_size)
sphere_sdf = wp.sim.SDF(sphere_vdb)
self.sphere_pos = wp.vec3(3.0, 15.0, 0.0)
self.sphere_scale = 1.0
self.sphere_radius = rad
builder.add_shape_sdf(
ke=1.0e4,
kd=1000.0,
kf=1000.0,
mu=0.5,
sdf=sphere_sdf,
body=-1,
pos=self.sphere_pos,
scale=wp.vec3(self.sphere_scale, self.sphere_scale, self.sphere_scale),
)
self.model = builder.finalize()
self.model.particle_kf = 25.0
self.model.soft_contact_kd = 100.0
self.model.soft_contact_kf *= 2.0
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.integrator = wp.sim.SemiImplicitIntegrator()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=20.0)
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
wp.sim.collide(self.model, self.state_0)
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step"):
self.model.particle_grid.build(self.state_0.particle_q, self.radius * 2.0)
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
# Note the extra wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), math.pi) is because .usd is oriented differently from .nvdb
self.renderer.render_ref(
name="collision",
path=os.path.join(warp.examples.get_asset_directory(), "rocks.usd"),
pos=wp.vec3(0.0, 0.0, 0.0),
rot=wp.quat(0.0, 0.0, 0.0, 1.0),
scale=wp.vec3(0.01, 0.01, 0.01),
)
self.renderer.render_sphere(
name="sphere",
pos=self.sphere_pos,
radius=self.sphere_scale * self.sphere_radius,
rot=wp.quat(0.0, 0.0, 0.0, 1.0),
)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_granular_collision_sdf.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=400, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 6,556 | Python | 32.454081 | 136 | 0.548353 |
NVIDIA/warp/warp/examples/sim/example_granular.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.
###########################################################################
# Example Sim Granular
#
# Shows how to set up a particle-based granular material model using the
# wp.sim.ModelBuilder().
#
###########################################################################
import warp as wp
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_granular.usd"):
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 64
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.radius = 0.1
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = self.radius
builder.add_particle_grid(
dim_x=16,
dim_y=32,
dim_z=16,
cell_x=self.radius * 2.0,
cell_y=self.radius * 2.0,
cell_z=self.radius * 2.0,
pos=wp.vec3(0.0, 1.0, 0.0),
rot=wp.quat_identity(),
vel=wp.vec3(5.0, 0.0, 0.0),
mass=0.1,
jitter=self.radius * 0.1,
)
self.model = builder.finalize()
self.model.particle_kf = 25.0
self.model.soft_contact_kd = 100.0
self.model.soft_contact_kf *= 2.0
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.integrator = wp.sim.SemiImplicitIntegrator()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=20.0)
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step"):
self.model.particle_grid.build(self.state_0.particle_q, self.radius * 2.0)
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_granular.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=400, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 3,907 | Python | 30.772357 | 101 | 0.576145 |
NVIDIA/warp/warp/examples/sim/example_cloth.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.
###########################################################################
# Example Sim Cloth
#
# Shows a simulation of an FEM cloth model colliding against a static
# rigid body mesh using the wp.sim.ModelBuilder().
#
###########################################################################
import math
import os
from enum import Enum
import numpy as np
from pxr import Usd, UsdGeom
import warp as wp
import warp.examples
import warp.sim
import warp.sim.render
class IntegratorType(Enum):
EULER = "euler"
XPBD = "xpbd"
def __str__(self):
return self.value
class Example:
def __init__(
self, stage_path="example_cloth.usd", integrator: IntegratorType = IntegratorType.EULER, height=32, width=64
):
self.integrator_type = integrator
self.sim_height = height
self.sim_width = width
fps = 60
self.sim_substeps = 32
self.frame_dt = 1.0 / fps
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.profiler = {}
builder = wp.sim.ModelBuilder()
if self.integrator_type == IntegratorType.EULER:
builder.add_cloth_grid(
pos=wp.vec3(0.0, 4.0, 0.0),
rot=wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), math.pi * 0.5),
vel=wp.vec3(0.0, 0.0, 0.0),
dim_x=self.sim_width,
dim_y=self.sim_height,
cell_x=0.1,
cell_y=0.1,
mass=0.1,
fix_left=True,
tri_ke=1.0e3,
tri_ka=1.0e3,
tri_kd=1.0e1,
)
else:
builder.add_cloth_grid(
pos=wp.vec3(0.0, 4.0, 0.0),
rot=wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), math.pi * 0.5),
vel=wp.vec3(0.0, 0.0, 0.0),
dim_x=self.sim_width,
dim_y=self.sim_height,
cell_x=0.1,
cell_y=0.1,
mass=0.1,
fix_left=True,
edge_ke=1.0e2,
add_springs=True,
spring_ke=1.0e3,
spring_kd=0.0,
)
usd_stage = Usd.Stage.Open(os.path.join(warp.examples.get_asset_directory(), "bunny.usd"))
usd_geom = UsdGeom.Mesh(usd_stage.GetPrimAtPath("/root/bunny"))
mesh_points = np.array(usd_geom.GetPointsAttr().Get())
mesh_indices = np.array(usd_geom.GetFaceVertexIndicesAttr().Get())
mesh = wp.sim.Mesh(mesh_points, mesh_indices)
builder.add_shape_mesh(
body=-1,
mesh=mesh,
pos=wp.vec3(1.0, 0.0, 1.0),
rot=wp.quat_from_axis_angle(wp.vec3(0.0, 1.0, 0.0), math.pi * 0.5),
scale=wp.vec3(2.0, 2.0, 2.0),
ke=1.0e2,
kd=1.0e2,
kf=1.0e1,
)
if self.integrator_type == IntegratorType.EULER:
self.integrator = wp.sim.SemiImplicitIntegrator()
else:
self.integrator = wp.sim.XPBDIntegrator(iterations=1)
self.model = builder.finalize()
self.model.ground = True
self.model.soft_contact_ke = 1.0e4
self.model.soft_contact_kd = 1.0e2
self.state_0 = self.model.state()
self.state_1 = self.model.state()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=40.0)
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
wp.sim.collide(self.model, self.state_0)
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step", dict=self.profiler):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_cloth.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
parser.add_argument(
"--integrator",
help="Type of integrator",
type=IntegratorType,
choices=list(IntegratorType),
default=IntegratorType.EULER,
)
parser.add_argument("--width", type=int, default=64, help="Cloth resolution in x.")
parser.add_argument("--height", type=int, default=32, help="Cloth resolution in y.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, integrator=args.integrator, height=args.height, width=args.width)
for _i in range(args.num_frames):
example.step()
example.render()
frame_times = example.profiler["step"]
print("\nAverage frame sim time: {:.2f} ms".format(sum(frame_times) / len(frame_times)))
if example.renderer:
example.renderer.save()
| 6,390 | Python | 31.774359 | 119 | 0.561815 |
NVIDIA/warp/warp/examples/sim/example_soft_body.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.
###########################################################################
# Example Sim Neo-Hookean
#
# Shows a simulation of an Neo-Hookean FEM beam being twisted through a
# 180 degree rotation.
#
###########################################################################
import math
import warp as wp
import warp.sim
import warp.sim.render
@wp.kernel
def twist_points(
rest: wp.array(dtype=wp.vec3), points: wp.array(dtype=wp.vec3), mass: wp.array(dtype=float), xform: wp.transform
):
tid = wp.tid()
r = rest[tid]
p = points[tid]
m = mass[tid]
# twist the top layer of particles in the beam
if m == 0 and p[1] != 0.0:
points[tid] = wp.transform_point(xform, r)
@wp.kernel
def compute_volume(points: wp.array(dtype=wp.vec3), indices: wp.array2d(dtype=int), volume: wp.array(dtype=float)):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
x0 = points[i]
x1 = points[j]
x2 = points[k]
x3 = points[l]
x10 = x1 - x0
x20 = x2 - x0
x30 = x3 - x0
v = wp.dot(x10, wp.cross(x20, x30)) / 6.0
wp.atomic_add(volume, 0, v)
class Example:
def __init__(self, stage_path="example_soft_body.usd", num_frames=300):
self.sim_substeps = 64
self.num_frames = num_frames
fps = 60
sim_duration = self.num_frames / fps
self.frame_dt = 1.0 / fps
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.lift_speed = 2.5 / sim_duration * 2.0 # from Smith et al.
self.rot_speed = math.pi / sim_duration
builder = wp.sim.ModelBuilder()
cell_dim = 15
cell_size = 2.0 / cell_dim
center = cell_size * cell_dim * 0.5
builder.add_soft_grid(
pos=wp.vec3(-center, 0.0, -center),
rot=wp.quat_identity(),
vel=wp.vec3(0.0, 0.0, 0.0),
dim_x=cell_dim,
dim_y=cell_dim,
dim_z=cell_dim,
cell_x=cell_size,
cell_y=cell_size,
cell_z=cell_size,
density=100.0,
fix_bottom=True,
fix_top=True,
k_mu=1000.0,
k_lambda=5000.0,
k_damp=0.0,
)
self.model = builder.finalize()
self.model.ground = False
self.model.gravity[1] = 0.0
self.integrator = wp.sim.SemiImplicitIntegrator()
self.rest = self.model.state()
self.rest_vol = (cell_size * cell_dim) ** 3
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.volume = wp.zeros(1, dtype=wp.float32)
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=20.0)
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
self.state_1.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step"):
xform = wp.transform(
(0.0, self.lift_speed * self.sim_time, 0.0),
wp.quat_from_axis_angle(wp.vec3(0.0, 1.0, 0.0), self.rot_speed * self.sim_time),
)
wp.launch(
kernel=twist_points,
dim=len(self.state_0.particle_q),
inputs=[self.rest.particle_q, self.state_0.particle_q, self.model.particle_mass, xform],
)
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.volume.zero_()
wp.launch(
kernel=compute_volume,
dim=self.model.tet_count,
inputs=[self.state_0.particle_q, self.model.tet_indices, self.volume],
)
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_soft_body.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, num_frames=args.num_frames)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 5,820 | Python | 29.798942 | 116 | 0.561684 |
NVIDIA/warp/warp/examples/sim/example_quadruped.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.
###########################################################################
# Example Sim Quadruped
#
# Shows how to set up a simulation of a rigid-body quadruped articulation
# from a URDF using the wp.sim.ModelBuilder().
# Note this example does not include a trained policy.
#
###########################################################################
import math
import os
import numpy as np
import warp as wp
import warp.examples
import warp.sim
import warp.sim.render
# Taken from env/environment.py
def compute_env_offsets(num_envs, env_offset=(5.0, 0.0, 5.0), up_axis="Y"):
# compute positional offsets per environment
env_offset = np.array(env_offset)
nonzeros = np.nonzero(env_offset)[0]
num_dim = nonzeros.shape[0]
if num_dim > 0:
side_length = int(np.ceil(num_envs ** (1.0 / num_dim)))
env_offsets = []
else:
env_offsets = np.zeros((num_envs, 3))
if num_dim == 1:
for i in range(num_envs):
env_offsets.append(i * env_offset)
elif num_dim == 2:
for i in range(num_envs):
d0 = i // side_length
d1 = i % side_length
offset = np.zeros(3)
offset[nonzeros[0]] = d0 * env_offset[nonzeros[0]]
offset[nonzeros[1]] = d1 * env_offset[nonzeros[1]]
env_offsets.append(offset)
elif num_dim == 3:
for i in range(num_envs):
d0 = i // (side_length * side_length)
d1 = (i // side_length) % side_length
d2 = i % side_length
offset = np.zeros(3)
offset[0] = d0 * env_offset[0]
offset[1] = d1 * env_offset[1]
offset[2] = d2 * env_offset[2]
env_offsets.append(offset)
env_offsets = np.array(env_offsets)
min_offsets = np.min(env_offsets, axis=0)
correction = min_offsets + (np.max(env_offsets, axis=0) - min_offsets) / 2.0
if isinstance(up_axis, str):
up_axis = "XYZ".index(up_axis.upper())
correction[up_axis] = 0.0 # ensure the envs are not shifted below the ground plane
env_offsets -= correction
return env_offsets
class Example:
def __init__(self, stage_path="example_quadruped.usd", num_envs=8):
articulation_builder = wp.sim.ModelBuilder()
wp.sim.parse_urdf(
os.path.join(warp.examples.get_asset_directory(), "quadruped.urdf"),
articulation_builder,
xform=wp.transform([0.0, 0.7, 0.0], wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), -math.pi * 0.5)),
floating=True,
density=1000,
armature=0.01,
stiffness=200,
damping=1,
contact_ke=1.0e4,
contact_kd=1.0e2,
contact_kf=1.0e2,
contact_mu=1.0,
limit_ke=1.0e4,
limit_kd=1.0e1,
)
builder = wp.sim.ModelBuilder()
self.sim_time = 0.0
fps = 100
self.frame_dt = 1.0 / fps
self.sim_substeps = 5
self.sim_dt = self.frame_dt / self.sim_substeps
self.num_envs = num_envs
offsets = compute_env_offsets(self.num_envs)
for i in range(self.num_envs):
builder.add_builder(articulation_builder, xform=wp.transform(offsets[i], wp.quat_identity()))
builder.joint_q[-12:] = [0.2, 0.4, -0.6, -0.2, -0.4, 0.6, -0.2, 0.4, -0.6, 0.2, -0.4, 0.6]
builder.joint_axis_mode = [wp.sim.JOINT_MODE_TARGET_POSITION] * len(builder.joint_axis_mode)
builder.joint_act[-12:] = [0.2, 0.4, -0.6, -0.2, -0.4, 0.6, -0.2, 0.4, -0.6, 0.2, -0.4, 0.6]
np.set_printoptions(suppress=True)
# finalize model
self.model = builder.finalize()
self.model.ground = True
# self.model.gravity = 0.0
self.model.joint_attach_ke = 16000.0
self.model.joint_attach_kd = 200.0
# self.integrator = wp.sim.XPBDIntegrator()
# self.integrator = wp.sim.SemiImplicitIntegrator()
self.integrator = wp.sim.FeatherstoneIntegrator(self.model)
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path)
else:
self.renderer = None
self.state_0 = self.model.state()
self.state_1 = self.model.state()
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state_0)
# simulate() allocates memory via a clone, so we can't use graph capture if the device does not support mempools
self.use_cuda_graph = wp.get_device().is_cuda and wp.is_mempool_enabled(wp.get_device())
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
else:
self.graph = None
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
wp.sim.collide(self.model, self.state_0)
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.state_0, self.state_1 = self.state_1, self.state_0
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_quadruped.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
parser.add_argument("--num_envs", type=int, default=8, help="Total number of simulated environments.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, num_envs=args.num_envs)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 6,970 | Python | 35.307291 | 120 | 0.585366 |
NVIDIA/warp/warp/examples/sim/example_cartpole.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.
###########################################################################
# Example Sim Cartpole
#
# Shows how to set up a simulation of a rigid-body cartpole articulation
# from a URDF using the wp.sim.ModelBuilder().
# Note this example does not include a trained policy.
#
###########################################################################
import math
import os
import numpy as np
import warp as wp
import warp.examples
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_cartpole.usd", num_envs=8):
builder = wp.sim.ModelBuilder()
self.num_envs = num_envs
articulation_builder = wp.sim.ModelBuilder()
wp.sim.parse_urdf(
os.path.join(warp.examples.get_asset_directory(), "cartpole.urdf"),
articulation_builder,
xform=wp.transform(wp.vec3(), wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), -math.pi * 0.5)),
floating=False,
density=100,
armature=0.1,
stiffness=0.0,
damping=0.0,
limit_ke=1.0e4,
limit_kd=1.0e1,
enable_self_collisions=False,
)
builder = wp.sim.ModelBuilder()
self.sim_time = 0.0
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 10
self.sim_dt = self.frame_dt / self.sim_substeps
for i in range(self.num_envs):
builder.add_builder(
articulation_builder, xform=wp.transform(np.array((i * 2.0, 4.0, 0.0)), wp.quat_identity())
)
# joint initial positions
builder.joint_q[-3:] = [0.0, 0.3, 0.0]
# finalize model
self.model = builder.finalize()
self.model.ground = False
self.model.joint_attach_ke = 1600.0
self.model.joint_attach_kd = 20.0
self.integrator = wp.sim.SemiImplicitIntegrator()
self.renderer = None
if stage_path:
self.renderer = wp.sim.render.SimRenderer(path=stage_path, model=self.model, scaling=15.0)
self.state = self.model.state()
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state)
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
self.state.clear_forces()
self.state = self.integrator.simulate(self.model, self.state, self.state, self.sim_dt)
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_cartpole.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=1200, help="Total number of frames.")
parser.add_argument("--num_envs", type=int, default=8, help="Total number of simulated environments.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, num_envs=args.num_envs)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 4,496 | Python | 31.586956 | 107 | 0.594973 |
NVIDIA/warp/warp/examples/sim/example_rigid_gyroscopic.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.
###########################################################################
# Example Sim Rigid Gyroscopic
#
# Demonstrates the Dzhanibekov effect where rigid bodies will tumble in
# free space due to unstable axes of rotation.
#
###########################################################################
import warp as wp
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_rigid_gyroscopic.usd"):
fps = 120
self.sim_dt = 1.0 / fps
self.sim_time = 0.0
self.scale = 0.5
builder = wp.sim.ModelBuilder()
b = builder.add_body()
# axis shape
builder.add_shape_box(
pos=wp.vec3(0.3 * self.scale, 0.0, 0.0),
hx=0.25 * self.scale,
hy=0.1 * self.scale,
hz=0.1 * self.scale,
density=100.0,
body=b,
)
# tip shape
builder.add_shape_box(
pos=wp.vec3(0.0, 0.0, 0.0),
hx=0.05 * self.scale,
hy=0.2 * self.scale,
hz=1.0 * self.scale,
density=100.0,
body=b,
)
# initial spin
builder.body_qd[0] = (25.0, 0.01, 0.01, 0.0, 0.0, 0.0)
builder.gravity = 0.0
self.model = builder.finalize()
self.model.ground = False
self.integrator = wp.sim.SemiImplicitIntegrator()
self.state = self.model.state()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=100.0)
else:
self.renderer = None
def step(self):
with wp.ScopedTimer("step"):
self.state.clear_forces()
self.state = self.integrator.simulate(self.model, self.state, self.state, self.sim_dt)
self.sim_time += self.sim_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_rigid_gyroscopic.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=2000, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 3,348 | Python | 30.009259 | 101 | 0.57497 |
NVIDIA/warp/warp/examples/sim/example_rigid_contact.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.
###########################################################################
# Example Sim Rigid Contact
#
# Shows how to set up free rigid bodies with different shape types falling
# and colliding against each other and the ground using wp.sim.ModelBuilder().
#
###########################################################################
import math
import os
import numpy as np
from pxr import Usd, UsdGeom
import warp as wp
import warp.examples
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_rigid_contact.usd"):
builder = wp.sim.ModelBuilder()
self.sim_time = 0.0
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 10
self.sim_dt = self.frame_dt / self.sim_substeps
self.num_bodies = 8
self.scale = 0.8
self.ke = 1.0e5
self.kd = 250.0
self.kf = 500.0
# boxes
for i in range(self.num_bodies):
b = builder.add_body(origin=wp.transform((i, 1.0, 0.0), wp.quat_identity()))
builder.add_shape_box(
pos=wp.vec3(0.0, 0.0, 0.0),
hx=0.5 * self.scale,
hy=0.2 * self.scale,
hz=0.2 * self.scale,
body=i,
ke=self.ke,
kd=self.kd,
kf=self.kf,
)
# spheres
for i in range(self.num_bodies):
b = builder.add_body(origin=wp.transform((i, 1.0, 2.0), wp.quat_identity()))
builder.add_shape_sphere(
pos=wp.vec3(0.0, 0.0, 0.0), radius=0.25 * self.scale, body=b, ke=self.ke, kd=self.kd, kf=self.kf
)
# capsules
for i in range(self.num_bodies):
b = builder.add_body(origin=wp.transform((i, 1.0, 6.0), wp.quat_identity()))
builder.add_shape_capsule(
pos=wp.vec3(0.0, 0.0, 0.0),
radius=0.25 * self.scale,
half_height=self.scale * 0.5,
up_axis=0,
body=b,
ke=self.ke,
kd=self.kd,
kf=self.kf,
)
# initial spin
for i in range(len(builder.body_qd)):
builder.body_qd[i] = (0.0, 2.0, 10.0, 0.0, 0.0, 0.0)
# meshes
bunny = self.load_mesh(os.path.join(warp.examples.get_asset_directory(), "bunny.usd"), "/root/bunny")
for i in range(self.num_bodies):
b = builder.add_body(
origin=wp.transform(
(i * 0.5 * self.scale, 1.0 + i * 1.7 * self.scale, 4.0 + i * 0.5 * self.scale),
wp.quat_from_axis_angle(wp.vec3(0.0, 1.0, 0.0), math.pi * 0.1 * i),
)
)
builder.add_shape_mesh(
body=b,
mesh=bunny,
pos=wp.vec3(0.0, 0.0, 0.0),
scale=wp.vec3(self.scale, self.scale, self.scale),
ke=self.ke,
kd=self.kd,
kf=self.kf,
density=1e3,
)
# finalize model
self.model = builder.finalize()
self.model.ground = True
self.integrator = wp.sim.SemiImplicitIntegrator()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=0.5)
else:
self.renderer = None
self.state_0 = self.model.state()
self.state_1 = self.model.state()
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state_0)
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def load_mesh(self, filename, path):
asset_stage = Usd.Stage.Open(filename)
mesh_geom = UsdGeom.Mesh(asset_stage.GetPrimAtPath(path))
points = np.array(mesh_geom.GetPointsAttr().Get())
indices = np.array(mesh_geom.GetFaceVertexIndicesAttr().Get()).flatten()
return wp.sim.Mesh(points, indices)
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
wp.sim.collide(self.model, self.state_0)
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.state_0, self.state_1 = self.state_1, self.state_0
def step(self):
with wp.ScopedTimer("step", active=True):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render", active=True):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_rigid_contact.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 6,213 | Python | 32.053191 | 112 | 0.54724 |
NVIDIA/warp/warp/examples/sim/example_jacobian_ik.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.
###########################################################################
# Example Jacobian
#
# Demonstrates how to compute the Jacobian of a multi-valued function.
# Here, we use the simulation of a cartpole to differentiate
# through the kinematics function. We instantiate multiple copies of the
# cartpole and compute the Jacobian of the state of each cartpole in parallel
# in order to perform inverse kinematics via Jacobian transpose.
#
###########################################################################
import math
import os
import numpy as np
import warp as wp
import warp.examples
import warp.sim
import warp.sim.render
@wp.kernel
def compute_endeffector_position(
body_q: wp.array(dtype=wp.transform),
num_links: int,
ee_link_index: int,
ee_link_offset: wp.vec3,
ee_pos: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
ee_pos[tid] = wp.transform_point(body_q[tid * num_links + ee_link_index], ee_link_offset)
class Example:
def __init__(self, stage_path="example_jacobian_ik.usd", num_envs=10):
builder = wp.sim.ModelBuilder()
self.num_envs = num_envs
fps = 60
self.frame_dt = 1.0 / fps
self.render_time = 0.0
# step size to use for the IK updates
self.step_size = 0.1
articulation_builder = wp.sim.ModelBuilder()
wp.sim.parse_urdf(
os.path.join(warp.examples.get_asset_directory(), "cartpole.urdf"),
articulation_builder,
xform=wp.transform_identity(),
floating=False,
)
builder = wp.sim.ModelBuilder()
self.num_links = len(articulation_builder.joint_type)
# use the last link as the end-effector
self.ee_link_index = self.num_links - 1
self.ee_link_offset = wp.vec3(0.0, 0.0, 1.0)
self.dof = len(articulation_builder.joint_q)
self.target_origin = []
for i in range(self.num_envs):
builder.add_builder(
articulation_builder,
xform=wp.transform(
wp.vec3(i * 2.0, 4.0, 0.0), wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), -math.pi * 0.5)
),
)
self.target_origin.append((i * 2.0, 4.0, 0.0))
# joint initial positions
builder.joint_q[-3:] = np.random.uniform(-0.5, 0.5, size=3)
self.target_origin = np.array(self.target_origin)
# finalize model
self.model = builder.finalize()
self.model.ground = True
self.model.joint_q.requires_grad = True
self.model.body_q.requires_grad = True
self.model.joint_attach_ke = 1600.0
self.model.joint_attach_kd = 20.0
self.integrator = wp.sim.SemiImplicitIntegrator()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path)
else:
self.renderer = None
self.ee_pos = wp.zeros(self.num_envs, dtype=wp.vec3, requires_grad=True)
self.state = self.model.state(requires_grad=True)
self.targets = self.target_origin.copy()
self.profiler = {}
def compute_ee_position(self):
# computes the end-effector position from the current joint angles
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state)
wp.launch(
compute_endeffector_position,
dim=self.num_envs,
inputs=[self.state.body_q, self.num_links, self.ee_link_index, self.ee_link_offset],
outputs=[self.ee_pos],
)
return self.ee_pos
def compute_jacobian(self):
# our function has 3 outputs (EE position), so we need a 3xN jacobian per environment
jacobians = np.empty((self.num_envs, 3, self.dof), dtype=np.float32)
tape = wp.Tape()
with tape:
self.compute_ee_position()
for output_index in range(3):
# select which row of the Jacobian we want to compute
select_index = np.zeros(3)
select_index[output_index] = 1.0
e = wp.array(np.tile(select_index, self.num_envs), dtype=wp.vec3)
tape.backward(grads={self.ee_pos: e})
q_grad_i = tape.gradients[self.model.joint_q]
jacobians[:, output_index, :] = q_grad_i.numpy().reshape(self.num_envs, self.dof)
tape.zero()
return jacobians
def compute_fd_jacobian(self, eps=1e-4):
jacobians = np.zeros((self.num_envs, 3, self.dof), dtype=np.float32)
q0 = self.model.joint_q.numpy().copy()
for e in range(self.num_envs):
for i in range(self.dof):
q = q0.copy()
q[e * self.dof + i] += eps
self.model.joint_q.assign(q)
self.compute_ee_position()
f_plus = self.ee_pos.numpy()[e].copy()
q[e * self.dof + i] -= 2 * eps
self.model.joint_q.assign(q)
self.compute_ee_position()
f_minus = self.ee_pos.numpy()[e].copy()
jacobians[e, :, i] = (f_plus - f_minus) / (2 * eps)
return jacobians
def step(self):
with wp.ScopedTimer("jacobian", print=False, active=True, dict=self.profiler):
# compute jacobian
jacobians = self.compute_jacobian()
# compute error
self.ee_pos_np = self.compute_ee_position().numpy()
error = self.targets - self.ee_pos_np
self.error = error.reshape(self.num_envs, 3, 1)
# compute Jacobian transpose update
delta_q = np.matmul(jacobians.transpose(0, 2, 1), self.error)
self.model.joint_q = wp.array(
self.model.joint_q.numpy() + self.step_size * delta_q.flatten(),
dtype=wp.float32,
requires_grad=True,
)
def render(self):
if self.renderer is None:
return
self.renderer.begin_frame(self.render_time)
self.renderer.render(self.state)
self.renderer.render_points("targets", self.targets, radius=0.05)
self.renderer.render_points("ee_pos", self.ee_pos_np, radius=0.05)
self.renderer.end_frame()
self.render_time += self.frame_dt
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_jacobian_ik.usd",
help="Path to the output USD file.",
)
parser.add_argument("--train_iters", type=int, default=50, help="Total number of training iterations.")
parser.add_argument("--num_envs", type=int, default=10, help="Total number of simulated environments.")
parser.add_argument(
"--num_rollouts",
type=int,
default=5,
help="Total number of rollouts. In each rollout, a new set of target points is resampled for all environments.",
)
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, num_envs=args.num_envs)
print("autodiff:")
print(example.compute_jacobian())
print("finite diff:")
print(example.compute_fd_jacobian())
for _ in range(args.num_rollouts):
# select new random target points for all envs
example.targets = example.target_origin.copy()
example.targets[:, 1:] += np.random.uniform(-0.5, 0.5, size=(example.num_envs, 2))
for iter in range(args.train_iters):
example.step()
example.render()
print("iter:", iter, "error:", example.error.mean())
if example.renderer:
example.renderer.save()
avg_time = np.array(example.profiler["jacobian"]).mean()
avg_steps_second = 1000.0 * float(example.num_envs) / avg_time
print(f"envs: {example.num_envs} steps/second {avg_steps_second} avg_time {avg_time}")
| 8,562 | Python | 35.438298 | 120 | 0.596239 |
NVIDIA/warp/warp/examples/sim/example_rigid_soft_contact.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.
###########################################################################
# Example Sim Rigid FEM
#
# Shows how to set up a rigid sphere colliding with an FEM beam
# using wp.sim.ModelBuilder().
#
###########################################################################
import warp as wp
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_rigid_soft_contact.usd"):
self.sim_width = 8
self.sim_height = 8
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 32
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.sim_iterations = 1
self.sim_relaxation = 1.0
self.profiler = {}
builder = wp.sim.ModelBuilder()
builder.default_particle_radius = 0.01
builder.add_soft_grid(
pos=wp.vec3(0.0, 0.0, 0.0),
rot=wp.quat_identity(),
vel=wp.vec3(0.0, 0.0, 0.0),
dim_x=20,
dim_y=10,
dim_z=10,
cell_x=0.1,
cell_y=0.1,
cell_z=0.1,
density=100.0,
k_mu=50000.0,
k_lambda=20000.0,
k_damp=0.0,
)
b = builder.add_body(origin=wp.transform((0.5, 2.5, 0.5), wp.quat_identity()))
builder.add_shape_sphere(body=b, radius=0.75, density=100.0)
self.model = builder.finalize()
self.model.ground = True
self.model.soft_contact_ke = 1.0e3
self.model.soft_contact_kd = 0.0
self.model.soft_contact_kf = 1.0e3
self.integrator = wp.sim.SemiImplicitIntegrator()
self.state_0 = self.model.state()
self.state_1 = self.model.state()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=1.0)
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _s in range(self.sim_substeps):
wp.sim.collide(self.model, self.state_0)
self.state_0.clear_forces()
self.state_1.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step", dict=self.profiler):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_rigid_soft_contact.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 4,264 | Python | 31.067669 | 101 | 0.570826 |
NVIDIA/warp/warp/examples/sim/example_rigid_force.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.
###########################################################################
# Example Sim Rigid Force
#
# Shows how to apply an external force (torque) to a rigid body causing
# it to roll.
#
###########################################################################
import warp as wp
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_rigid_force.usd", use_opengl=False):
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 5
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
builder = wp.sim.ModelBuilder()
b = builder.add_body(origin=wp.transform((0.0, 10.0, 0.0), wp.quat_identity()))
builder.add_shape_box(body=b, hx=1.0, hy=1.0, hz=1.0, density=100.0)
self.model = builder.finalize()
self.model.ground = True
self.integrator = wp.sim.XPBDIntegrator()
self.state_0 = self.model.state()
self.state_1 = self.model.state()
if use_opengl:
self.renderer = wp.sim.render.SimRendererOpenGL(self.model, stage_path)
elif stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path)
else:
self.renderer = None
# simulate() allocates memory via a clone, so we can't use graph capture if the device does not support mempools
self.use_cuda_graph = wp.get_device().is_cuda and wp.is_mempool_enabled(wp.get_device())
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
wp.sim.collide(self.model, self.state_0)
self.state_0.clear_forces()
self.state_1.clear_forces()
self.state_0.body_f.assign(
[
[0.0, 0.0, -7000.0, 0.0, 0.0, 0.0],
]
)
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_rigid_force.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
parser.add_argument(
"--opengl",
action="store_true",
help="Open an interactive window to play back animations in real time. Ignores --num_frames if used.",
)
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path, use_opengl=args.opengl)
if args.opengl:
while example.renderer.is_running():
example.step()
example.render()
else:
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 4,295 | Python | 33.095238 | 120 | 0.582305 |
NVIDIA/warp/warp/examples/sim/example_rigid_chain.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.
###########################################################################
# Example Sim Rigid Chain
#
# Shows how to set up a chain of rigid bodies connected by different joint
# types using wp.sim.ModelBuilder(). There is one chain for each joint
# type, including fixed joints which act as a flexible beam.
#
###########################################################################
import numpy as np
import warp as wp
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_rigid_chain.usd"):
self.chain_length = 8
self.chain_width = 1.0
self.chain_types = [
wp.sim.JOINT_REVOLUTE,
wp.sim.JOINT_FIXED,
wp.sim.JOINT_BALL,
wp.sim.JOINT_UNIVERSAL,
wp.sim.JOINT_COMPOUND,
]
builder = wp.sim.ModelBuilder()
self.sim_time = 0.0
fps = 100
self.frame_dt = 1.0 / fps
self.sim_substeps = 10
self.sim_dt = self.frame_dt / self.sim_substeps
for c, t in enumerate(self.chain_types):
# start a new articulation
builder.add_articulation()
for i in range(self.chain_length):
if i == 0:
parent = -1
parent_joint_xform = wp.transform([0.0, 0.0, c * 1.0], wp.quat_identity())
else:
parent = builder.joint_count - 1
parent_joint_xform = wp.transform([self.chain_width, 0.0, 0.0], wp.quat_identity())
# create body
b = builder.add_body(origin=wp.transform([i, 0.0, c * 1.0], wp.quat_identity()), armature=0.1)
# create shape
builder.add_shape_box(
pos=wp.vec3(self.chain_width * 0.5, 0.0, 0.0),
hx=self.chain_width * 0.5,
hy=0.1,
hz=0.1,
density=10.0,
body=b,
)
joint_type = t
if joint_type == wp.sim.JOINT_REVOLUTE:
joint_limit_lower = -np.deg2rad(60.0)
joint_limit_upper = np.deg2rad(60.0)
builder.add_joint_revolute(
parent=parent,
child=b,
axis=(0.0, 0.0, 1.0),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
limit_lower=joint_limit_lower,
limit_upper=joint_limit_upper,
target_ke=0.0,
target_kd=0.0,
limit_ke=1e5,
limit_kd=1.0,
)
elif joint_type == wp.sim.JOINT_UNIVERSAL:
builder.add_joint_universal(
parent=parent,
child=b,
axis_0=wp.sim.JointAxis((1.0, 0.0, 0.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
axis_1=wp.sim.JointAxis((0.0, 0.0, 1.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
elif joint_type == wp.sim.JOINT_BALL:
builder.add_joint_ball(
parent=parent,
child=b,
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
elif joint_type == wp.sim.JOINT_FIXED:
builder.add_joint_fixed(
parent=parent,
child=b,
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
elif joint_type == wp.sim.JOINT_COMPOUND:
builder.add_joint_compound(
parent=parent,
child=b,
axis_0=wp.sim.JointAxis((1.0, 0.0, 0.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
axis_1=wp.sim.JointAxis((0.0, 1.0, 0.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
axis_2=wp.sim.JointAxis((0.0, 0.0, 1.0), -np.deg2rad(60.0), np.deg2rad(60.0)),
parent_xform=parent_joint_xform,
child_xform=wp.transform_identity(),
)
self.model = builder.finalize()
self.model.ground = False
self.integrator = wp.sim.FeatherstoneIntegrator(self.model)
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=20.0)
else:
self.renderer = None
self.state_0 = self.model.state()
self.state_1 = self.model.state()
wp.sim.eval_fk(self.model, self.model.joint_q, self.model.joint_qd, None, self.state_0)
# simulate() allocates memory via a clone, so we can't use graph capture if the device does not support mempools
self.use_cuda_graph = wp.get_device().is_cuda and wp.is_mempool_enabled(wp.get_device())
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
self.state_0, self.state_1 = self.state_1, self.state_0
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_rigid_chain.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=500, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 7,420 | Python | 36.862245 | 120 | 0.512264 |
NVIDIA/warp/warp/examples/sim/example_particle_chain.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.
###########################################################################
# Example Sim Particle Chain
#
# Shows how to set up a simple chain of particles connected by springs
# using wp.sim.ModelBuilder().
#
###########################################################################
import math
import warp as wp
import warp.sim
import warp.sim.render
class Example:
def __init__(self, stage_path="example_particle_chain.usd"):
self.sim_width = 64
self.sim_height = 32
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 10
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
builder = wp.sim.ModelBuilder()
# anchor
builder.add_particle(wp.vec3(0.0, 1.0, 0.0), wp.vec3(0.0, 0.0, 0.0), 0.0)
# chain
for i in range(1, 10):
radius = math.sqrt(i) * 0.2
mass = math.pi * radius * radius * radius
builder.add_particle(wp.vec3(i, 1.0, 0.0), wp.vec3(0.0, 0.0, 0.0), mass, radius=radius)
builder.add_spring(i - 1, i, 1.0e6, 0.0, 0)
self.model = builder.finalize()
self.model.ground = False
self.integrator = wp.sim.XPBDIntegrator()
self.state_0 = self.model.state()
self.state_1 = self.model.state()
if stage_path:
self.renderer = wp.sim.render.SimRenderer(self.model, stage_path, scaling=15.0)
else:
self.renderer = None
# simulate() allocates memory via a clone, so we can't use graph capture if the device does not support mempools
self.use_cuda_graph = wp.get_device().is_cuda and wp.is_mempool_enabled(wp.get_device())
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
self.state_0.clear_forces()
self.state_1.clear_forces()
self.integrator.simulate(self.model, self.state_0, self.state_1, self.sim_dt)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
def step(self):
with wp.ScopedTimer("step"):
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_particle_chain.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=300, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 3,932 | Python | 32.615384 | 120 | 0.589268 |
NVIDIA/warp/warp/examples/fem/bsr_utils.py | from typing import Any, Optional, Tuple, Union
import warp as wp
import warp.types
from warp.optim.linear import LinearOperator, aslinearoperator, preconditioner
from warp.sparse import BsrMatrix, bsr_get_diag, bsr_mv, bsr_transposed, bsr_zeros
def bsr_to_scipy(matrix: BsrMatrix) -> "scipy.sparse.bsr_array": # noqa: F821
try:
from scipy.sparse import bsr_array, csr_array
except ImportError:
# WAR for older scipy
from scipy.sparse import bsr_matrix as bsr_array
from scipy.sparse import csr_matrix as csr_array
if matrix.block_shape == (1, 1):
return csr_array(
(
matrix.values.numpy().flatten()[: matrix.nnz],
matrix.columns.numpy()[: matrix.nnz],
matrix.offsets.numpy(),
),
shape=matrix.shape,
)
return bsr_array(
(
matrix.values.numpy().reshape((matrix.values.shape[0], *matrix.block_shape))[: matrix.nnz],
matrix.columns.numpy()[: matrix.nnz],
matrix.offsets.numpy(),
),
shape=matrix.shape,
)
def scipy_to_bsr(
sp: Union["scipy.sparse.bsr_array", "scipy.sparse.csr_array"], # noqa: F821
device=None,
dtype=None,
) -> BsrMatrix:
try:
from scipy.sparse import csr_array
except ImportError:
# WAR for older scipy
from scipy.sparse import csr_matrix as csr_array
if dtype is None:
dtype = warp.types.np_dtype_to_warp_type[sp.dtype]
sp.sort_indices()
if isinstance(sp, csr_array):
matrix = bsr_zeros(sp.shape[0], sp.shape[1], dtype, device=device)
else:
block_shape = sp.blocksize
block_type = wp.types.matrix(shape=block_shape, dtype=dtype)
matrix = bsr_zeros(
sp.shape[0] // block_shape[0],
sp.shape[1] // block_shape[1],
block_type,
device=device,
)
matrix.nnz = sp.nnz
matrix.values = wp.array(sp.data.flatten(), dtype=matrix.values.dtype, device=device)
matrix.columns = wp.array(sp.indices, dtype=matrix.columns.dtype, device=device)
matrix.offsets = wp.array(sp.indptr, dtype=matrix.offsets.dtype, device=device)
return matrix
def get_linear_solver_func(method_name: str):
from warp.optim.linear import bicgstab, cg, cr, gmres
if method_name == "bicgstab":
return bicgstab
if method_name == "gmres":
return gmres
if method_name == "cr":
return cr
return cg
def bsr_cg(
A: BsrMatrix,
x: wp.array,
b: wp.array,
max_iters: int = 0,
tol: float = 0.0001,
check_every=10,
use_diag_precond=True,
mv_routine=None,
quiet=False,
method: str = "cg",
) -> Tuple[float, int]:
"""Solves the linear system A x = b using an iterative solver, optionally with diagonal preconditioning
Args:
A: system left-hand side
x: result vector and initial guess
b: system right-hand-side
max_iters: maximum number of iterations to perform before aborting. If set to zero, equal to the system size.
tol: relative tolerance under which to stop the solve
check_every: number of iterations every which to evaluate the current residual norm to compare against tolerance
use_diag_precond: Whether to use diagonal preconditioning
mv_routine: Matrix-vector multiplication routine to use for multiplications with ``A``
quiet: if True, do not print iteration residuals
method: Iterative solver method to use, defaults to Conjugate Gradient
Returns:
Tuple (residual norm, iteration count)
"""
if mv_routine is None:
M = preconditioner(A, "diag") if use_diag_precond else None
else:
A = LinearOperator(A.shape, A.dtype, A.device, matvec=mv_routine)
M = None
func = get_linear_solver_func(method_name=method)
def print_callback(i, err, tol):
print(f"{func.__name__}: at iteration {i} error = \t {err} \t tol: {tol}")
callback = None if quiet else print_callback
end_iter, err, atol = func(
A=A,
b=b,
x=x,
maxiter=max_iters,
tol=tol,
check_every=check_every,
M=M,
callback=callback,
)
if not quiet:
res_str = "OK" if err <= atol else "TRUNCATED"
print(f"{func.__name__}: terminated after {end_iter} iterations with error = \t {err} ({res_str})")
return err, end_iter
class SaddleSystem(LinearOperator):
"""Builds a linear operator corresponding to the saddle-point linear system [A B^T; B 0]
If use_diag_precond` is ``True``, builds the corresponding diagonal preconditioner `[diag(A); diag(B diag(A)^-1 B^T)]`
"""
def __init__(
self,
A: BsrMatrix,
B: BsrMatrix,
Bt: Optional[BsrMatrix] = None,
use_diag_precond: bool = True,
):
if Bt is None:
Bt = bsr_transposed(B)
self._A = A
self._B = B
self._Bt = Bt
self._u_dtype = wp.vec(length=A.block_shape[0], dtype=A.scalar_type)
self._p_dtype = wp.vec(length=B.block_shape[0], dtype=B.scalar_type)
self._p_byte_offset = A.nrow * wp.types.type_size_in_bytes(self._u_dtype)
saddle_shape = (A.shape[0] + B.shape[0], A.shape[0] + B.shape[0])
super().__init__(saddle_shape, dtype=A.scalar_type, device=A.device, matvec=self._saddle_mv)
if use_diag_precond:
self._preconditioner = self._diag_preconditioner()
else:
self._preconditioner = None
def _diag_preconditioner(self):
A = self._A
B = self._B
M_u = preconditioner(A, "diag")
A_diag = bsr_get_diag(A)
schur_block_shape = (B.block_shape[0], B.block_shape[0])
schur_dtype = wp.mat(shape=schur_block_shape, dtype=B.scalar_type)
schur_inv_diag = wp.empty(dtype=schur_dtype, shape=B.nrow, device=self.device)
wp.launch(
_compute_schur_inverse_diagonal,
dim=B.nrow,
device=A.device,
inputs=[B.offsets, B.columns, B.values, A_diag, schur_inv_diag],
)
if schur_block_shape == (1, 1):
# Downcast 1x1 mats to scalars
schur_inv_diag = schur_inv_diag.view(dtype=B.scalar_type)
M_p = aslinearoperator(schur_inv_diag)
def precond_mv(x, y, z, alpha, beta):
x_u = self.u_slice(x)
x_p = self.p_slice(x)
y_u = self.u_slice(y)
y_p = self.p_slice(y)
z_u = self.u_slice(z)
z_p = self.p_slice(z)
M_u.matvec(x_u, y_u, z_u, alpha=alpha, beta=beta)
M_p.matvec(x_p, y_p, z_p, alpha=alpha, beta=beta)
return LinearOperator(
shape=self.shape,
dtype=self.dtype,
device=self.device,
matvec=precond_mv,
)
@property
def preconditioner(self):
return self._preconditioner
def u_slice(self, a: wp.array):
return wp.array(
ptr=a.ptr,
dtype=self._u_dtype,
shape=self._A.nrow,
strides=None,
device=a.device,
pinned=a.pinned,
copy=False,
)
def p_slice(self, a: wp.array):
return wp.array(
ptr=a.ptr + self._p_byte_offset,
dtype=self._p_dtype,
shape=self._B.nrow,
strides=None,
device=a.device,
pinned=a.pinned,
copy=False,
)
def _saddle_mv(self, x, y, z, alpha, beta):
x_u = self.u_slice(x)
x_p = self.p_slice(x)
z_u = self.u_slice(z)
z_p = self.p_slice(z)
if y.ptr != z.ptr and beta != 0.0:
wp.copy(src=y, dest=z)
bsr_mv(self._A, x_u, z_u, alpha=alpha, beta=beta)
bsr_mv(self._Bt, x_p, z_u, alpha=alpha, beta=1.0)
bsr_mv(self._B, x_u, z_p, alpha=alpha, beta=beta)
def bsr_solve_saddle(
saddle_system: SaddleSystem,
x_u: wp.array,
x_p: wp.array,
b_u: wp.array,
b_p: wp.array,
max_iters: int = 0,
tol: float = 0.0001,
check_every=10,
quiet=False,
method: str = "cg",
) -> Tuple[float, int]:
"""Solves the saddle-point linear system [A B^T; B 0] (x_u; x_p) = (b_u; b_p) using an iterative solver, optionally with diagonal preconditioning
Args:
saddle_system: Saddle point system
x_u: primal part of the result vector and initial guess
x_p: Lagrange multiplier part of the result vector and initial guess
b_u: primal left-hand-side
b_p: constraint left-hand-side
max_iters: maximum number of iterations to perform before aborting. If set to zero, equal to the system size.
tol: relative tolerance under which to stop the solve
check_every: number of iterations every which to evaluate the current residual norm to compare against tolerance
quiet: if True, do not print iteration residuals
method: Iterative solver method to use, defaults to BiCGSTAB
Returns:
Tuple (residual norm, iteration count)
"""
x = wp.empty(dtype=saddle_system.scalar_type, shape=saddle_system.shape[0], device=saddle_system.device)
b = wp.empty_like(x)
wp.copy(src=x_u, dest=saddle_system.u_slice(x))
wp.copy(src=x_p, dest=saddle_system.p_slice(x))
wp.copy(src=b_u, dest=saddle_system.u_slice(b))
wp.copy(src=b_p, dest=saddle_system.p_slice(b))
func = get_linear_solver_func(method_name=method)
def print_callback(i, err, tol):
print(f"{func.__name__}: at iteration {i} error = \t {err} \t tol: {tol}")
callback = None if quiet else print_callback
end_iter, err, atol = func(
A=saddle_system,
b=b,
x=x,
maxiter=max_iters,
tol=tol,
check_every=check_every,
M=saddle_system.preconditioner,
callback=callback,
)
if not quiet:
res_str = "OK" if err <= atol else "TRUNCATED"
print(f"{func.__name__}: terminated after {end_iter} iterations with absolute error = \t {err} ({res_str})")
wp.copy(dest=x_u, src=saddle_system.u_slice(x))
wp.copy(dest=x_p, src=saddle_system.p_slice(x))
return err, end_iter
@wp.kernel
def _compute_schur_inverse_diagonal(
B_offsets: wp.array(dtype=int),
B_indices: wp.array(dtype=int),
B_values: wp.array(dtype=Any),
A_diag: wp.array(dtype=Any),
P_diag: wp.array(dtype=Any),
):
row = wp.tid()
zero = P_diag.dtype(P_diag.dtype.dtype(0.0))
schur = zero
beg = B_offsets[row]
end = B_offsets[row + 1]
for b in range(beg, end):
B = B_values[b]
col = B_indices[b]
Ai = wp.inverse(A_diag[col])
S = B * Ai * wp.transpose(B)
schur += S
schur_diag = wp.get_diag(schur)
id_diag = type(schur_diag)(schur_diag.dtype(1.0))
inv_diag = wp.select(schur == zero, wp.cw_div(id_diag, schur_diag), id_diag)
P_diag[row] = wp.diag(inv_diag)
def invert_diagonal_bsr_mass_matrix(A: BsrMatrix):
"""Inverts each block of a block-diagonal mass matrix"""
scale = A.scalar_type(A.block_shape[0])
values = A.values
if not wp.types.type_is_matrix(values.dtype):
values = values.view(dtype=wp.mat(shape=(1, 1), dtype=A.scalar_type))
wp.launch(
kernel=_block_diagonal_mass_invert,
dim=A.nrow,
inputs=[values, scale],
device=values.device,
)
@wp.kernel
def _block_diagonal_mass_invert(values: wp.array(dtype=Any), scale: Any):
i = wp.tid()
values[i] = scale * values[i] / wp.ddot(values[i], values[i])
| 11,673 | Python | 29.802111 | 149 | 0.592136 |
NVIDIA/warp/warp/examples/fem/example_stokes_transfer.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.
###########################################################################
# Example Stokes Transfer
#
# This example computes a 2D weakly-compressible Stokes flow around
# a moving object, including:
# - defining active cells from a mask, and restricting the computation domain to those
# - utilizing the PicQuadrature to integrate over unstructured particles
###########################################################################
import math
import numpy as np
import warp as wp
import warp.fem as fem
from warp.fem.utils import array_axpy
from warp.sparse import bsr_axpy, bsr_mm, bsr_mv, bsr_transposed
from warp.utils import array_cast
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from plot_utils import Plot
@fem.integrand
def vel_from_particles_form(s: fem.Sample, particle_vel: wp.array(dtype=wp.vec2), v: fem.Field):
vel = particle_vel[s.qp_index]
return wp.dot(vel, v(s))
@fem.integrand
def viscosity_form(s: fem.Sample, u: fem.Field, v: fem.Field, nu: float):
return nu * wp.ddot(fem.D(u, s), fem.D(v, s))
@fem.integrand
def mass_form(
s: fem.Sample,
u: fem.Field,
v: fem.Field,
):
return wp.dot(u(s), v(s))
@fem.integrand
def scalar_mass_form(
s: fem.Sample,
p: fem.Field,
q: fem.Field,
):
return p(s) * q(s)
@fem.integrand
def div_form(
s: fem.Sample,
u: fem.Field,
q: fem.Field,
):
return q(s) * fem.div(u, s)
@fem.integrand
def cell_activity(s: fem.Sample, domain: fem.Domain, c1: wp.vec2, c2: wp.vec2, radius: float):
pos = domain(s)
if wp.length(pos - c1) < radius:
return 0.0
if wp.length(pos - c2) < radius:
return 0.0
return 1.0
@wp.kernel
def inverse_array_kernel(m: wp.array(dtype=wp.float64)):
m[wp.tid()] = wp.float64(1.0) / m[wp.tid()]
class Example:
def __init__(self, quiet=False, resolution=50):
self._quiet = quiet
self.res = resolution
self.cell_size = 1.0 / self.res
self.vel = 1.0
self.viscosity = 100.0
self.compliance = 0.01
self.bd_strength = 100000.0
geo = fem.Grid2D(res=wp.vec2i(self.res))
# Displacement boundary conditions are defined by two circles going in opposite directions
# Sample particles along those
circle_radius = 0.15
c1_center = wp.vec2(0.25, 0.5)
c2_center = wp.vec2(0.75, 0.5)
particles, particle_areas, particle_velocities = self._gen_particles(circle_radius, c1_center, c2_center)
# Disable cells that are interior to the circles
cell_space = fem.make_polynomial_space(geo, degree=0)
activity = cell_space.make_field()
fem.interpolate(
cell_activity,
dest=activity,
values={"c1": c1_center, "c2": c2_center, "radius": circle_radius - self.cell_size},
)
# Explicitly define the active geometry partition from those cells
self._active_partition = fem.ExplicitGeometryPartition(geo, wp.array(activity.dof_values.numpy(), dtype=int))
if not self._quiet:
print("Active cells:", self._active_partition.cell_count())
# Function spaces -- Q1 for vel, Q0 for pressure
u_space = fem.make_polynomial_space(geo, degree=1, dtype=wp.vec2)
p_space = fem.make_polynomial_space(geo, degree=0)
self._active_space_partition = fem.make_space_partition(
space=u_space, geometry_partition=self._active_partition
)
self._active_p_space_partition = fem.make_space_partition(
space=p_space, geometry_partition=self._active_partition
)
self._u_field = u_space.make_field()
self._p_field = p_space.make_field()
# Particle-based quadrature rule over active cells
domain = fem.Cells(geometry=self._active_partition)
self._pic_quadrature = fem.PicQuadrature(domain, particles, particle_areas)
self._particle_velocities = particle_velocities
self.renderer = Plot()
def step(self):
u_space = self._u_field.space
p_space = self._p_field.space
# Weakly-enforced boundary condition on particles
u_test = fem.make_test(space=u_space, space_partition=self._active_space_partition)
u_trial = fem.make_trial(space=u_space, space_partition=self._active_space_partition)
u_rhs = fem.integrate(
vel_from_particles_form,
quadrature=self._pic_quadrature,
fields={"v": u_test},
values={"particle_vel": self._particle_velocities},
output_dtype=wp.vec2d,
)
u_bd_matrix = fem.integrate(mass_form, quadrature=self._pic_quadrature, fields={"u": u_trial, "v": u_test})
# Viscosity
u_visc_matrix = fem.integrate(
viscosity_form,
fields={"u": u_trial, "v": u_test},
values={"nu": self.viscosity},
)
# Pressure-velocity coupling
p_test = fem.make_test(space=p_space, space_partition=self._active_p_space_partition)
p_trial = fem.make_trial(space=p_space, space_partition=self._active_p_space_partition)
div_matrix = fem.integrate(div_form, fields={"u": u_trial, "q": p_test})
inv_p_mass_matrix = fem.integrate(scalar_mass_form, fields={"p": p_trial, "q": p_test})
wp.launch(
kernel=inverse_array_kernel,
dim=inv_p_mass_matrix.values.shape,
device=inv_p_mass_matrix.values.device,
inputs=[inv_p_mass_matrix.values],
)
# Assemble linear system
u_matrix = u_visc_matrix
bsr_axpy(u_bd_matrix, u_matrix, alpha=self.bd_strength)
div_matrix_t = bsr_transposed(div_matrix)
gradient_matrix = bsr_mm(div_matrix_t, inv_p_mass_matrix)
bsr_mm(gradient_matrix, div_matrix, u_matrix, alpha=1.0 / self.compliance, beta=1.0)
array_axpy(u_rhs, u_rhs, alpha=0.0, beta=self.bd_strength)
# Solve for displacement
u_res = wp.zeros_like(u_rhs)
bsr_cg(u_matrix, x=u_res, b=u_rhs, quiet=self._quiet)
# Compute pressure from displacement
div_u = bsr_mv(A=div_matrix, x=u_res)
p_res = bsr_mv(A=inv_p_mass_matrix, x=div_u, alpha=-1)
# Copy to fields
u_nodes = wp.indexedarray(self._u_field.dof_values, indices=self._active_space_partition.space_node_indices())
p_nodes = wp.indexedarray(self._p_field.dof_values, indices=self._active_p_space_partition.space_node_indices())
array_cast(in_array=u_res, out_array=u_nodes)
array_cast(in_array=p_res, out_array=p_nodes)
def render(self):
self.renderer.add_surface("pressure", self._p_field)
self.renderer.add_surface_vector("velocity", self._u_field)
def _gen_particles(self, circle_radius, c1_center, c2_center):
"""Generate some particles along two circles defining velocity boundary conditions"""
# Generate particles defining the transfer displacement
particles_per_circle = int(2.0 * math.pi * circle_radius * self.res)
angles = np.linspace(0, 2.0 * math.pi, particles_per_circle, endpoint=False)
n_particles = 2 * particles_per_circle
particles = np.empty((n_particles, 2), dtype=float)
particles[:particles_per_circle, 0] = c1_center[0] + circle_radius * np.cos(angles)
particles[:particles_per_circle, 1] = c1_center[1] + circle_radius * np.sin(angles)
particles[particles_per_circle:, 0] = c2_center[0] + circle_radius * np.cos(angles)
particles[particles_per_circle:, 1] = c2_center[1] + circle_radius * np.sin(angles)
particle_areas = np.ones(n_particles) * self.cell_size**2
particle_velocities = np.zeros_like(particles)
particle_velocities[:particles_per_circle, 0] = self.vel
particle_velocities[particles_per_circle:, 0] = -self.vel
particles = wp.array(particles, dtype=wp.vec2)
particle_areas = wp.array(particle_areas, dtype=float)
particle_velocities = wp.array(particle_velocities, dtype=wp.vec2)
return particles, particle_areas, particle_velocities
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(quiet=args.quiet, resolution=args.resolution)
example.step()
example.render()
if not args.headless:
example.renderer.plot(streamlines=["velocity"])
| 9,696 | Python | 35.73106 | 120 | 0.640264 |
NVIDIA/warp/warp/examples/fem/example_apic_fluid.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.
###########################################################################
# Example APIC Fluid Simulation
#
# Shows how to implement a minimalist APIC fluid simulation using a NanoVDB
# grid and the PicQuadrature class.
###########################################################################
import numpy as np
import warp as wp
import warp.fem as fem
import warp.sim.render
from warp.fem import Domain, Field, Sample, at_node, div, grad, integrand
from warp.sim import Model, State
from warp.sparse import BsrMatrix, bsr_mm, bsr_mv, bsr_transposed
try:
from .bsr_utils import bsr_cg
except ImportError:
from bsr_utils import bsr_cg
@wp.func
def collision_sdf(x: wp.vec3):
# Arbitrary sdf representing collision geometry
# Here an inverted half-ball of radius 10
x[1] = wp.min(x[1], 0.0)
return 10.0 - wp.length(x), -wp.normalize(x)
@integrand
def integrate_fraction(s: Sample, phi: Field):
return phi(s)
@integrand
def integrate_velocity(
s: Sample,
domain: Domain,
u: Field,
velocities: wp.array(dtype=wp.vec3),
velocity_gradients: wp.array(dtype=wp.mat33),
dt: float,
gravity: wp.vec3,
):
"""Transfer particle velocities to grid"""
node_offset = domain(at_node(u, s)) - domain(s)
vel_apic = velocities[s.qp_index] + velocity_gradients[s.qp_index] * node_offset
vel_adv = vel_apic + dt * gravity
# if inside collider, remove normal velocity
sdf, sdf_gradient = collision_sdf(domain(s))
if sdf <= 0:
v_n = wp.dot(vel_adv, sdf_gradient)
vel_adv -= wp.max(v_n, 0.0) * sdf_gradient
return wp.dot(u(s), vel_adv)
@integrand
def update_particles(
s: Sample,
domain: Domain,
grid_vel: Field,
dt: float,
pos: wp.array(dtype=wp.vec3),
pos_prev: wp.array(dtype=wp.vec3),
vel: wp.array(dtype=wp.vec3),
vel_grad: wp.array(dtype=wp.mat33),
):
"""Read particle velocity from grid and advect positions"""
p_vel = grid_vel(s)
vel_grad[s.qp_index] = grad(grid_vel, s)
pos_adv = pos_prev[s.qp_index] + dt * p_vel
pos[s.qp_index] = pos_adv
vel[s.qp_index] = p_vel
@integrand
def velocity_boundary_projector_form(s: Sample, domain: Domain, u: Field, v: Field):
"""Projector for velocity-Dirichlet boundary conditions"""
x = domain(s)
sdf, sdf_normal = collision_sdf(x)
if sdf > 0.0:
# Neuman
return 0.0
# Free-slip on boundary
return wp.dot(u(s), sdf_normal) * wp.dot(v(s), sdf_normal)
@integrand
def divergence_form(s: Sample, domain: Domain, u: Field, psi: Field):
# Divergence bilinear form
return div(u, s) * psi(s)
@wp.kernel
def invert_volume_kernel(values: wp.array(dtype=float)):
i = wp.tid()
m = values[i]
values[i] = wp.select(m == 0.0, 1.0 / m, 0.0)
@wp.kernel
def scalar_vector_multiply(
alpha: wp.array(dtype=float),
x: wp.array(dtype=wp.vec3),
y: wp.array(dtype=wp.vec3),
):
i = wp.tid()
y[i] = alpha[i] * x[i]
@wp.kernel
def scale_transposed_divergence_mat(
tr_divergence_mat_offsets: wp.array(dtype=int),
tr_divergence_mat_values: wp.array(dtype=wp.mat(shape=(3, 1), dtype=float)),
inv_fraction_int: wp.array(dtype=float),
):
# In-place scaling of gradient operator rows wiht inverse mass
u_i = wp.tid()
block_beg = tr_divergence_mat_offsets[u_i]
block_end = tr_divergence_mat_offsets[u_i + 1]
for b in range(block_beg, block_end):
tr_divergence_mat_values[b] = tr_divergence_mat_values[b] * inv_fraction_int[u_i]
@wp.kernel
def compute_particle_ijk(positions: wp.array(dtype=wp.vec3), voxel_size: float, ijks: wp.array(dtype=wp.vec3i)):
# Index-space coordinates of grid cell containing each particle
p = wp.tid()
pos = positions[p] / voxel_size
ijks[p] = wp.vec3i(int(wp.floor(pos[0])), int(wp.floor(pos[1])), int(wp.floor(pos[2])))
def solve_incompressibility(divergence_mat: BsrMatrix, inv_volume, pressure, velocity, quiet: bool = False):
"""Solve for divergence-free velocity delta:
delta_velocity = inv_volume * transpose(divergence_mat) * pressure
divergence_mat * (velocity + delta_velocity) = 0
"""
# Build transposed gradient matrix, scale with inverse fraction
transposed_divergence_mat = bsr_transposed(divergence_mat)
wp.launch(
kernel=scale_transposed_divergence_mat,
dim=inv_volume.shape[0],
inputs=[
transposed_divergence_mat.offsets,
transposed_divergence_mat.values,
inv_volume,
],
)
# For simplicity, assemble Schur complement and solve with CG
schur = bsr_mm(divergence_mat, transposed_divergence_mat)
rhs = wp.zeros_like(pressure)
bsr_mv(A=divergence_mat, x=velocity, y=rhs, alpha=-1.0, beta=0.0)
bsr_cg(schur, b=rhs, x=pressure, quiet=quiet, tol=1.0e-6)
# Apply pressure to velocity
bsr_mv(A=transposed_divergence_mat, x=pressure, y=velocity, alpha=1.0, beta=1.0)
class Example:
def __init__(self, quiet=False, stage_path="example_apic_fluid.usd", voxel_size=1.0):
fps = 60
self.frame_dt = 1.0 / fps
self.current_frame = 0
self.sim_substeps = 1
self.sim_dt = self.frame_dt / self.sim_substeps
self.voxel_size = voxel_size
self._quiet = quiet
# particle emission
particle_grid_lo = wp.vec3(-5)
particle_grid_hi = wp.vec3(5)
grid_cell_size = voxel_size
grid_cell_volume = np.prod(grid_cell_size)
PARTICLES_PER_CELL_DIM = 2
self.radius = float(np.max(grid_cell_size) / (2 * PARTICLES_PER_CELL_DIM))
particle_grid_res = (
np.array((particle_grid_hi - particle_grid_lo) / voxel_size, dtype=int) * PARTICLES_PER_CELL_DIM
)
particle_grid_offset = wp.vec3(self.radius, self.radius, self.radius)
# Initialize warp.sim model, spawn particles
np.random.seed(0)
builder = wp.sim.ModelBuilder()
builder.add_particle_grid(
dim_x=particle_grid_res[0],
dim_y=particle_grid_res[1],
dim_z=particle_grid_res[2],
cell_x=self.radius * 2.0,
cell_y=self.radius * 2.0,
cell_z=self.radius * 2.0,
pos=particle_grid_lo + particle_grid_offset,
rot=wp.quat_identity(),
vel=wp.vec3(0.0, 0.0, 0.0),
mass=grid_cell_volume / PARTICLES_PER_CELL_DIM**3,
jitter=self.radius * 1.0,
)
self.model: Model = builder.finalize()
# Storage for temporary variables
self.temporary_store = fem.TemporaryStore()
if not self._quiet:
print("Particle count:", self.model.particle_count)
self.state_0: State = self.model.state()
self.state_0.particle_qd_grad = wp.zeros(shape=(self.model.particle_count), dtype=wp.mat33)
self.state_1: State = self.model.state()
self.state_1.particle_qd_grad = wp.zeros(shape=(self.model.particle_count), dtype=wp.mat33)
try:
if stage_path:
self.renderer = warp.sim.render.SimRenderer(self.model, stage_path, scaling=20.0)
else:
self.renderer = None
except Exception as err:
print(f"Could not initialize SimRenderer for stage '{stage_path}': {err}.")
def step(self):
fem.set_default_temporary_store(self.temporary_store)
self.current_frame = self.current_frame + 1
particle_ijk = wp.empty(self.state_0.particle_count, dtype=wp.vec3i)
with wp.ScopedTimer(f"simulate frame {self.current_frame}", active=True):
for _s in range(self.sim_substeps):
# Compute the voxel coordinates for each particle.
# `Volume.allocate_by_voxels` accepts world positions, but allocates
# the voxels with the closest origin rather than the enclosing ones
# (i.e, it "round"s the positions, while here we eant to "floor" it)
wp.launch(
compute_particle_ijk,
dim=particle_ijk.shape,
inputs=[self.state_0.particle_q, self.voxel_size, particle_ijk],
)
# Allocate the voxels and create the warp.fem geometry
volume = wp.Volume.allocate_by_voxels(
voxel_points=particle_ijk,
voxel_size=self.voxel_size,
)
grid = fem.Nanogrid(volume)
# Define function spaces: linear (Q1) for velocity and volume fraction,
# piecewise-constant for pressure
linear_basis_space = fem.make_polynomial_basis_space(grid, degree=1)
velocity_space = fem.make_collocated_function_space(linear_basis_space, dtype=wp.vec3)
fraction_space = fem.make_collocated_function_space(linear_basis_space, dtype=float)
strain_space = fem.make_polynomial_space(
grid,
dtype=float,
degree=0,
discontinuous=True,
)
pressure_field = strain_space.make_field()
velocity_field = velocity_space.make_field()
# Define test and trial functions and integrating linear and bilinear forms
domain = fem.Cells(grid)
velocity_test = fem.make_test(velocity_space, domain=domain)
velocity_trial = fem.make_trial(velocity_space, domain=domain)
fraction_test = fem.make_test(fraction_space, domain=domain)
strain_test = fem.make_test(strain_space, domain=domain)
# Build projector for Dirichlet boundary conditions
vel_projector = fem.integrate(
velocity_boundary_projector_form,
fields={"u": velocity_trial, "v": velocity_test},
nodal=True,
output_dtype=float,
)
fem.normalize_dirichlet_projector(vel_projector)
# Bin particles to grid cells
pic = fem.PicQuadrature(
domain=domain, positions=self.state_0.particle_q, measures=self.model.particle_mass
)
# Compute inverse particle volume for each grid node
inv_volume = fem.integrate(
integrate_fraction,
quadrature=pic,
fields={"phi": fraction_test},
output_dtype=float,
)
wp.launch(kernel=invert_volume_kernel, dim=inv_volume.shape, inputs=[inv_volume])
# Velocity right-hand side
velocity_int = fem.integrate(
integrate_velocity,
quadrature=pic,
fields={"u": velocity_test},
values={
"velocities": self.state_0.particle_qd,
"velocity_gradients": self.state_0.particle_qd_grad,
"dt": self.sim_dt,
"gravity": self.model.gravity,
},
output_dtype=wp.vec3,
)
# Compute constraint-free velocity
wp.launch(
kernel=scalar_vector_multiply,
dim=inv_volume.shape[0],
inputs=[inv_volume, velocity_int, velocity_field.dof_values],
)
# Apply velocity boundary conditions:
# velocity -= vel_projector * velocity
bsr_mv(
A=vel_projector,
x=velocity_field.dof_values,
y=velocity_field.dof_values,
alpha=-1.0,
beta=1.0,
)
# Assemble divergence operator matrix
divergence_matrix = fem.integrate(
divergence_form,
quadrature=pic,
fields={"u": velocity_trial, "psi": strain_test},
output_dtype=float,
)
# Project matrix to enforce boundary conditions
# divergence_matrix -= divergence_matrix * vel_projector
bsr_mm(alpha=-1.0, x=divergence_matrix, y=vel_projector, z=divergence_matrix, beta=1.0)
# Solve unilateral incompressibility
solve_incompressibility(
divergence_matrix,
inv_volume,
pressure_field.dof_values,
velocity_field.dof_values,
quiet=self._quiet,
)
# (A)PIC advection
fem.interpolate(
update_particles,
quadrature=pic,
values={
"pos": self.state_1.particle_q,
"pos_prev": self.state_0.particle_q,
"vel": self.state_1.particle_qd,
"vel_grad": self.state_1.particle_qd_grad,
"dt": self.sim_dt,
},
fields={"grid_vel": velocity_field},
)
# swap states
(self.state_0, self.state_1) = (self.state_1, self.state_0)
fem.set_default_temporary_store(None)
def render(self, is_live=False):
if self.renderer is None:
return
with wp.ScopedTimer("render", active=True):
time = self.current_frame * self.frame_dt
self.renderer.begin_frame(time)
self.renderer.render(self.state_0)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_apic_fluid.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=250, help="Total number of frames.")
parser.add_argument("--quiet", action="store_true")
parser.add_argument(
"--voxel_size",
type=float,
default=0.25,
)
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(quiet=args.quiet, stage_path=args.stage_path, voxel_size=args.voxel_size)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 15,290 | Python | 34.314088 | 112 | 0.573578 |
NVIDIA/warp/warp/examples/fem/example_navier_stokes.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.
###########################################################################
# Example Navier Stokes
#
# This example solves a 2D Navier-Stokes flow problem:
#
# Du/dt -nu D(u) + grad p = 0
# Div u = 0
#
# with (hard) velocity-Dirichlet boundary conditions
# and using semi-Lagrangian advection
###########################################################################
import warp as wp
import warp.fem as fem
from warp.fem.utils import array_axpy
from warp.sparse import bsr_copy, bsr_mm, bsr_mv
try:
from .bsr_utils import SaddleSystem, bsr_solve_saddle
from .mesh_utils import gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import SaddleSystem, bsr_solve_saddle
from mesh_utils import gen_trimesh
from plot_utils import Plot
@fem.integrand
def u_boundary_value(s: fem.Sample, domain: fem.Domain, v: fem.Field, top_vel: float):
# Horizontal velocity on top of domain, zero elsewhere
if domain(s)[1] == 1.0:
return wp.dot(wp.vec2f(top_vel, 0.0), v(s))
return wp.dot(wp.vec2f(0.0, 0.0), v(s))
@fem.integrand
def mass_form(
s: fem.Sample,
u: fem.Field,
v: fem.Field,
):
return wp.dot(u(s), v(s))
@fem.integrand
def inertia_form(s: fem.Sample, u: fem.Field, v: fem.Field, dt: float):
return mass_form(s, u, v) / dt
@fem.integrand
def viscosity_form(s: fem.Sample, u: fem.Field, v: fem.Field, nu: float):
return 2.0 * nu * wp.ddot(fem.D(u, s), fem.D(v, s))
@fem.integrand
def viscosity_and_inertia_form(s: fem.Sample, u: fem.Field, v: fem.Field, dt: float, nu: float):
return inertia_form(s, u, v, dt) + viscosity_form(s, u, v, nu)
@fem.integrand
def transported_inertia_form(s: fem.Sample, domain: fem.Domain, u: fem.Field, v: fem.Field, dt: float):
pos = domain(s)
vel = u(s)
conv_pos = pos - 0.5 * vel * dt
conv_s = fem.lookup(domain, conv_pos, s)
conv_vel = u(conv_s)
conv_pos = conv_pos - 0.5 * conv_vel * dt
conv_vel = u(fem.lookup(domain, conv_pos, conv_s))
return wp.dot(conv_vel, v(s)) / dt
@fem.integrand
def div_form(
s: fem.Sample,
u: fem.Field,
q: fem.Field,
):
return -q(s) * fem.div(u, s)
class Example:
def __init__(self, quiet=False, degree=2, resolution=25, Re=1000.0, top_velocity=1.0, tri_mesh=False):
self._quiet = quiet
res = resolution
self.sim_dt = 1.0 / resolution
self.current_frame = 0
viscosity = top_velocity / Re
if tri_mesh:
positions, tri_vidx = gen_trimesh(res=wp.vec2i(res))
geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
else:
geo = fem.Grid2D(res=wp.vec2i(res))
domain = fem.Cells(geometry=geo)
boundary = fem.BoundarySides(geo)
# Functions spaces: Q(d)-Q(d-1)
u_degree = degree
u_space = fem.make_polynomial_space(geo, degree=u_degree, dtype=wp.vec2)
p_space = fem.make_polynomial_space(geo, degree=u_degree - 1)
# Viscosity and inertia
u_test = fem.make_test(space=u_space, domain=domain)
u_trial = fem.make_trial(space=u_space, domain=domain)
u_matrix = fem.integrate(
viscosity_and_inertia_form,
fields={"u": u_trial, "v": u_test},
values={"nu": viscosity, "dt": self.sim_dt},
)
# Pressure-velocity coupling
p_test = fem.make_test(space=p_space, domain=domain)
div_matrix = fem.integrate(div_form, fields={"u": u_trial, "q": p_test})
# Enforcing the Dirichlet boundary condition the hard way;
# build projector for velocity left- and right-hand-sides
u_bd_test = fem.make_test(space=u_space, domain=boundary)
u_bd_trial = fem.make_trial(space=u_space, domain=boundary)
u_bd_projector = fem.integrate(mass_form, fields={"u": u_bd_trial, "v": u_bd_test}, nodal=True)
u_bd_value = fem.integrate(
u_boundary_value,
fields={"v": u_bd_test},
values={"top_vel": top_velocity},
nodal=True,
output_dtype=wp.vec2d,
)
fem.normalize_dirichlet_projector(u_bd_projector, u_bd_value)
u_bd_rhs = wp.zeros_like(u_bd_value)
fem.project_linear_system(u_matrix, u_bd_rhs, u_bd_projector, u_bd_value, normalize_projector=False)
# div_bd_rhs = div_matrix * u_bd_rhs
div_bd_rhs = wp.zeros(shape=(div_matrix.nrow,), dtype=div_matrix.scalar_type)
bsr_mv(div_matrix, u_bd_value, y=div_bd_rhs, alpha=-1.0)
# div_matrix = div_matrix - div_matrix * bd_projector
bsr_mm(x=bsr_copy(div_matrix), y=u_bd_projector, z=div_matrix, alpha=-1.0, beta=1.0)
# Assemble saddle system
self._saddle_system = SaddleSystem(u_matrix, div_matrix)
# Save data for computing time steps rhs
self._u_bd_projector = u_bd_projector
self._u_bd_rhs = u_bd_rhs
self._u_test = u_test
self._div_bd_rhs = div_bd_rhs
# Velocitiy and pressure fields
self._u_field = u_space.make_field()
self._p_field = p_space.make_field()
self.renderer = Plot()
self.renderer.add_surface_vector("velocity", self._u_field)
def step(self):
self.current_frame += 1
u_rhs = fem.integrate(
transported_inertia_form,
fields={"u": self._u_field, "v": self._u_test},
values={"dt": self.sim_dt},
output_dtype=wp.vec2d,
)
# Apply boundary conditions
# u_rhs = (I - P) * u_rhs + u_bd_rhs
bsr_mv(self._u_bd_projector, x=u_rhs, y=u_rhs, alpha=-1.0, beta=1.0)
array_axpy(x=self._u_bd_rhs, y=u_rhs, alpha=1.0, beta=1.0)
p_rhs = self._div_bd_rhs
x_u = wp.empty_like(u_rhs)
x_p = wp.empty_like(p_rhs)
wp.utils.array_cast(out_array=x_u, in_array=self._u_field.dof_values)
wp.utils.array_cast(out_array=x_p, in_array=self._p_field.dof_values)
bsr_solve_saddle(
saddle_system=self._saddle_system,
tol=1.0e-6,
x_u=x_u,
x_p=x_p,
b_u=u_rhs,
b_p=p_rhs,
quiet=self._quiet,
)
wp.utils.array_cast(in_array=x_u, out_array=self._u_field.dof_values)
wp.utils.array_cast(in_array=x_p, out_array=self._p_field.dof_values)
def render(self):
self.renderer.begin_frame(time=self.current_frame * self.sim_dt)
self.renderer.add_surface_vector("velocity", self._u_field)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=25, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--num_frames", type=int, default=1000, help="Total number of frames.")
parser.add_argument(
"--top_velocity",
type=float,
default=1.0,
help="Horizontal velocity boundary condition at the top of the domain.",
)
parser.add_argument("--Re", type=float, default=1000.0, help="Reynolds number.")
parser.add_argument("--tri_mesh", action="store_true", help="Use a triangular mesh.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
Re=args.Re,
top_velocity=args.top_velocity,
tri_mesh=args.tri_mesh,
)
for k in range(args.num_frames):
print(f"Frame {k}:")
example.step()
example.render()
example.renderer.add_surface_vector("velocity_final", example._u_field)
if not args.headless:
example.renderer.plot(streamlines={"velocity_final"})
| 8,835 | Python | 33.248062 | 115 | 0.607357 |
NVIDIA/warp/warp/examples/fem/example_diffusion_mgpu.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.
###########################################################################
# Example Diffusion MGPU
#
# This example illustrates using domain decomposition to
# solve a diffusion PDE over multiple devices
###########################################################################
from typing import Tuple
import warp as wp
import warp.fem as fem
from warp.sparse import bsr_axpy, bsr_mv
from warp.utils import array_cast
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .example_diffusion import diffusion_form, linear_form
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from example_diffusion import diffusion_form, linear_form
from plot_utils import Plot
@fem.integrand
def mass_form(
s: fem.Sample,
u: fem.Field,
v: fem.Field,
):
return u(s) * v(s)
@wp.kernel
def scal_kernel(a: wp.array(dtype=wp.float64), res: wp.array(dtype=wp.float64), alpha: wp.float64):
res[wp.tid()] = a[wp.tid()] * alpha
@wp.kernel
def sum_kernel(a: wp.indexedarray(dtype=wp.float64), b: wp.array(dtype=wp.float64)):
a[wp.tid()] = a[wp.tid()] + b[wp.tid()]
def sum_vecs(vecs, indices, sum: wp.array, tmp: wp.array):
for v, idx in zip(vecs, indices):
wp.copy(dest=tmp, src=v)
idx_sum = wp.indexedarray(sum, idx)
wp.launch(kernel=sum_kernel, dim=idx.shape, device=sum.device, inputs=[idx_sum, tmp])
return sum
class DistributedSystem:
device = None
scalar_type: type
tmp_buf: wp.array
nrow: int
shape = Tuple[int, int]
rank_data = None
def mv_routine(self, x: wp.array, y: wp.array, z: wp.array, alpha=1.0, beta=0.0):
"""Distributed matrix-vector multiplication routine, for example purposes"""
tmp = self.tmp_buf
wp.launch(kernel=scal_kernel, dim=y.shape, device=y.device, inputs=[y, z, wp.float64(beta)])
stream = wp.get_stream()
for mat_i, x_i, y_i, idx in zip(*self.rank_data):
# WAR copy with indexed array requiring matching shape
tmp_i = wp.array(ptr=tmp.ptr, device=tmp.device, capacity=tmp.capacity, dtype=tmp.dtype, shape=idx.shape)
# Compress rhs on rank 0
x_idx = wp.indexedarray(x, idx)
wp.copy(dest=tmp_i, src=x_idx, count=idx.size, stream=stream)
# Send to rank i
wp.copy(dest=x_i, src=tmp_i, count=idx.size, stream=stream)
with wp.ScopedDevice(x_i.device):
wp.wait_stream(stream)
bsr_mv(A=mat_i, x=x_i, y=y_i, alpha=alpha, beta=0.0)
wp.wait_stream(wp.get_stream(x_i.device))
# Back to rank 0 for sum
wp.copy(dest=tmp_i, src=y_i, count=idx.size, stream=stream)
z_idx = wp.indexedarray(z, idx)
wp.launch(kernel=sum_kernel, dim=idx.shape, device=z_idx.device, inputs=[z_idx, tmp_i], stream=stream)
wp.wait_stream(stream)
class Example:
def __init__(self, quiet=False, device=None):
self._bd_weight = 100.0
self._quiet = quiet
self._geo = fem.Grid2D(res=wp.vec2i(25))
self._main_device = wp.get_device(device)
with wp.ScopedDevice(self._main_device):
self._scalar_space = fem.make_polynomial_space(self._geo, degree=3)
self._scalar_field = self._scalar_space.make_field()
self.renderer = Plot()
def step(self):
devices = wp.get_cuda_devices()
main_device = self._main_device
rhs_vecs = []
res_vecs = []
matrices = []
indices = []
# Build local system for each device
for k, device in enumerate(devices):
with wp.ScopedDevice(device):
# Construct the partition corresponding to the k'th device
geo_partition = fem.LinearGeometryPartition(self._geo, k, len(devices))
matrix, rhs, partition_node_indices = self._assemble_local_system(geo_partition)
rhs_vecs.append(rhs)
res_vecs.append(wp.empty_like(rhs))
matrices.append(matrix)
indices.append(partition_node_indices.to(main_device))
# Global rhs as sum of all local rhs
glob_rhs = wp.zeros(n=self._scalar_space.node_count(), dtype=wp.float64, device=main_device)
# This temporary buffer will be used for peer-to-peer copying during graph capture,
# so we allocate it using the default CUDA allocator. This ensures that the copying
# will succeed without enabling mempool access between devices, which is not supported
# on all systems.
with wp.ScopedMempool(main_device, False):
tmp = wp.empty_like(glob_rhs)
sum_vecs(rhs_vecs, indices, glob_rhs, tmp)
# Distributed CG
global_res = wp.zeros_like(glob_rhs)
A = DistributedSystem()
A.device = main_device
A.dtype = glob_rhs.dtype
A.nrow = self._scalar_space.node_count()
A.shape = (A.nrow, A.nrow)
A.tmp_buf = tmp
A.rank_data = (matrices, rhs_vecs, res_vecs, indices)
with wp.ScopedDevice(main_device):
bsr_cg(A, x=global_res, b=glob_rhs, use_diag_precond=False, quiet=self._quiet, mv_routine=A.mv_routine)
array_cast(in_array=global_res, out_array=self._scalar_field.dof_values)
def render(self):
self.renderer.add_surface("solution", self._scalar_field)
def _assemble_local_system(self, geo_partition: fem.GeometryPartition):
scalar_space = self._scalar_space
space_partition = fem.make_space_partition(scalar_space, geo_partition)
domain = fem.Cells(geometry=geo_partition)
# Right-hand-side
test = fem.make_test(space=scalar_space, space_partition=space_partition, domain=domain)
rhs = fem.integrate(linear_form, fields={"v": test})
# Weakly-imposed boundary conditions on all sides
boundary = fem.BoundarySides(geometry=geo_partition)
bd_test = fem.make_test(space=scalar_space, space_partition=space_partition, domain=boundary)
bd_trial = fem.make_trial(space=scalar_space, space_partition=space_partition, domain=boundary)
bd_matrix = fem.integrate(mass_form, fields={"u": bd_trial, "v": bd_test})
# Diffusion form
trial = fem.make_trial(space=scalar_space, space_partition=space_partition, domain=domain)
matrix = fem.integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": 1.0})
bsr_axpy(y=matrix, x=bd_matrix, alpha=self._bd_weight)
return matrix, rhs, space_partition.space_node_indices()
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
args = parser.parse_known_args()[0]
with wp.ScopedTimer(__file__):
example = Example(quiet=args.quiet, device=args.device)
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 7,981 | Python | 35.281818 | 117 | 0.633254 |
NVIDIA/warp/warp/examples/fem/example_diffusion.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.
###########################################################################
# Example Diffusion
#
# This example solves a 2d diffusion problem:
#
# nu Div u = 1
#
# with Dirichlet boundary conditions on vertical edges and
# homogeneous Neumann on horizontal edges.
###########################################################################
import warp as wp
import warp.fem as fem
from warp.fem.utils import array_axpy
from warp.sparse import bsr_axpy
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .mesh_utils import gen_quadmesh, gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from mesh_utils import gen_quadmesh, gen_trimesh
from plot_utils import Plot
@fem.integrand
def linear_form(
s: fem.Sample,
v: fem.Field,
):
"""Linear form with constant slope 1 -- forcing term of our problem"""
return v(s)
@fem.integrand
def diffusion_form(s: fem.Sample, u: fem.Field, v: fem.Field, nu: float):
"""Diffusion bilinear form with constant coefficient ``nu``"""
return nu * wp.dot(
fem.grad(u, s),
fem.grad(v, s),
)
@fem.integrand
def y_boundary_value_form(s: fem.Sample, domain: fem.Domain, v: fem.Field, val: float):
"""Linear form with coefficient val on vertical edges, zero elsewhere"""
nor = fem.normal(domain, s)
return val * v(s) * wp.abs(nor[0])
@fem.integrand
def y_boundary_projector_form(
s: fem.Sample,
domain: fem.Domain,
u: fem.Field,
v: fem.Field,
):
"""
Bilinear boundary condition projector form, non-zero on vertical edges only.
"""
# Reuse the above linear form implementation by evaluating one of the participating field and passing it as a normal scalar argument.
return y_boundary_value_form(s, domain, v, u(s))
class Example:
def __init__(
self,
quiet=False,
degree=2,
resolution=50,
mesh="grid",
serendipity=False,
viscosity=2.0,
boundary_value=5.0,
boundary_compliance=0.0,
):
self._quiet = quiet
self._viscosity = viscosity
self._boundary_value = boundary_value
self._boundary_compliance = boundary_compliance
# Grid or triangle mesh geometry
if mesh == "tri":
positions, tri_vidx = gen_trimesh(res=wp.vec2i(resolution))
self._geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
elif mesh == "quad":
positions, quad_vidx = gen_quadmesh(res=wp.vec2i(resolution))
self._geo = fem.Quadmesh2D(quad_vertex_indices=quad_vidx, positions=positions)
else:
self._geo = fem.Grid2D(res=wp.vec2i(resolution))
# Scalar function space
element_basis = fem.ElementBasis.SERENDIPITY if serendipity else None
self._scalar_space = fem.make_polynomial_space(self._geo, degree=degree, element_basis=element_basis)
# Scalar field over our function space
self._scalar_field = self._scalar_space.make_field()
self.renderer = Plot()
def step(self):
geo = self._geo
domain = fem.Cells(geometry=geo)
# Right-hand-side (forcing term)
test = fem.make_test(space=self._scalar_space, domain=domain)
rhs = fem.integrate(linear_form, fields={"v": test})
# Diffusion form
trial = fem.make_trial(space=self._scalar_space, domain=domain)
matrix = fem.integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": self._viscosity})
# Boundary conditions on Y sides
# Use nodal integration so that boundary conditions are specified on each node independently
boundary = fem.BoundarySides(geo)
bd_test = fem.make_test(space=self._scalar_space, domain=boundary)
bd_trial = fem.make_trial(space=self._scalar_space, domain=boundary)
bd_matrix = fem.integrate(y_boundary_projector_form, fields={"u": bd_trial, "v": bd_test}, nodal=True)
bd_rhs = fem.integrate(
y_boundary_value_form, fields={"v": bd_test}, values={"val": self._boundary_value}, nodal=True
)
# Assemble linear system
if self._boundary_compliance == 0.0:
# Hard BC: project linear system
fem.project_linear_system(matrix, rhs, bd_matrix, bd_rhs)
else:
# Weak BC: add together diffusion and boundary condition matrices
boundary_strength = 1.0 / self._boundary_compliance
bsr_axpy(x=bd_matrix, y=matrix, alpha=boundary_strength, beta=1)
array_axpy(x=bd_rhs, y=rhs, alpha=boundary_strength, beta=1)
# Solve linear system using Conjugate Gradient
x = wp.zeros_like(rhs)
bsr_cg(matrix, b=rhs, x=x, quiet=self._quiet)
# Assign system result to our discrete field
self._scalar_field.dof_values = x
def render(self):
self.renderer.add_surface("solution", self._scalar_field)
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--serendipity", action="store_true", default=False, help="Use Serendipity basis functions.")
parser.add_argument("--viscosity", type=float, default=2.0, help="Fluid viscosity parameter.")
parser.add_argument(
"--boundary_value", type=float, default=5.0, help="Value of Dirichlet boundary condition on vertical edges."
)
parser.add_argument(
"--boundary_compliance", type=float, default=0.0, help="Dirichlet boundary condition compliance."
)
parser.add_argument("--mesh", choices=("grid", "tri", "quad"), default="grid", help="Mesh type.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
mesh=args.mesh,
serendipity=args.serendipity,
viscosity=args.viscosity,
boundary_value=args.boundary_value,
boundary_compliance=args.boundary_compliance,
)
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 7,419 | Python | 36.1 | 137 | 0.644022 |
NVIDIA/warp/warp/examples/fem/example_burgers.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.
###########################################################################
# Example Burgers
#
# This example simulates an inviscid non-conservative Burgers PDE using
# Discontinuous Galerkin with minmod slope limiter
#
# d u /dt + (u . grad) u = 0
#
###########################################################################
import warp as wp
import warp.fem as fem
import warp.sparse as sp
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import invert_diagonal_bsr_mass_matrix
from .plot_utils import Plot
except ImportError:
from bsr_utils import invert_diagonal_bsr_mass_matrix
from plot_utils import Plot
@fem.integrand
def vel_mass_form(
s: fem.Sample,
u: fem.Field,
v: fem.Field,
):
return wp.dot(v(s), u(s))
@fem.integrand
def upwind_transport_form(s: fem.Sample, domain: fem.Domain, u: fem.Field, v: fem.Field, w: fem.Field):
# Upwinding transport with discontinuous convection velocity,
# using jump(w v) = jump(w) avg(v) + avg(w) jump(w)
nor = fem.normal(domain, s)
w_avg_n = wp.dot(fem.average(w, s), nor)
w_jump_n = wp.dot(fem.jump(w, s), nor)
x = domain(s)
v_avg = fem.average(v, s)
if x[0] <= 0.0 or x[0] >= 1.0: # out
# if x[0] >= 1.0: # out
v_jump = v(s)
else:
v_jump = fem.jump(v, s)
u_avg = fem.average(u, s)
u_jump = fem.jump(u, s)
return wp.dot(u_avg, v_jump * w_avg_n + v_avg * w_jump_n) + 0.5 * wp.dot(v_jump, u_jump) * (
wp.abs(w_avg_n) + 0.5 * wp.abs(w_jump_n)
)
@fem.integrand
def cell_transport_form(s: fem.Sample, domain: fem.Domain, u: fem.Field, v: fem.Field, w: fem.Field):
# ((w . grad) u) . v = v^T (grad u) w = grad(u) : (v w^T)
# with integration by parts
# u . Div (w v^T) = u^T grad(v) w + u^T v div (w)
return -wp.dot(fem.div(w, s) * v(s) + fem.grad(v, s) * w(s), u(s))
@fem.integrand
def initial_condition(s: fem.Sample, domain: fem.Domain):
x = domain(s)[0] * 2.0
wave = wp.sin(x * wp.pi)
return wp.vec2(wp.select(x <= 1.0, 0.0, wave), 0.0)
@fem.integrand
def velocity_norm(s: fem.Sample, u: fem.Field):
return wp.length(u(s))
@wp.func
def minmod(a: float, b: float):
sa = wp.sign(a)
sb = wp.sign(b)
return wp.select(sa == sb, 0.0, sa * wp.min(wp.abs(a), wp.abs(b)))
@fem.integrand
def slope_limiter(domain: fem.Domain, s: fem.Sample, u: fem.Field, dx: wp.vec2):
# Minmod slope limiter against P0 discretization (evaluation at cell centers)
# Assumes regular grid topology
center_coords = fem.Coords(0.5, 0.5, 0.0)
cell_center = fem.types.make_free_sample(s.element_index, center_coords)
center_pos = domain(cell_center)
u_center = u(cell_center)
delta_coords = s.element_coords - center_coords
neighbour_xp = fem.lookup(domain, center_pos + wp.vec2(dx[0], 0.0))
neighbour_yp = fem.lookup(domain, center_pos + wp.vec2(0.0, dx[1]))
neighbour_xm = fem.lookup(domain, center_pos - wp.vec2(dx[0], 0.0))
neighbour_ym = fem.lookup(domain, center_pos - wp.vec2(0.0, dx[1]))
u_nxp = u(neighbour_xp)
u_nyp = u(neighbour_yp)
u_nxm = u(neighbour_xm)
u_nym = u(neighbour_ym)
gx = minmod(u_nxp[0] - u_center[0], u_center[0] - u_nxm[0]) * delta_coords[0]
gy = minmod(u_nyp[1] - u_center[1], u_center[1] - u_nym[1]) * delta_coords[1]
delta_u = u(s) - u_center
return u_center + wp.vec2(minmod(gx, delta_u[0]), minmod(gy, delta_u[1]))
class Example:
def __init__(self, quiet=False, resolution=50, degree=1):
self._quiet = quiet
res = resolution
self.sim_dt = 1.0 / res
self.current_frame = 0
geo = fem.Grid2D(res=wp.vec2i(resolution))
domain = fem.Cells(geometry=geo)
sides = fem.Sides(geo)
basis_space = fem.make_polynomial_basis_space(geo, degree=degree, discontinuous=True)
vector_space = fem.make_collocated_function_space(basis_space, dtype=wp.vec2)
scalar_space = fem.make_collocated_function_space(basis_space, dtype=float)
# Test function for ou vector space
self._test = fem.make_test(space=vector_space, domain=domain)
# Test function for integration on sides
self._side_test = fem.make_test(space=vector_space, domain=sides)
# Inertia matrix
# For simplicity, use nodal integration so that inertia matrix is diagonal
trial = fem.make_trial(space=vector_space, domain=domain)
matrix_inertia = fem.integrate(
vel_mass_form, fields={"u": trial, "v": self._test}, output_dtype=wp.float32, nodal=True
)
self._inv_mass_matrix = sp.bsr_copy(matrix_inertia)
invert_diagonal_bsr_mass_matrix(self._inv_mass_matrix)
# Initial condition
self.velocity_field = vector_space.make_field()
fem.interpolate(initial_condition, dest=self.velocity_field)
# Velocity nor field -- for visualization purposes
self.velocity_norm_field = scalar_space.make_field()
fem.interpolate(velocity_norm, dest=self.velocity_norm_field, fields={"u": self.velocity_field})
self.renderer = Plot()
self.renderer.add_surface("u_norm", self.velocity_norm_field)
def _velocity_delta(self, trial_velocity):
# Integration on sides
rhs = fem.integrate(
upwind_transport_form,
fields={"u": trial_velocity.trace(), "v": self._side_test, "w": trial_velocity.trace()},
output_dtype=wp.vec2,
)
if self.velocity_field.space.degree > 0:
# Integration on cells (if not piecewise-constant)
fem.utils.array_axpy(
x=fem.integrate(
cell_transport_form,
fields={"u": trial_velocity, "v": self._test, "w": trial_velocity},
output_dtype=wp.vec2,
quadrature=fem.RegularQuadrature(
order=3, domain=self._test.domain, family=fem.Polynomial.LOBATTO_GAUSS_LEGENDRE
),
),
y=rhs,
alpha=1.0,
beta=1.0,
)
return sp.bsr_mv(self._inv_mass_matrix, rhs)
def step(self):
self.current_frame += 1
# Third-order Strong Stability Preserving Runge-Kutta (SSPRK3)
k1 = self._velocity_delta(self.velocity_field)
# tmp = v0 - dt * k1
tmp = self.velocity_field.space.make_field()
fem.utils.array_axpy(y=tmp.dof_values, x=self.velocity_field.dof_values, alpha=1.0, beta=0.0)
fem.utils.array_axpy(y=tmp.dof_values, x=k1, alpha=-self.sim_dt, beta=1.0)
k2 = self._velocity_delta(tmp)
# tmp = v0 - dt * (0.25 * k1 + 0.25 * k2)
fem.utils.array_axpy(y=tmp.dof_values, x=k1, alpha=0.75 * self.sim_dt, beta=1.0)
fem.utils.array_axpy(y=tmp.dof_values, x=k2, alpha=-0.25 * self.sim_dt, beta=1.0)
k3 = self._velocity_delta(tmp)
# v = v0 - dt * (1/6 * k1 + 1/6 * k2 + 2/3 * k3)
fem.utils.array_axpy(y=self.velocity_field.dof_values, x=k1, alpha=-1.0 / 6.0 * self.sim_dt, beta=1.0)
fem.utils.array_axpy(y=self.velocity_field.dof_values, x=k2, alpha=-1.0 / 6.0 * self.sim_dt, beta=1.0)
fem.utils.array_axpy(y=self.velocity_field.dof_values, x=k3, alpha=-2.0 / 3.0 * self.sim_dt, beta=1.0)
# Apply slope limiter
if self.velocity_field.space.degree > 0:
res = self.velocity_field.space.geometry.res
dx = wp.vec2(1.0 / res[0], 1.0 / res[1])
fem.interpolate(slope_limiter, dest=tmp, fields={"u": self.velocity_field}, values={"dx": dx})
wp.copy(src=tmp.dof_values, dest=self.velocity_field.dof_values)
# Update velocity norm (for visualization)
fem.interpolate(velocity_norm, dest=self.velocity_norm_field, fields={"u": self.velocity_field})
def render(self):
self.renderer.begin_frame(time=self.current_frame * self.sim_dt)
self.renderer.add_surface("u_norm", self.velocity_norm_field)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument("--num_frames", type=int, default=250, help="Total number of frames.")
parser.add_argument("--degree", choices=(0, 1), type=int, default=1, help="Discretization order.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
resolution=args.resolution,
degree=args.degree,
)
for k in range(args.num_frames):
print(f"Frame {k}:")
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 9,777 | Python | 36.178707 | 110 | 0.609594 |
NVIDIA/warp/warp/examples/fem/example_stokes.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.
###########################################################################
# Example Stokes
#
# This example solves a 2D Stokes flow problem
#
# -nu D(u) + grad p = 0
# Div u = 0
#
# with (soft) velocity-Dirichlet boundary conditions
###########################################################################
import warp as wp
import warp.fem as fem
import warp.sparse as sparse
from warp.fem.utils import array_axpy
try:
from .bsr_utils import SaddleSystem, bsr_solve_saddle
from .mesh_utils import gen_quadmesh, gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import SaddleSystem, bsr_solve_saddle
from mesh_utils import gen_quadmesh, gen_trimesh
from plot_utils import Plot
@fem.integrand
def constant_form(val: wp.vec2):
return val
@fem.integrand
def viscosity_form(s: fem.Sample, u: fem.Field, v: fem.Field, nu: float):
return nu * wp.ddot(fem.D(u, s), fem.D(v, s))
@fem.integrand
def top_mass_form(
s: fem.Sample,
domain: fem.Domain,
u: fem.Field,
v: fem.Field,
):
# non zero on top boundary of domain only
nor = fem.normal(domain, s)
return wp.dot(u(s), v(s)) * wp.max(0.0, nor[1])
@fem.integrand
def mass_form(
s: fem.Sample,
u: fem.Field,
v: fem.Field,
):
return wp.dot(u(s), v(s))
@fem.integrand
def div_form(
s: fem.Sample,
u: fem.Field,
q: fem.Field,
):
return q(s) * fem.div(u, s)
class Example:
def __init__(
self,
quiet=False,
mesh="grid",
degree=2,
resolution=50,
viscosity=1.0,
top_velocity=1.0,
boundary_strength=100.0,
nonconforming_pressures=False,
):
self._quiet = quiet
self.viscosity = viscosity
self.boundary_strength = boundary_strength
# Grid or triangle mesh geometry
if mesh == "tri":
positions, tri_vidx = gen_trimesh(res=wp.vec2i(resolution))
geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
elif mesh == "quad":
positions, quad_vidx = gen_quadmesh(res=wp.vec2i(resolution))
geo = fem.Quadmesh2D(quad_vertex_indices=quad_vidx, positions=positions)
else:
geo = fem.Grid2D(res=wp.vec2i(resolution))
# Function spaces -- Q_d for vel, P_{d-1} for pressure
u_space = fem.make_polynomial_space(geo, degree=degree, dtype=wp.vec2)
if mesh != "tri" and nonconforming_pressures:
p_space = fem.make_polynomial_space(
geo, degree=degree - 1, element_basis=fem.ElementBasis.NONCONFORMING_POLYNOMIAL
)
else:
p_space = fem.make_polynomial_space(geo, degree=degree - 1)
# Vector and scalar fields
self._u_field = u_space.make_field()
self._p_field = p_space.make_field()
# Interpolate initial condition on boundary (for example purposes)
self._bd_field = u_space.make_field()
f_boundary = fem.make_restriction(self._bd_field, domain=fem.BoundarySides(geo))
top_velocity = wp.vec2(top_velocity, 0.0)
fem.interpolate(constant_form, dest=f_boundary, values={"val": top_velocity})
self.renderer = Plot()
def step(self):
u_space = self._u_field.space
p_space = self._p_field.space
geo = u_space.geometry
domain = fem.Cells(geometry=geo)
boundary = fem.BoundarySides(geo)
# Viscosity
u_test = fem.make_test(space=u_space, domain=domain)
u_trial = fem.make_trial(space=u_space, domain=domain)
u_visc_matrix = fem.integrate(
viscosity_form,
fields={"u": u_trial, "v": u_test},
values={"nu": self.viscosity},
)
# Weak velocity boundary conditions
u_bd_test = fem.make_test(space=u_space, domain=boundary)
u_bd_trial = fem.make_trial(space=u_space, domain=boundary)
u_rhs = fem.integrate(
top_mass_form, fields={"u": self._bd_field.trace(), "v": u_bd_test}, output_dtype=wp.vec2d
)
u_bd_matrix = fem.integrate(mass_form, fields={"u": u_bd_trial, "v": u_bd_test})
# Pressure-velocity coupling
p_test = fem.make_test(space=p_space, domain=domain)
div_matrix = fem.integrate(div_form, fields={"u": u_trial, "q": p_test})
# Define and solve the saddle-point system
u_matrix = u_visc_matrix
sparse.bsr_axpy(x=u_bd_matrix, y=u_matrix, alpha=self.boundary_strength, beta=1.0)
array_axpy(x=u_rhs, y=u_rhs, alpha=0.0, beta=self.boundary_strength)
p_rhs = wp.zeros(p_space.node_count(), dtype=wp.float64)
x_u = wp.zeros_like(u_rhs)
x_p = wp.zeros_like(p_rhs)
bsr_solve_saddle(
SaddleSystem(A=u_matrix, B=div_matrix), x_u=x_u, x_p=x_p, b_u=u_rhs, b_p=p_rhs, quiet=self._quiet
)
wp.utils.array_cast(in_array=x_u, out_array=self._u_field.dof_values)
wp.utils.array_cast(in_array=x_p, out_array=self._p_field.dof_values)
def render(self):
self.renderer.add_surface("pressure", self._p_field)
self.renderer.add_surface_vector("velocity", self._u_field)
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument(
"--top_velocity",
type=float,
default=1.0,
help="Horizontal velocity initial condition at the top of the domain.",
)
parser.add_argument("--viscosity", type=float, default=1.0, help="Fluid viscosity parameter.")
parser.add_argument("--boundary_strength", type=float, default=100.0, help="Soft boundary condition strength.")
parser.add_argument("--mesh", choices=("grid", "tri", "quad"), default="grid", help="Mesh type.")
parser.add_argument(
"--nonconforming_pressures", action="store_true", help="For grid, use non-conforming pressure (Q_d/P_{d-1})."
)
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
mesh=args.mesh,
degree=args.degree,
resolution=args.resolution,
viscosity=args.viscosity,
top_velocity=args.top_velocity,
boundary_strength=args.boundary_strength,
nonconforming_pressures=args.nonconforming_pressures,
)
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 7,601 | Python | 33.712329 | 117 | 0.619261 |
NVIDIA/warp/warp/examples/fem/example_mixed_elasticity.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.
###########################################################################
# Example Mixed Elasticity
#
# This example illustrates using Mixed FEM to solve a
# 2D linear elasticity problem:
#
# Div[ E: D(u) ] = 0
#
# with Dirichlet boundary conditions on horizontal sides,
# and E the elasticity rank-4 tensor
###########################################################################
import numpy as np
import warp as wp
import warp.fem as fem
from warp.sparse import bsr_mm, bsr_transposed
try:
from .bsr_utils import bsr_cg, invert_diagonal_bsr_mass_matrix
from .mesh_utils import gen_quadmesh, gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg, invert_diagonal_bsr_mass_matrix
from mesh_utils import gen_quadmesh, gen_trimesh
from plot_utils import Plot
@wp.func
def compute_stress(tau: wp.mat22, E: wp.mat33):
"""Strain to stress computation"""
tau_sym = wp.vec3(tau[0, 0], tau[1, 1], tau[0, 1] + tau[1, 0])
sig_sym = E * tau_sym
return wp.mat22(sig_sym[0], 0.5 * sig_sym[2], 0.5 * sig_sym[2], sig_sym[1])
@fem.integrand
def symmetric_grad_form(
s: fem.Sample,
u: fem.Field,
tau: fem.Field,
):
"""D(u) : tau"""
return wp.ddot(tau(s), fem.D(u, s))
@fem.integrand
def stress_form(s: fem.Sample, u: fem.Field, tau: fem.Field, E: wp.mat33):
"""(E : D(u)) : tau"""
return wp.ddot(tau(s), compute_stress(fem.D(u, s), E))
@fem.integrand
def horizontal_boundary_projector_form(
s: fem.Sample,
domain: fem.Domain,
u: fem.Field,
v: fem.Field,
):
# non zero on horizontal boundary of domain only
nor = fem.normal(domain, s)
return wp.dot(u(s), v(s)) * wp.abs(nor[1])
@fem.integrand
def horizontal_displacement_form(
s: fem.Sample,
domain: fem.Domain,
v: fem.Field,
displacement: float,
):
# opposed to normal on horizontal boundary of domain only
nor = fem.normal(domain, s)
return -wp.abs(nor[1]) * displacement * wp.dot(nor, v(s))
@fem.integrand
def tensor_mass_form(
s: fem.Sample,
sig: fem.Field,
tau: fem.Field,
):
return wp.ddot(tau(s), sig(s))
class Example:
def __init__(
self,
quiet=False,
degree=2,
resolution=25,
mesh="grid",
displacement=0.1,
young_modulus=1.0,
poisson_ratio=0.5,
nonconforming_stresses=False,
):
self._quiet = quiet
self._displacement = displacement
# Grid or triangle mesh geometry
if mesh == "tri":
positions, tri_vidx = gen_trimesh(res=wp.vec2i(resolution))
self._geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
elif mesh == "quad":
positions, quad_vidx = gen_quadmesh(res=wp.vec2i(resolution))
self._geo = fem.Quadmesh2D(quad_vertex_indices=quad_vidx, positions=positions)
else:
self._geo = fem.Grid2D(res=wp.vec2i(resolution))
# Strain-stress matrix
young = young_modulus
poisson = poisson_ratio
self._elasticity_mat = wp.mat33(
young
/ (1.0 - poisson * poisson)
* np.array(
[
[1.0, poisson, 0.0],
[poisson, 1.0, 0.0],
[0.0, 0.0, (2.0 * (1.0 + poisson)) * (1.0 - poisson * poisson)],
]
)
)
# Function spaces -- S_k for displacement, Q_{k-1}d for stress
self._u_space = fem.make_polynomial_space(
self._geo, degree=degree, dtype=wp.vec2, element_basis=fem.ElementBasis.SERENDIPITY
)
# Store stress degrees of freedom as symmetric tensors (3 dof) rather than full 2x2 matrices
tau_basis = fem.ElementBasis.NONCONFORMING_POLYNOMIAL if nonconforming_stresses else fem.ElementBasis.LAGRANGE
self._tau_space = fem.make_polynomial_space(
self._geo,
degree=degree - 1,
discontinuous=True,
element_basis=tau_basis,
dof_mapper=fem.SymmetricTensorMapper(wp.mat22),
)
self._u_field = self._u_space.make_field()
self.renderer = Plot()
def step(self):
boundary = fem.BoundarySides(self._geo)
domain = fem.Cells(geometry=self._geo)
# Displacement boundary conditions
u_bd_test = fem.make_test(space=self._u_space, domain=boundary)
u_bd_trial = fem.make_trial(space=self._u_space, domain=boundary)
u_bd_rhs = fem.integrate(
horizontal_displacement_form,
fields={"v": u_bd_test},
values={"displacement": self._displacement},
nodal=True,
output_dtype=wp.vec2d,
)
u_bd_matrix = fem.integrate(
horizontal_boundary_projector_form, fields={"u": u_bd_trial, "v": u_bd_test}, nodal=True
)
# Stress/velocity coupling
u_trial = fem.make_trial(space=self._u_space, domain=domain)
tau_test = fem.make_test(space=self._tau_space, domain=domain)
tau_trial = fem.make_trial(space=self._tau_space, domain=domain)
sym_grad_matrix = fem.integrate(symmetric_grad_form, fields={"u": u_trial, "tau": tau_test})
stress_matrix = fem.integrate(
stress_form, fields={"u": u_trial, "tau": tau_test}, values={"E": self._elasticity_mat}
)
# Compute inverse of the (block-diagonal) tau mass matrix
tau_inv_mass_matrix = fem.integrate(tensor_mass_form, fields={"sig": tau_trial, "tau": tau_test}, nodal=True)
invert_diagonal_bsr_mass_matrix(tau_inv_mass_matrix)
# Assemble system matrix
u_matrix = bsr_mm(bsr_transposed(sym_grad_matrix), bsr_mm(tau_inv_mass_matrix, stress_matrix))
# Enforce boundary conditions
u_rhs = wp.zeros_like(u_bd_rhs)
fem.project_linear_system(u_matrix, u_rhs, u_bd_matrix, u_bd_rhs)
x = wp.zeros_like(u_rhs)
bsr_cg(u_matrix, b=u_rhs, x=x, tol=1.0e-16, quiet=self._quiet)
# Extract result
self._u_field.dof_values = x
def render(self):
self.renderer.add_surface_vector("solution", self._u_field)
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=25, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--displacement", type=float, default=0.1)
parser.add_argument("--young_modulus", type=float, default=1.0)
parser.add_argument("--poisson_ratio", type=float, default=0.5)
parser.add_argument("--mesh", choices=("grid", "tri", "quad"), default="grid", help="Mesh type")
parser.add_argument(
"--nonconforming_stresses", action="store_true", help="For grid, use non-conforming stresses (Q_d/P_d)"
)
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
mesh=args.mesh,
displacement=args.displacement,
young_modulus=args.young_modulus,
poisson_ratio=args.poisson_ratio,
nonconforming_stresses=args.nonconforming_stresses,
)
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 8,389 | Python | 33.526749 | 118 | 0.611753 |
NVIDIA/warp/warp/examples/fem/example_convection_diffusion_dg.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.
###########################################################################
# Example Convection Diffusion DG
#
# This example simulates a convection-diffusion PDE using Discontinuous
# Galerkin with upwind transport and Symmetric Interior Penalty
#
# D phi / dt - nu d2 phi / dx^2 = 0
###########################################################################
import warp as wp
import warp.fem as fem
from warp.sparse import bsr_axpy
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .example_convection_diffusion import (
diffusion_form,
inertia_form,
initial_condition,
velocity,
)
from .mesh_utils import gen_quadmesh, gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from example_convection_diffusion import (
diffusion_form,
inertia_form,
initial_condition,
velocity,
)
from mesh_utils import gen_quadmesh, gen_trimesh
from plot_utils import Plot
# Standard transport term, on cells' interior
@fem.integrand
def transport_form(s: fem.Sample, domain: fem.Domain, phi: fem.Field, psi: fem.Field, ang_vel: float):
pos = domain(s)
vel = velocity(pos, ang_vel)
return psi(s) * wp.dot(fem.grad(phi, s), vel)
# Upwind flux, on cell sides
@fem.integrand
def upwind_transport_form(s: fem.Sample, domain: fem.Domain, phi: fem.Field, psi: fem.Field, ang_vel: float):
pos = domain(s)
vel = velocity(pos, ang_vel)
vel_n = wp.dot(vel, fem.normal(domain, s))
return fem.jump(phi, s) * (-fem.average(psi, s) * vel_n + 0.5 * fem.jump(psi, s) * wp.abs(vel_n))
# Symmetric-Interior-Penalty diffusion term (See Pietro Ern 2012)
@fem.integrand
def sip_diffusion_form(
s: fem.Sample,
domain: fem.Domain,
psi: fem.Field,
phi: fem.Field,
):
nor = fem.normal(domain, s)
penalty = fem.measure_ratio(domain, s) * float(fem.degree(psi) * fem.degree(phi))
return penalty * fem.jump(phi, s) * fem.jump(psi, s) - (
wp.dot(fem.grad_average(phi, s), nor) * fem.jump(psi, s)
+ wp.dot(fem.grad_average(psi, s), nor) * fem.jump(phi, s)
)
class Example:
def __init__(self, quiet=False, degree=2, resolution=50, mesh="grid", viscosity=0.001, ang_vel=1.0):
self._quiet = quiet
res = resolution
self.sim_dt = 1.0 / (ang_vel * res)
self.current_frame = 0
if mesh == "tri":
positions, tri_vidx = gen_trimesh(res=wp.vec2i(resolution))
geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
elif mesh == "quad":
positions, quad_vidx = gen_quadmesh(res=wp.vec2i(resolution))
geo = fem.Quadmesh2D(quad_vertex_indices=quad_vidx, positions=positions)
else:
geo = fem.Grid2D(res=wp.vec2i(resolution))
domain = fem.Cells(geometry=geo)
sides = fem.Sides(geo)
scalar_space = fem.make_polynomial_space(
geo,
discontinuous=True,
degree=degree,
family=fem.Polynomial.GAUSS_LEGENDRE,
)
# Assemble transport, diffusion and inertia matrices
self._test = fem.make_test(space=scalar_space, domain=domain)
trial = fem.make_trial(space=scalar_space, domain=domain)
matrix_inertia = fem.integrate(
inertia_form,
fields={"phi": trial, "psi": self._test},
values={"dt": self.sim_dt},
)
matrix_transport = fem.integrate(
transport_form,
fields={"phi": trial, "psi": self._test},
values={"ang_vel": ang_vel},
)
side_test = fem.make_test(space=scalar_space, domain=sides)
side_trial = fem.make_trial(space=scalar_space, domain=sides)
bsr_axpy(
fem.integrate(
upwind_transport_form,
fields={"phi": side_trial, "psi": side_test},
values={"ang_vel": ang_vel},
),
y=matrix_transport,
)
matrix_diffusion = fem.integrate(
diffusion_form,
fields={"u": trial, "v": self._test},
)
bsr_axpy(
fem.integrate(
sip_diffusion_form,
fields={"phi": side_trial, "psi": side_test},
),
y=matrix_diffusion,
)
self._matrix = matrix_inertia
bsr_axpy(x=matrix_transport, y=self._matrix)
bsr_axpy(x=matrix_diffusion, y=self._matrix, alpha=viscosity)
# Initial condition
self._phi_field = scalar_space.make_field()
fem.interpolate(initial_condition, dest=self._phi_field)
self.renderer = Plot()
self.renderer.add_surface("phi", self._phi_field)
def step(self):
self.current_frame += 1
rhs = fem.integrate(
inertia_form,
fields={"phi": self._phi_field, "psi": self._test},
values={"dt": self.sim_dt},
)
phi = wp.zeros_like(rhs)
bsr_cg(self._matrix, b=rhs, x=phi, method="bicgstab", quiet=self._quiet)
wp.utils.array_cast(in_array=phi, out_array=self._phi_field.dof_values)
def render(self):
self.renderer.begin_frame(time=self.current_frame * self.sim_dt)
self.renderer.add_surface("phi", self._phi_field)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--num_frames", type=int, default=100, help="Total number of frames.")
parser.add_argument("--viscosity", type=float, default=0.001, help="Fluid viscosity parameter.")
parser.add_argument("--ang_vel", type=float, default=1.0, help="Angular velocity.")
parser.add_argument("--mesh", choices=("grid", "tri", "quad"), default="grid", help="Mesh type.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
mesh=args.mesh,
viscosity=args.viscosity,
ang_vel=args.ang_vel,
)
for k in range(args.num_frames):
print(f"Frame {k}:")
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 7,499 | Python | 33.40367 | 109 | 0.604481 |
NVIDIA/warp/warp/examples/fem/example_convection_diffusion.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.
###########################################################################
# Example Convection Diffusion
#
# This example simulates a convection-diffusion PDE using
# semi-Lagrangian advection
#
# D phi / dt - nu d2 phi / dx^2 = 0
###########################################################################
import warp as wp
import warp.fem as fem
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .mesh_utils import gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from mesh_utils import gen_trimesh
from plot_utils import Plot
@fem.integrand
def initial_condition(domain: fem.Domain, s: fem.Sample):
"""Initial condition: 1.0 in ]0.6, 0.4[ x ]0.2, 0.8[, 0.0 elsewhere"""
pos = domain(s)
if pos[0] > 0.4 and pos[0] < 0.6 and pos[1] > 0.2 and pos[1] < 0.8:
return 1.0
return 0.0
@wp.func
def velocity(pos: wp.vec2, ang_vel: float):
center = wp.vec2(0.5, 0.5)
offset = pos - center
return wp.vec2(offset[1], -offset[0]) * ang_vel
@fem.integrand
def inertia_form(s: fem.Sample, phi: fem.Field, psi: fem.Field, dt: float):
return phi(s) * psi(s) / dt
@fem.integrand
def transported_inertia_form(
s: fem.Sample, domain: fem.Domain, phi: fem.Field, psi: fem.Field, ang_vel: float, dt: float
):
pos = domain(s)
vel = velocity(pos, ang_vel)
# semi-Lagrangian advection; evaluate phi upstream
conv_pos = pos - vel * dt
# lookup operator constructs a Sample from a world position.
# the optional last argument provides a initial guess for the lookup
conv_phi = phi(fem.lookup(domain, conv_pos, s))
return conv_phi * psi(s) / dt
@fem.integrand
def diffusion_form(
s: fem.Sample,
u: fem.Field,
v: fem.Field,
):
return wp.dot(
fem.grad(u, s),
fem.grad(v, s),
)
@fem.integrand
def diffusion_and_inertia_form(s: fem.Sample, phi: fem.Field, psi: fem.Field, dt: float, nu: float):
return inertia_form(s, phi, psi, dt) + nu * diffusion_form(s, phi, psi)
class Example:
def __init__(self, quiet=False, degree=2, resolution=50, tri_mesh=False, viscosity=0.001, ang_vel=1.0):
self._quiet = quiet
self._ang_vel = ang_vel
res = resolution
self.sim_dt = 1.0 / (ang_vel * res)
self.current_frame = 0
if tri_mesh:
positions, tri_vidx = gen_trimesh(res=wp.vec2i(res))
geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
else:
geo = fem.Grid2D(res=wp.vec2i(res))
domain = fem.Cells(geometry=geo)
scalar_space = fem.make_polynomial_space(geo, degree=degree)
# Initial condition
self._phi_field = scalar_space.make_field()
fem.interpolate(initial_condition, dest=self._phi_field)
# Assemble diffusion and inertia matrix
self._test = fem.make_test(space=scalar_space, domain=domain)
self._trial = fem.make_trial(space=scalar_space, domain=domain)
self._matrix = fem.integrate(
diffusion_and_inertia_form,
fields={"phi": self._trial, "psi": self._test},
values={"nu": viscosity, "dt": self.sim_dt},
output_dtype=float,
)
self.renderer = Plot()
self.renderer.add_surface("phi", self._phi_field)
def step(self):
self.current_frame += 1
# right-hand-side -- advected inertia
rhs = fem.integrate(
transported_inertia_form,
fields={"phi": self._phi_field, "psi": self._test},
values={"ang_vel": self._ang_vel, "dt": self.sim_dt},
output_dtype=float,
)
# Solve linear system
bsr_cg(self._matrix, x=self._phi_field.dof_values, b=rhs, quiet=self._quiet, tol=1.0e-12)
def render(self):
self.renderer.begin_frame(time=self.current_frame * self.sim_dt)
self.renderer.add_surface("phi", self._phi_field)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--num_frames", type=int, default=250, help="Total number of frames.")
parser.add_argument("--viscosity", type=float, default=0.001, help="Fluid viscosity parameter.")
parser.add_argument("--ang_vel", type=float, default=1.0, help="Angular velocity.")
parser.add_argument("--tri_mesh", action="store_true", help="Use a triangular mesh.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
tri_mesh=args.tri_mesh,
viscosity=args.viscosity,
ang_vel=args.ang_vel,
)
for k in range(args.num_frames):
print(f"Frame {k}:")
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 6,181 | Python | 33.154696 | 115 | 0.624009 |
NVIDIA/warp/warp/examples/fem/example_deformed_geometry.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.
###########################################################################
# Example Deformed Geometry
#
# This example solves a 2d diffusion problem:
#
# nu Div u = 1
#
# with Dirichlet boundary conditions on vertical edges and
# homogeneous Neumann on horizontal edges.
###########################################################################
import warp as wp
import warp.fem as fem
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .example_diffusion import diffusion_form, linear_form
from .mesh_utils import gen_quadmesh, gen_trimesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from example_diffusion import diffusion_form, linear_form
from mesh_utils import gen_quadmesh, gen_trimesh
from plot_utils import Plot
@fem.integrand
def deformation_field_expr(
s: fem.Sample,
domain: fem.Domain,
):
"""
Deformation field mapping the unique square to a circular band
"""
x = domain(s)
r = x[1] + 0.5
t = 0.5 * 3.1416 * x[0]
return r * wp.vec2(wp.sin(t), wp.cos(t)) - x
@fem.integrand
def boundary_projector_form(
s: fem.Sample,
domain: fem.Domain,
u: fem.Field,
v: fem.Field,
):
"""
Bilinear boundary condition projector form, non-zero on radial edges
"""
nor = fem.normal(domain, s)
active = wp.select(nor[0] < -0.9999 or nor[1] < -0.9999, 0.0, 1.0)
return active * u(s) * v(s)
class Example:
def __init__(
self,
quiet=False,
degree=2,
resolution=50,
mesh="grid",
serendipity=False,
viscosity=2.0,
):
self._quiet = quiet
self._viscosity = viscosity
# Grid or triangle mesh geometry
if mesh == "tri":
positions, tri_vidx = gen_trimesh(res=wp.vec2i(resolution))
base_geo = fem.Trimesh2D(tri_vertex_indices=tri_vidx, positions=positions)
elif mesh == "quad":
positions, quad_vidx = gen_quadmesh(res=wp.vec2i(resolution))
base_geo = fem.Quadmesh2D(quad_vertex_indices=quad_vidx, positions=positions)
else:
base_geo = fem.Grid2D(res=wp.vec2i(resolution))
# Construct deformation field on base geometry
deformation_space = fem.make_polynomial_space(base_geo, degree=degree, dtype=wp.vec2)
deformation_field = deformation_space.make_field()
fem.interpolate(deformation_field_expr, dest=deformation_field)
self._geo = deformation_field.make_deformed_geometry()
# Scalar function space on deformed geometry
element_basis = fem.ElementBasis.SERENDIPITY if serendipity else None
self._scalar_space = fem.make_polynomial_space(self._geo, degree=degree, element_basis=element_basis)
# Scalar field over our function space
self._scalar_field = self._scalar_space.make_field()
self.renderer = Plot()
def step(self):
geo = self._geo
domain = fem.Cells(geometry=geo)
# Right-hand-side (forcing term)
test = fem.make_test(space=self._scalar_space, domain=domain)
rhs = fem.integrate(linear_form, fields={"v": test})
# Diffusion form
trial = fem.make_trial(space=self._scalar_space, domain=domain)
matrix = fem.integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": self._viscosity})
# Weakly-imposed boundary conditions on all sides
boundary = fem.BoundarySides(geo)
bd_test = fem.make_test(space=self._scalar_space, domain=boundary)
bd_trial = fem.make_trial(space=self._scalar_space, domain=boundary)
bd_matrix = fem.integrate(boundary_projector_form, fields={"u": bd_trial, "v": bd_test}, nodal=True)
fem.project_linear_system(matrix, rhs, bd_matrix)
# Solve linear system using Conjugate Gradient
x = wp.zeros_like(rhs)
bsr_cg(matrix, b=rhs, x=x, quiet=self._quiet, tol=1.0e-6)
# Assign system result to our discrete field
self._scalar_field.dof_values = x
def render(self):
self.renderer.add_surface("solution", self._scalar_field)
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=50, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--serendipity", action="store_true", default=False, help="Use Serendipity basis functions.")
parser.add_argument("--viscosity", type=float, default=2.0, help="Fluid viscosity parameter.")
parser.add_argument("--mesh", choices=("grid", "tri", "quad"), default="grid", help="Mesh type")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
mesh=args.mesh,
serendipity=args.serendipity,
viscosity=args.viscosity,
)
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 6,196 | Python | 34.210227 | 117 | 0.642834 |
NVIDIA/warp/warp/examples/fem/mesh_utils.py | from typing import Optional
import numpy as np
import warp as wp
from warp.fem.utils import grid_to_hexes, grid_to_quads, grid_to_tets, grid_to_tris
def gen_trimesh(res, bounds_lo: Optional[wp.vec2] = None, bounds_hi: Optional[wp.vec2] = None):
"""Constructs a triangular mesh by diving each cell of a dense 2D grid into two triangles
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
Returns:
Tuple of ndarrays: (Vertex positions, Triangle vertex indices)
"""
if bounds_lo is None:
bounds_lo = wp.vec2(0.0)
if bounds_hi is None:
bounds_hi = wp.vec2(1.0)
Nx = res[0]
Ny = res[1]
x = np.linspace(bounds_lo[0], bounds_hi[0], Nx + 1)
y = np.linspace(bounds_lo[1], bounds_hi[1], Ny + 1)
positions = np.transpose(np.meshgrid(x, y, indexing="ij"), axes=(1, 2, 0)).reshape(-1, 2)
vidx = grid_to_tris(Nx, Ny)
return wp.array(positions, dtype=wp.vec2), wp.array(vidx, dtype=int)
def gen_tetmesh(res, bounds_lo: Optional[wp.vec3] = None, bounds_hi: Optional[wp.vec3] = None):
"""Constructs a tetrahedral mesh by diving each cell of a dense 3D grid into five tetrahedrons
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
Returns:
Tuple of ndarrays: (Vertex positions, Tetrahedron vertex indices)
"""
if bounds_lo is None:
bounds_lo = wp.vec3(0.0)
if bounds_hi is None:
bounds_hi = wp.vec3(1.0)
Nx = res[0]
Ny = res[1]
Nz = res[2]
x = np.linspace(bounds_lo[0], bounds_hi[0], Nx + 1)
y = np.linspace(bounds_lo[1], bounds_hi[1], Ny + 1)
z = np.linspace(bounds_lo[2], bounds_hi[2], Nz + 1)
positions = np.transpose(np.meshgrid(x, y, z, indexing="ij"), axes=(1, 2, 3, 0)).reshape(-1, 3)
vidx = grid_to_tets(Nx, Ny, Nz)
return wp.array(positions, dtype=wp.vec3), wp.array(vidx, dtype=int)
def gen_quadmesh(res, bounds_lo: Optional[wp.vec2] = None, bounds_hi: Optional[wp.vec2] = None):
"""Constructs a quadrilateral mesh from a dense 2D grid
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
Returns:
Tuple of ndarrays: (Vertex positions, Triangle vertex indices)
"""
if bounds_lo is None:
bounds_lo = wp.vec2(0.0)
if bounds_hi is None:
bounds_hi = wp.vec2(1.0)
Nx = res[0]
Ny = res[1]
x = np.linspace(bounds_lo[0], bounds_hi[0], Nx + 1)
y = np.linspace(bounds_lo[1], bounds_hi[1], Ny + 1)
positions = np.transpose(np.meshgrid(x, y, indexing="ij"), axes=(1, 2, 0)).reshape(-1, 2)
vidx = grid_to_quads(Nx, Ny)
return wp.array(positions, dtype=wp.vec2), wp.array(vidx, dtype=int)
def gen_hexmesh(res, bounds_lo: Optional[wp.vec3] = None, bounds_hi: Optional[wp.vec3] = None):
"""Constructs a quadrilateral mesh from a dense 2D grid
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
Returns:
Tuple of ndarrays: (Vertex positions, Triangle vertex indices)
"""
if bounds_lo is None:
bounds_lo = wp.vec3(0.0)
if bounds_hi is None:
bounds_hi = wp.vec3(1.0)
Nx = res[0]
Ny = res[1]
Nz = res[2]
x = np.linspace(bounds_lo[0], bounds_hi[0], Nx + 1)
y = np.linspace(bounds_lo[1], bounds_hi[1], Ny + 1)
z = np.linspace(bounds_lo[1], bounds_hi[1], Nz + 1)
positions = np.transpose(np.meshgrid(x, y, z, indexing="ij"), axes=(1, 2, 3, 0)).reshape(-1, 3)
vidx = grid_to_hexes(Nx, Ny, Nz)
return wp.array(positions, dtype=wp.vec3), wp.array(vidx, dtype=int)
| 4,117 | Python | 29.731343 | 99 | 0.632014 |
NVIDIA/warp/warp/examples/fem/example_diffusion_3d.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.
###########################################################################
# Example Diffusion 3D
#
# This example solves a 3d diffusion problem:
#
# nu Div u = 1
#
# with homogeneous Neumann conditions on horizontal sides
# and homogeneous Dirichlet boundary conditions other sides.
###########################################################################
import warp as wp
import warp.fem as fem
from warp.sparse import bsr_axpy
# Import example utilities
# Make sure that works both when imported as module and run as standalone file
try:
from .bsr_utils import bsr_cg
from .example_diffusion import diffusion_form, linear_form
from .mesh_utils import gen_hexmesh, gen_tetmesh
from .plot_utils import Plot
except ImportError:
from bsr_utils import bsr_cg
from example_diffusion import diffusion_form, linear_form
from mesh_utils import gen_hexmesh, gen_tetmesh
from plot_utils import Plot
@fem.integrand
def vert_boundary_projector_form(
s: fem.Sample,
domain: fem.Domain,
u: fem.Field,
v: fem.Field,
):
# Non-zero mass on vertical sides only
w = 1.0 - wp.abs(fem.normal(domain, s)[1])
return w * u(s) * v(s)
class Example:
def __init__(
self,
quiet=False,
degree=2,
resolution=10,
mesh="grid",
serendipity=False,
viscosity=2.0,
boundary_compliance=0.0,
):
self._quiet = quiet
self._viscosity = viscosity
self._boundary_compliance = boundary_compliance
res = wp.vec3i(resolution, resolution // 2, resolution * 2)
if mesh == "tet":
pos, tet_vtx_indices = gen_tetmesh(
res=res,
bounds_lo=wp.vec3(0.0, 0.0, 0.0),
bounds_hi=wp.vec3(1.0, 0.5, 2.0),
)
self._geo = fem.Tetmesh(tet_vtx_indices, pos)
elif mesh == "hex":
pos, hex_vtx_indices = gen_hexmesh(
res=res,
bounds_lo=wp.vec3(0.0, 0.0, 0.0),
bounds_hi=wp.vec3(1.0, 0.5, 2.0),
)
self._geo = fem.Hexmesh(hex_vtx_indices, pos)
elif mesh == "nano":
volume = wp.Volume.allocate(min=[0, 0, 0], max=[1.0, 0.5, 2.0], voxel_size=1.0 / res[0], bg_value=None)
self._geo = fem.Nanogrid(volume)
else:
self._geo = fem.Grid3D(
res=res,
bounds_lo=wp.vec3(0.0, 0.0, 0.0),
bounds_hi=wp.vec3(1.0, 0.5, 2.0),
)
# Domain and function spaces
element_basis = fem.ElementBasis.SERENDIPITY if serendipity else None
self._scalar_space = fem.make_polynomial_space(self._geo, degree=degree, element_basis=element_basis)
# Scalar field over our function space
self._scalar_field: fem.DiscreteField = self._scalar_space.make_field()
self.renderer = Plot()
def step(self):
geo = self._geo
domain = fem.Cells(geometry=geo)
# Right-hand-side
test = fem.make_test(space=self._scalar_space, domain=domain)
rhs = fem.integrate(linear_form, fields={"v": test})
# Weakly-imposed boundary conditions on Y sides
with wp.ScopedTimer("Integrate"):
boundary = fem.BoundarySides(geo)
bd_test = fem.make_test(space=self._scalar_space, domain=boundary)
bd_trial = fem.make_trial(space=self._scalar_space, domain=boundary)
bd_matrix = fem.integrate(vert_boundary_projector_form, fields={"u": bd_trial, "v": bd_test}, nodal=True)
# Diffusion form
trial = fem.make_trial(space=self._scalar_space, domain=domain)
matrix = fem.integrate(diffusion_form, fields={"u": trial, "v": test}, values={"nu": self._viscosity})
if self._boundary_compliance == 0.0:
# Hard BC: project linear system
bd_rhs = wp.zeros_like(rhs)
fem.project_linear_system(matrix, rhs, bd_matrix, bd_rhs)
else:
# Weak BC: add together diffusion and boundary condition matrices
boundary_strength = 1.0 / self._boundary_compliance
bsr_axpy(x=bd_matrix, y=matrix, alpha=boundary_strength, beta=1)
with wp.ScopedTimer("CG solve"):
x = wp.zeros_like(rhs)
bsr_cg(matrix, b=rhs, x=x, quiet=self._quiet)
self._scalar_field.dof_values = x
def render(self):
self.renderer.add_volume("solution", self._scalar_field)
if __name__ == "__main__":
import argparse
wp.set_module_options({"enable_backward": False})
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--resolution", type=int, default=10, help="Grid resolution.")
parser.add_argument("--degree", type=int, default=2, help="Polynomial degree of shape functions.")
parser.add_argument("--serendipity", action="store_true", default=False, help="Use Serendipity basis functions.")
parser.add_argument("--viscosity", type=float, default=2.0, help="Fluid viscosity parameter.")
parser.add_argument(
"--boundary_compliance", type=float, default=0.0, help="Dirichlet boundary condition compliance."
)
parser.add_argument("--mesh", choices=("grid", "tet", "hex", "nano"), default="grid", help="Mesh type.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--quiet", action="store_true", help="Suppresses the printing out of iteration residuals.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(
quiet=args.quiet,
degree=args.degree,
resolution=args.resolution,
mesh=args.mesh,
serendipity=args.serendipity,
viscosity=args.viscosity,
boundary_compliance=args.boundary_compliance,
)
example.step()
example.render()
if not args.headless:
example.renderer.plot()
| 6,660 | Python | 36.21229 | 117 | 0.60991 |
NVIDIA/warp/warp/examples/fem/plot_utils.py | from typing import Set
import numpy as np
from warp.fem import DiscreteField
def plot_grid_surface(field, axes=None):
import matplotlib.pyplot as plt
from matplotlib import cm
if axes is None:
fig, axes = plt.subplots(subplot_kw={"projection": "3d"})
node_positions = field.space.node_grid()
# Make data.
X = node_positions[0]
Y = node_positions[1]
Z = field.dof_values.numpy().reshape(X.shape)
# Plot the surface.
return axes.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
def plot_tri_surface(field, axes=None):
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.tri.triangulation import Triangulation
if axes is None:
fig, axes = plt.subplots(subplot_kw={"projection": "3d"})
node_positions = field.space.node_positions().numpy()
triangulation = Triangulation(
x=node_positions[:, 0], y=node_positions[:, 1], triangles=field.space.node_triangulation()
)
Z = field.dof_values.numpy()
# Plot the surface.
return axes.plot_trisurf(triangulation, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)
def plot_scatter_surface(field, axes=None):
import matplotlib.pyplot as plt
from matplotlib import cm
if axes is None:
fig, axes = plt.subplots(subplot_kw={"projection": "3d"})
X, Y = field.space.node_positions().numpy().T
# Make data.
Z = field.dof_values.numpy().reshape(X.shape)
# Plot the surface.
return axes.scatter(X, Y, Z, c=Z, cmap=cm.coolwarm)
def plot_surface(field, axes=None):
if hasattr(field.space, "node_grid"):
return plot_grid_surface(field, axes)
elif hasattr(field.space, "node_triangulation"):
return plot_tri_surface(field, axes)
else:
return plot_scatter_surface(field, axes)
def plot_grid_color(field, axes=None):
import matplotlib.pyplot as plt
from matplotlib import cm
if axes is None:
fig, axes = plt.subplots()
node_positions = field.space.node_grid()
# Make data.
X = node_positions[0]
Y = node_positions[1]
Z = field.dof_values.numpy().reshape(X.shape)
# Plot the surface.
return axes.pcolormesh(X, Y, Z, cmap=cm.coolwarm)
def plot_velocities(field, axes=None):
import matplotlib.pyplot as plt
if axes is None:
fig, axes = plt.subplots()
node_positions = field.space.node_positions().numpy()
# Make data.
X = node_positions[:, 0]
Y = node_positions[:, 1]
vel = field.dof_values.numpy()
u = np.ascontiguousarray(vel[:, 0])
v = np.ascontiguousarray(vel[:, 1])
u = u.reshape(X.shape)
v = v.reshape(X.shape)
return axes.quiver(X, Y, u, v)
def plot_grid_streamlines(field, axes=None):
import matplotlib.pyplot as plt
if axes is None:
fig, axes = plt.subplots()
node_positions = field.space.node_grid()
# Make data.
X = node_positions[0][:, 0]
Y = node_positions[1][0, :]
vel = field.dof_values.numpy()
u = np.ascontiguousarray(vel[:, 0])
v = np.ascontiguousarray(vel[:, 1])
u = np.transpose(u.reshape(node_positions[0].shape))
v = np.transpose(v.reshape(node_positions[0].shape))
splot = axes.streamplot(X, Y, u, v, density=2)
splot.axes = axes
return splot
def plot_3d_scatter(field, axes=None):
import matplotlib.pyplot as plt
from matplotlib import cm
if axes is None:
fig, axes = plt.subplots(subplot_kw={"projection": "3d"})
X, Y, Z = field.space.node_positions().numpy().T
# Make data.
f = field.dof_values.numpy().reshape(X.shape)
# Plot the surface.
return axes.scatter(X, Y, Z, c=f, cmap=cm.coolwarm)
def plot_3d_velocities(field, axes=None):
import matplotlib.pyplot as plt
if axes is None:
fig, axes = plt.subplots(subplot_kw={"projection": "3d"})
X, Y, Z = field.space.node_positions().numpy().T
vel = field.dof_values.numpy()
u = np.ascontiguousarray(vel[:, 0])
v = np.ascontiguousarray(vel[:, 1])
w = np.ascontiguousarray(vel[:, 2])
u = u.reshape(X.shape)
v = v.reshape(X.shape)
w = w.reshape(X.shape)
return axes.quiver(X, Y, Z, u, v, w, length=1.0 / X.shape[0], normalize=False)
class Plot:
def __init__(self, stage=None, default_point_radius=0.01):
self.default_point_radius = default_point_radius
self._surfaces = {}
self._surface_vectors = {}
self._volumes = {}
self._usd_renderer = None
if stage is not None:
try:
from warp.render import UsdRenderer
self._usd_renderer = UsdRenderer(stage)
except Exception as err:
print(f"Could not initialize UsdRenderer for stage '{stage}': {err}.")
def begin_frame(self, time):
if self._usd_renderer is not None:
self._usd_renderer.begin_frame(time=time)
def end_frame(self):
if self._usd_renderer is not None:
self._usd_renderer.end_frame()
def add_surface(self, name: str, field: DiscreteField):
if self._usd_renderer is not None:
points_2d = field.space.node_positions().numpy()
values = field.dof_values.numpy()
points_3d = np.hstack((points_2d, values.reshape(-1, 1)))
if hasattr(field.space, "node_triangulation"):
indices = field.space.node_triangulation()
self._usd_renderer.render_mesh(name, points=points_3d, indices=indices)
else:
self._usd_renderer.render_points(name, points=points_3d, radius=self.default_point_radius)
if name not in self._surfaces:
field_clone = field.space.make_field(space_partition=field.space_partition)
self._surfaces[name] = (field_clone, [])
self._surfaces[name][1].append(field.dof_values.numpy())
def add_surface_vector(self, name: str, field: DiscreteField):
if self._usd_renderer is not None:
points_2d = field.space.node_positions().numpy()
values = field.dof_values.numpy()
points_3d = np.hstack((points_2d + values, np.zeros_like(points_2d[:, 0]).reshape(-1, 1)))
if hasattr(field.space, "node_triangulation"):
indices = field.space.node_triangulation()
self._usd_renderer.render_mesh(name, points=points_3d, indices=indices)
else:
self._usd_renderer.render_points(name, points=points_3d, radius=self.default_point_radius)
if name not in self._surface_vectors:
field_clone = field.space.make_field(space_partition=field.space_partition)
self._surface_vectors[name] = (field_clone, [])
self._surface_vectors[name][1].append(field.dof_values.numpy())
def add_volume(self, name: str, field: DiscreteField):
if self._usd_renderer is not None:
points_3d = field.space.node_positions().numpy()
values = field.dof_values.numpy()
self._usd_renderer.render_points(name, points_3d, radius=values)
if name not in self._volumes:
field_clone = field.space.make_field(space_partition=field.space_partition)
self._volumes[name] = (field_clone, [])
self._volumes[name][1].append(field.dof_values.numpy())
def plot(self, streamlines: Set[str] = None):
if streamlines is None:
streamlines = []
return self._plot_matplotlib(streamlines)
def _plot_matplotlib(self, streamlines: Set[str] = None):
import matplotlib.animation as animation
import matplotlib.pyplot as plt
if streamlines is None:
streamlines = []
def make_animation(ax, field, values, plot_func, num_frames: int):
def animate(i):
ax.clear()
field.dof_values = values[i]
return plot_func(field, axes=ax)
return animation.FuncAnimation(
ax.figure,
animate,
interval=30,
blit=False,
frames=len(values),
)
for _name, (field, values) in self._surfaces.items():
field.dof_values = values[0]
ax = plot_surface(field).axes
if len(values) > 1:
_anim = make_animation(ax, field, values, plot_func=plot_surface, num_frames=len(values))
for name, (field, values) in self._surface_vectors.items():
field.dof_values = values[0]
if name in streamlines and hasattr(field.space, "node_grid"):
ax = plot_grid_streamlines(field).axes
else:
ax = plot_velocities(field).axes
if len(values) > 1:
_anim = make_animation(ax, field, values, plot_func=plot_velocities, num_frames=len(values))
for _name, (field, values) in self._volumes.items():
field.dof_values = values[0]
ax = plot_3d_scatter(field).axes
plt.show()
| 9,076 | Python | 29.979522 | 112 | 0.608969 |
NVIDIA/warp/warp/examples/core/example_raymarch.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.
###########################################################################
# Example Ray March
#
# Shows how to implement an SDF ray marching based renderer. Please see
# https://iquilezles.org/www/articles/distfunctions/distfunctions.htm
# for reference on different distance functions.
#
###########################################################################
import warp as wp
@wp.func
def sdf_sphere(p: wp.vec3, r: float):
return wp.length(p) - r
@wp.func
def sdf_box(upper: wp.vec3, p: wp.vec3):
qx = wp.abs(p[0]) - upper[0]
qy = wp.abs(p[1]) - upper[1]
qz = wp.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 sdf_plane(p: wp.vec3, plane: wp.vec4):
return plane[0] * p[0] + plane[1] * p[1] + plane[2] * p[2] + plane[3]
@wp.func
def op_union(d1: float, d2: float):
return wp.min(d1, d2)
@wp.func
def op_subtract(d1: float, d2: float):
return wp.max(-d1, d2)
@wp.func
def op_intersect(d1: float, d2: float):
return wp.max(d1, d2)
# simple scene
@wp.func
def sdf(p: wp.vec3):
sphere_1 = wp.vec3(0.0, 0.75, 0.0)
d = op_subtract(sdf_sphere(p - sphere_1, 0.75), sdf_box(wp.vec3(1.0, 0.5, 0.5), p))
# ground plane
d = op_union(d, sdf_plane(p, wp.vec4(0.0, 1.0, 0.0, 1.0)))
return d
@wp.func
def normal(p: wp.vec3):
eps = 1.0e-5
# compute gradient of the SDF using finite differences
dx = sdf(p + wp.vec3(eps, 0.0, 0.0)) - sdf(p - wp.vec3(eps, 0.0, 0.0))
dy = sdf(p + wp.vec3(0.0, eps, 0.0)) - sdf(p - wp.vec3(0.0, eps, 0.0))
dz = sdf(p + wp.vec3(0.0, 0.0, eps)) - sdf(p - wp.vec3(0.0, 0.0, eps))
return wp.normalize(wp.vec3(dx, dy, dz))
@wp.func
def shadow(ro: wp.vec3, rd: wp.vec3):
t = float(0.0)
s = float(1.0)
for _ in range(64):
d = sdf(ro + t * rd)
t = t + wp.clamp(d, 0.0001, 2.0)
h = wp.clamp(4.0 * d / t, 0.0, 1.0)
s = wp.min(s, h * h * (3.0 - 2.0 * h))
if t > 8.0:
return 1.0
return s
@wp.kernel
def draw(cam_pos: wp.vec3, cam_rot: wp.quat, width: int, height: int, pixels: wp.array(dtype=wp.vec3)):
tid = wp.tid()
x = tid % width
y = tid // width
# compute pixel coordinates
sx = (2.0 * float(x) - float(width)) / float(height)
sy = (2.0 * float(y) - float(height)) / float(height)
# compute view ray
ro = cam_pos
rd = wp.quat_rotate(cam_rot, wp.normalize(wp.vec3(sx, sy, -2.0)))
t = float(0.0)
# ray march
for _ in range(128):
d = sdf(ro + rd * t)
t = t + d
if d < 0.01:
p = ro + rd * t
n = normal(p)
l = wp.normalize(wp.vec3(0.6, 0.4, 0.5))
# half-vector
h = wp.normalize(l - rd)
diffuse = wp.dot(n, l)
specular = wp.clamp(wp.dot(n, h), 0.0, 1.0) ** 80.0
fresnel = 0.04 + 0.96 * wp.clamp(1.0 - wp.dot(h, l), 0.0, 1.0) ** 5.0
intensity = 2.0
result = (
wp.vec3(0.85, 0.9, 0.95)
* (diffuse * (1.0 - fresnel) + specular * fresnel * 10.0)
* shadow(p, l)
* intensity
)
# gamma
pixels[tid] = wp.vec3(
wp.clamp(result[0] ** 2.2, 0.0, 1.0),
wp.clamp(result[1] ** 2.2, 0.0, 1.0),
wp.clamp(result[2] ** 2.2, 0.0, 1.0),
)
else:
pixels[tid] = wp.vec3(0.4, 0.45, 0.5) * 1.5
class Example:
def __init__(self, height=1024, width=2048):
self.width = width
self.height = height
self.cam_pos = (-1.25, 1.0, 2.0)
self.cam_rot = wp.quat_rpy(-0.5, -0.5, 0.0)
self.pixels = wp.zeros(self.width * self.height, dtype=wp.vec3)
def render(self):
with wp.ScopedTimer("render"):
wp.launch(
kernel=draw,
dim=self.width * self.height,
inputs=[self.cam_pos, self.cam_rot, self.width, self.height, self.pixels],
)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode, suppressing the opening of any graphical windows.",
)
parser.add_argument("--width", type=int, default=2048, help="Output image width in pixels.")
parser.add_argument("--height", type=int, default=1024, help="Output image height in pixels.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(height=args.height, width=args.width)
example.render()
if not args.headless:
import matplotlib.pyplot as plt
plt.imshow(
example.pixels.numpy().reshape((example.height, example.width, 3)),
origin="lower",
interpolation="antialiased",
)
plt.show()
| 5,515 | Python | 26.858586 | 103 | 0.550499 |
NVIDIA/warp/warp/examples/core/example_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.
###########################################################################
# OpenGL renderer example
#
# Demonstrates how to set up tiled rendering and retrieves the pixels from
# OpenGLRenderer as a Warp array while keeping all memory on the GPU.
#
###########################################################################
import numpy as np
import warp as wp
import warp.render
class Example:
def __init__(self, num_tiles=4, custom_tile_arrangement=False):
self.renderer = wp.render.OpenGLRenderer(vsync=False)
instance_ids = []
if custom_tile_arrangement:
positions = []
sizes = []
else:
positions = None
sizes = None
if num_tiles > 1:
# set up instances to hide one of the capsules in each tile
for i in range(num_tiles):
instances = [j for j in np.arange(13) if j != i + 2]
instance_ids.append(instances)
if custom_tile_arrangement:
angle = np.pi * 2.0 / num_tiles * i
positions.append((int(np.cos(angle) * 150 + 250), int(np.sin(angle) * 150 + 250)))
sizes.append((150, 150))
self.renderer.setup_tiled_rendering(instance_ids, tile_positions=positions, tile_sizes=sizes)
self.renderer.render_ground()
def render(self):
time = self.renderer.clock_time
self.renderer.begin_frame(time)
for i in range(10):
self.renderer.render_capsule(
f"capsule_{i}",
[i - 5.0, np.sin(time + i * 0.2), -3.0],
[0.0, 0.0, 0.0, 1.0],
radius=0.5,
half_height=0.8,
)
self.renderer.render_cylinder(
"cylinder",
[3.2, 1.0, np.sin(time + 0.5)],
np.array(wp.quat_from_axis_angle(wp.vec3(1.0, 0.0, 0.0), wp.sin(time + 0.5))),
radius=0.5,
half_height=0.8,
)
self.renderer.render_cone(
"cone",
[-1.2, 1.0, 0.0],
np.array(wp.quat_from_axis_angle(wp.vec3(0.707, 0.707, 0.0), time)),
radius=0.5,
half_height=0.8,
)
self.renderer.end_frame()
if __name__ == "__main__":
import argparse
import distutils.util
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument("--num_tiles", type=int, default=4, help="Number of viewports to render in a single frame.")
parser.add_argument(
"--show_plot",
type=lambda x: bool(distutils.util.strtobool(x.strip())),
default=True,
help="Display the pixels in an additional matplotlib figure.",
)
parser.add_argument("--render_mode", type=str, choices=("depth", "rgb"), default="depth", help="")
parser.add_argument(
"--split_up_tiles",
type=lambda x: bool(distutils.util.strtobool(x.strip())),
default=True,
help="Whether to split tiles into subplots when --show_plot is True.",
)
parser.add_argument("--custom_tile_arrangement", action="store_true", help="Apply custom tile arrangement.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(num_tiles=args.num_tiles, custom_tile_arrangement=args.custom_tile_arrangement)
channels = 1 if args.render_mode == "depth" else 3
if args.show_plot:
import matplotlib.pyplot as plt
if args.split_up_tiles:
pixels = wp.zeros(
(args.num_tiles, example.renderer.tile_height, example.renderer.tile_width, channels),
dtype=wp.float32,
)
ncols = int(np.ceil(np.sqrt(args.num_tiles)))
nrows = int(np.ceil(args.num_tiles / float(ncols)))
img_plots = []
aspect_ratio = example.renderer.tile_height / example.renderer.tile_width
fig, axes = plt.subplots(
ncols=ncols,
nrows=nrows,
constrained_layout=True,
figsize=(ncols * 3.5, nrows * 3.5 * aspect_ratio),
squeeze=False,
sharex=True,
sharey=True,
num=1,
)
tile_temp = np.zeros(
(example.renderer.tile_height, example.renderer.tile_width, channels), dtype=np.float32
)
for dim in range(ncols * nrows):
ax = axes[dim // ncols, dim % ncols]
if dim >= args.num_tiles:
ax.axis("off")
continue
if args.render_mode == "depth":
img_plots.append(
ax.imshow(
tile_temp,
vmin=example.renderer.camera_near_plane,
vmax=example.renderer.camera_far_plane,
)
)
else:
img_plots.append(ax.imshow(tile_temp))
else:
fig = plt.figure(1)
pixels = wp.zeros(
(example.renderer.screen_height, example.renderer.screen_width, channels), dtype=wp.float32
)
if args.render_mode == "depth":
img_plot = plt.imshow(
pixels.numpy(), vmin=example.renderer.camera_near_plane, vmax=example.renderer.camera_far_plane
)
else:
img_plot = plt.imshow(pixels.numpy())
plt.ion()
plt.show()
while example.renderer.is_running():
example.render()
if args.show_plot and plt.fignum_exists(1):
if args.split_up_tiles:
pixel_shape = (args.num_tiles, example.renderer.tile_height, example.renderer.tile_width, channels)
else:
pixel_shape = (example.renderer.screen_height, example.renderer.screen_width, channels)
if pixel_shape != pixels.shape:
# make sure we resize the pixels array to the right dimensions if the user resizes the window
pixels = wp.zeros(pixel_shape, dtype=wp.float32)
example.renderer.get_pixels(pixels, split_up_tiles=args.split_up_tiles, mode=args.render_mode)
if args.split_up_tiles:
pixels_np = pixels.numpy()
for i, img_plot in enumerate(img_plots):
img_plot.set_data(pixels_np[i])
else:
img_plot.set_data(pixels.numpy())
fig.canvas.draw()
fig.canvas.flush_events()
example.renderer.clear()
| 7,490 | Python | 39.711956 | 119 | 0.524967 |
NVIDIA/warp/warp/examples/core/example_dem.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.
###########################################################################
# Example DEM
#
# Shows how to implement a DEM particle simulation with cohesion between
# particles. Neighbors are found using the wp.HashGrid class, and
# wp.hash_grid_query(), wp.hash_grid_query_next() kernel methods.
#
###########################################################################
import numpy as np
import warp as wp
import warp.render
@wp.func
def contact_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 apply_forces(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_f: wp.array(dtype=wp.vec3),
radius: float,
k_contact: float,
k_damp: float,
k_friction: float,
k_mu: float,
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
x = particle_x[i]
v = particle_v[i]
f = wp.vec3()
# ground contact
n = wp.vec3(0.0, 1.0, 0.0)
c = wp.dot(n, x)
cohesion_ground = 0.02
cohesion_particle = 0.0075
if c < cohesion_ground:
f = f + contact_force(n, v, c, k_contact, k_damp, 100.0, 0.5)
# particle contact
neighbors = wp.hash_grid_query(grid, x, radius * 5.0)
for index in neighbors:
if index != i:
# compute distance to point
n = x - particle_x[index]
d = wp.length(n)
err = d - radius * 2.0
if err <= cohesion_particle:
n = n / d
vrel = v - particle_v[index]
f = f + contact_force(n, vrel, err, k_contact, k_damp, k_friction, k_mu)
particle_f[i] = f
@wp.kernel
def integrate(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
f: wp.array(dtype=wp.vec3),
gravity: wp.vec3,
dt: float,
inv_mass: float,
):
tid = wp.tid()
v_new = v[tid] + f[tid] * inv_mass * dt + gravity * dt
x_new = x[tid] + v_new * dt
v[tid] = v_new
x[tid] = x_new
class Example:
def __init__(self, stage_path="example_dem.usd"):
fps = 60
self.frame_dt = 1.0 / fps
self.sim_substeps = 64
self.sim_dt = self.frame_dt / self.sim_substeps
self.sim_time = 0.0
self.point_radius = 0.1
self.k_contact = 8000.0
self.k_damp = 2.0
self.k_friction = 1.0
self.k_mu = 100000.0 # for cohesive materials
self.inv_mass = 64.0
self.grid = wp.HashGrid(128, 128, 128)
self.grid_cell_size = self.point_radius * 5.0
self.points = self.particle_grid(32, 64, 32, (0.0, 0.5, 0.0), self.point_radius, 0.1)
self.x = wp.array(self.points, dtype=wp.vec3)
self.v = wp.array(np.ones([len(self.x), 3]) * np.array([0.0, 0.0, 15.0]), dtype=wp.vec3)
self.f = wp.zeros_like(self.v)
if stage_path:
self.renderer = wp.render.UsdRenderer(stage_path)
self.renderer.render_ground()
else:
self.renderer = None
self.use_cuda_graph = wp.get_device().is_cuda
if self.use_cuda_graph:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
for _ in range(self.sim_substeps):
wp.launch(
kernel=apply_forces,
dim=len(self.x),
inputs=[
self.grid.id,
self.x,
self.v,
self.f,
self.point_radius,
self.k_contact,
self.k_damp,
self.k_friction,
self.k_mu,
],
)
wp.launch(
kernel=integrate,
dim=len(self.x),
inputs=[self.x, self.v, self.f, (0.0, -9.8, 0.0), self.sim_dt, self.inv_mass],
)
def step(self):
with wp.ScopedTimer("step"):
with wp.ScopedTimer("grid build", active=False):
self.grid.build(self.x, self.grid_cell_size)
if self.use_cuda_graph:
wp.capture_launch(self.graph)
else:
self.simulate()
self.sim_time += self.frame_dt
def render(self):
if self.renderer is None:
return
with wp.ScopedTimer("render"):
self.renderer.begin_frame(self.sim_time)
self.renderer.render_points(
points=self.x.numpy(), radius=self.point_radius, name="points", colors=(0.8, 0.3, 0.2)
)
self.renderer.end_frame()
# creates a grid of particles
def particle_grid(self, 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))
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--device", type=str, default=None, help="Override the default Warp device.")
parser.add_argument(
"--stage_path",
type=lambda x: None if x == "None" else str(x),
default="example_dem.usd",
help="Path to the output USD file.",
)
parser.add_argument("--num_frames", type=int, default=200, help="Total number of frames.")
args = parser.parse_known_args()[0]
with wp.ScopedDevice(args.device):
example = Example(stage_path=args.stage_path)
for _ in range(args.num_frames):
example.step()
example.render()
if example.renderer:
example.renderer.save()
| 6,722 | Python | 27.854077 | 118 | 0.542844 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.