GithubHelp home page GithubHelp logo

luisagroup / luisacompute Goto Github PK

View Code? Open in Web Editor NEW
647.0 26.0 56.0 157.24 MB

High-Performance Rendering Framework on Stream Architectures

License: BSD 3-Clause "New" or "Revised" License

CMake 0.51% C++ 78.95% C 11.81% Dockerfile 0.01% Python 2.41% Objective-C++ 0.01% Cuda 0.44% Lua 0.33% Metal 0.34% Rust 5.19% Shell 0.01%
cpu gpu high-performance cross-platform cuda directx graphics ispc llvm metal

luisacompute's Introduction

LuisaCompute

teaser

LuisaCompute is a high-performance cross-platform computing framework for graphics and beyond.

LuisaCompute is also the rendering framework described in the SIGGRAPH Asia 2022 paper

LuisaRender: A High-Performance Rendering Framework with Layered and Unified Interfaces on Stream Architectures.

See also LuisaRender for the rendering application as described in the paper; and please visit the project page for other information about the paper and the project.

Welcome to join the discussion channel on Discord!

对于**大陆的用户,也欢迎加入我们的 QQ 群组:295618382。

Table of Contents

Overview

LuisaCompute seeks to balance the seemingly ever-conflicting pursuits for unification, programmability, and performance. To achieve this goal, we design three major components:

  • A domain-specific language (DSL) embedded inside modern C++ for kernel programming exploiting JIT code generation and compilation;
  • A unified runtime with resource wrappers for cross-platform resource management and command scheduling; and
  • Multiple optimized backends, including CUDA, DirectX, Metal, and CPU.

To demonstrate the practicality of the system, we also build a Monte Carlo renderer, LuisaRender, atop the framework, which is faster than the state-of-the-art rendering frameworks on modern GPUs.

Embedded Domain-Specific Language

The DSL in our system provides a unified approach to authoring kernels, i.e., programmable computation tasks on the device. Distinct from typical graphics APIs that use standalone shading languages for device code, our system unifies the authoring of both the host-side logic and device-side kernels into the same language, i.e., modern C++.

The implementation purely relies on the C++ language itself, without any custom preprocessing pass or compiler extension. We exploit meta-programming techniques to simulate the syntax, and function/operator overloading to dynamically trace the user-defined kernels. ASTs are constructed during the tracing as an intermediate representation and later handed over to the backends for generating concrete, platform-dependent shader source code.

Example program in the embedded DSL:

Callable to_srgb = [](Float3 x) {
    $if (x <= 0.00031308f) {
        x = 12.92f * x;
    } $else {
        x = 1.055f * pow(x, 1.f / 2.4f) - .055f;
    };
    return x;
};
Kernel2D fill = [&](ImageFloat image) {
    auto coord = dispatch_id().xy();
    auto size = make_float2(dispatch_size().xy());
    auto rg = make_float2(coord) / size;
    // invoke the callable
    auto srgb = to_srgb(make_float3(rg, 1.f));
    image.write(coord, make_float4(srgb, 1.f));
};

Unified Runtime with Resource Wrappers

Like the RHIs in game engines, we introduce an abstract runtime layer to re-unify the fragmented graphics APIs across platforms. It extracts the common concepts and constructs shared by the backend APIs and plays the bridging role between the high-level frontend interfaces and the low-level backend implementations.

On the programming interfaces for users, we provide high-level resource wrappers to ease programming and eliminate boilerplate code. They are strongly and statically typed modern C++ objects, which not only simplify the generation of commands via convenient member methods but also support close interaction with the DSL. Moreover, with the resource usage information in kernels and commands, the runtime automatically probes the dependencies between commands and re-schedules them to improve hardware utilization.

Multiple Backends

The backends are the final realizers of computation. They generate concrete shader sources from the ASTs and compile them into native shaders. They implement the virtual device interfaces with low-level platform-dependent API calls and translate the intermediate command representations into native kernel launches and command dispatches.

Currently, we have 3 working GPU backends for the C++ and Python frontends, based on CUDA, Metal, and DirectX, respectively, and a CPU backend (re-)implemented in Rust for debugging purpose and fallback.

Python Frontend

Besides the native C++ DSL and runtime interfaces, we are also working on a Python frontend and have published early-access packages to PyPI. You may install the pre-built wheels with pip (Python >= 3.10 required):

python -m pip install luisa-python

You may also build your own wheels with pip:

python -m pip wheel <path-to-project> -w <output-dir>

Examples using the Python frontend can be found under src/tests/python.

Note: Due to the different syntax and idioms between Python and C++, the Python frontend does not 1:1 reflects the C++ DSL and APIs. For instance, Python does not have a dedicated reference type qualifier, so we follow the Python idiom that structures and arrays are passed as references to @luisa.func and built-in types (scalar, vector, matrix, etc.) as values by default.

C API and Frontends in Other Languages

We are also making a C API for creating other language bindings and frontends (e.g., in Rust and C#).

Building

Note: LuisaCompute is a rendering framework rather than a renderer itself. It is designed to provide general computation functionalities on modern stream-processing hardware, on which high-performance, cross-platform graphics applications can be easily built. If you would like to just try a Monte Carlo renderer out of the box rather than building one from scratch, please see LuisaRender.

Preparation

  • Check your hardware and platform. Currently, we support CUDA on Linux and Windows; DirectX on Windows; Metal on macOS; and CPU on all the major platforms. For CUDA, an RTX-enabled graphics card, e.g., NVIDIA RTX 20 and 30 series, is required. For DirectX, a DirectX-12.1 & Shader Model 6.5 compatible graphics card is required.

  • Prepare the environment and dependencies. We recommend using the latest IDEs, Compilers, XMake/CMake, CUDA drivers, etc. Since we aggressively use new technologies like C++20 and OptiX 8, you may need to, for example, upgrade your VS to 2019 or 2022 and install CUDA 11.7+ and NVIDIA driver R535+.

  • Clone the repo with the --recursive option:

    git clone -b next https://github.com/LuisaGroup/LuisaCompute.git/ --recursive

    Since we use Git submodules to manage third-party dependencies, a --recursive clone is required.

  • Detailed requirements for each platform are listed in BUILD.md.

Build via the Bootstrap Script

The easiest way to build LuisaCompute is to use the bootstrap script. It can even download and install the required dependencies and build the project.

python bootstrap.py cmake -f cuda -b # build with CUDA backend using CMake
python bootstrap.py cmake -f cuda -b -- -DCMAKE_BUILD_TYPE=RelWithDebInfo # everything after -- will be passed to CMake

You may specify -f all to enable all available features on your platform.

To install certain dependencies, you can use the --install or -i option. For example, to install Rust, you can use:

python bootstrap.py -i rust

Alternatively, the bootstrap script can output a configuration file for build system without actually building the project. This is useful when you want to use the project inside IDE.

python bootstrap.py cmake -f cuda -c -o cmake-build-release # generate CMake configuration in ./cmake-build-release

Please use python bootstrap.py --help for more details.

Build from Source with XMake/CMake

LuisaCompute follows the standard XMake and CMake build process. Please see also BUILD.md for details on platform requirements, configuration options, and other precautions.

Usage

A Minimal Example

Using LuisaCompute to construct a graphics application basically involves the following steps:

  1. Create a Context and loading a Device plug-in;
  2. Create a Stream for command submission and other device resources (e.g., Buffer<T>s for linear storage, Image<T>s for 2D readable/writable textures, and Meshes and Accels for ray-scene intersection testing structures) via Device's create_* interfaces;
  3. Author Kernels to describe the on-device computation tasks, and compile them into Shaders via Device's compile interface;
  4. Generate Commands via each resource's interface (e.g., Buffer<T>::copy_to), or Shader's operator() and dispatch, and submit them to the stream;
  5. Wait for the results by inserting a synchronize phoney command to the Stream.

Putting the above together, a minimal example program that write gradient color to an image would look like

#include <luisa-compute.h>

// For the DSL sugar macros like $if.
// We exclude this header from <luisa-compute.h> to avoid pollution.
// So you have to include it explicitly to use the sugar macros.
#include <dsl/sugar.h>

using namespace luisa;
using namespace luisa::compute;

int main(int argc, char *argv[]) {

    // Step 1.1: Create a context
    Context context{argv[0]};
    
    // Step 1.2: Load the CUDA backend plug-in and create a device
    Device device = context.create_device("cuda");
    
    // Step 2.1: Create a stream for command submission
    Stream stream = device.create_stream();
    
    // Step 2.2: Create an 1024x1024 image with 4-channel 8-bit storage for each pixel; the template 
    //           argument `float` indicates that pixel values reading from or writing to the image
    //           are converted from `byte4` to `float4` or `float4` to `byte4` automatically
    Image<float> device_image = device.create_image<float>(PixelStorage::BYTE4, 1024u, 1024u, 0u);
    
    // Step 3.1: Define kernels to describe the device-side computation
    // 
    //           A `Callable` is a function *entity* (not directly inlined during 
    //           the AST recording) that is invocable from kernels or other callables
    Callable linear_to_srgb = [](Float4 /* alias for Var<float4> */ linear) noexcept {
        // The DSL syntax is much like the original C++
        auto x = linear.xyz();
        return make_float4(
            select(1.055f * pow(x, 1.0f / 2.4f) - 0.055f,
                   12.92f * x,
                   x <= 0.00031308f),
            linear.w);
    };
    //           A `Kernel` is an *entry* function to the device workload 
    Kernel2D fill_image_kernel = [&linear_to_srgb](ImageFloat /* alias for Var<Image<float>> */ image) noexcept {
        Var coord = dispatch_id().xy();
        Var rg = make_float2(coord) / make_float2(dispatch_size().xy());
        image->write(coord, linear_to_srgb(make_float4(rg, 1.0f, 1.0f)));
    };
    
    // Step 3.2: Compile the kernel into a shader (i.e., a runnable object on the device)
    auto fill_image = device.compile(fill_image_kernel);
    
    // Prepare the host memory for holding the image
    std::vector<std::byte> download_image(1024u * 1024u * 4u);
    
    // Step 4: Generate commands from resources and shaders, and
    //         submit them to the stream to execute on the device
    stream << fill_image(device_image.view(0)).dispatch(1024u, 1024u)
           << device_image.copy_to(download_image.data())
           << synchronize();// Step 5: Synchronize the stream
   
   // Now, you have the device-computed pixels in the host memory!
   your_image_save_function("color.png", downloaded_image, 1024u, 1024u, 4u);
}

Basic Types

In addition to standard C++ scalar types (e.g., int, uint --- alias of uint32_t, float, and bool), LuisaCompute provides vector/matrix types for 3D graphics, including the following types:

// boolean vectors
using bool2 = Vector<bool, 2>;   // alignment: 2B
using bool3 = Vector<bool, 3>;   // alignment: 4B
using bool4 = Vector<bool, 4>;   // alignment: 4B
// signed and unsigned integer vectors
using int2 = Vector<int, 2>;     // alignment: 8B
using int3 = Vector<int, 3>;     // alignment: 16B
using int4 = Vector<int, 4>;     // alignment: 16B
using uint2 = Vector<uint, 2>;   // alignment: 8B
using uint3 = Vector<uint, 3>;   // alignment: 16B
using uint4 = Vector<uint, 4>;   // alignment: 16B
// floating-point vectors and matrices
using float2 = Vector<float, 2>; // alignment: 8B
using float3 = Vector<float, 3>; // alignment: 16B
using float4 = Vector<float, 4>; // alignment: 16B
using float2x2 = Matrix<2>;      // column-major, alignment: 8B
using float3x3 = Matrix<3>;      // column-major, alignment: 16B
using float4x4 = Matrix<4>;      // column-major, alignment: 16B

⚠️ Please pay attention to the alignment of 3D vectors and matrices --- they are aligned like 4D ones rather than packed. Also, we do not provide 64-bit integer or floating-point vector/matrix types, as they are less useful and typically unsupported on GPUs.

To make vectors/matrices, we provide make_* and read-only swizzle interfaces, e.g.,

auto a = make_float2();       // (0.f, 0.f)
auto b = make_int3(1);        // (1,   1,   1)
auto c = make_uint3(b);       // (1u,  1u,  1u): converts from a same-dimentional but (possibly) differently typed vector
auto d = make_float3(a, 1.f); // (0.f, 0.f, 1.f): construct float3 from float2 and a float scalar
auto e = d.zzxy();            // (1.f, 1.f, 0.f, 0.f): swizzle
auto m = make_float2x2(1.f);  // ((1.f, 0.f,), (0.f, 1.f)): diagonal matrix from a scalar
...

Operators are also overloaded for scalar-vector, vector-vector, scalar-matrix, vector-matrix, and matrix-matrix calculations, e.g.,

auto one = make_float2(1.f); // (1.f, 1.f)
auto two = 2.f;
auto three = one + two;      // (3.f, 3.f), scalar broadcast to vector
auto m2 = make_float2(2.f);  // ((2.f, 0.f), (0.f, 2.f))
auto m3 = 1.5f * m2;         // ((3.f, 0.f), (0.f, 3.f)), scalar-matrix multiplication
auto v = m3 * one;           // (3.f, 3.f), matrix-vector multiplication, the vector should always
                             // appear at the right-hand side and is interpreted as a column vector
auto m6 = m2 * m3;           // ((6.f, 0.f), (0.f, 6.f)), matrix-matrix multiplication

The scalar, vector, matrix, and array types are also supported in the DSL, together with make_*, swizzles, and operators. Just wrap them in the Var<T> template or use the pre-defined aliases:

// scalar types; note that 64-bit ones are not supported
using Int = Var<int>;
using UInt = Var<uint>;
using Float = Var<float>;
using Bool = Var<bool>;

// vector types
using Int2 = Var<int2>; // = Var<Vector<int, 2>>
using Int3 = Var<int3>; // = Var<Vector<int, 3>>
/* ... */

// matrix types
using Float2x2 = Var<float2x2>; // = Var<Matrix<2>>
using Float3x3 = Var<float3x3>; // = Var<Matrix<3>>
using Float4x4 = Var<float4x4>; // = Var<Matrix<4>>

// array types
template<typename T, size_t N>
using ArrayVar = Var<std::array<T, N>>;

// make_*
auto a = make_float2(one);    // Float2(1.f, 1.f), suppose one = Float(1.f)
auto m = make_float2x2(a, a); // Float2x2((1.f, 1.f), (1.f, 1.f))
auto c = make_int2(a);        // Int2(1, 1)
auto d = c.xxx();             // Int3(1, 1, 1)
auto e = d[0];                // 1
/* ... */

// operators
auto v2 = a * 2.f;  // Float2(2.f, 2.f)
auto eq = v2 == v2; // Bool2(true, true)
/* ... */

⚠️ The only exception is that we disable operator&& and operator|| in the DSL for scalars. This is because the DSL does not support the short-circuit semantics. We disable them to avoid ambiguity. Please use operator& and operator| instead, which have the consistent non-short-circuit semantics on both the host and device sides.

Besides the Var<T> template, there's also an Expr<T>, which is to Var<T> what const T & is to T on the host side. In other words, Expr<T> stands for a const DSL variable reference, which does not create variables copies when passed around. However, note that the parameters of Callable/Kernel definition functions may only be Var<T>. This restriction might be removed in the future.

To conveniently convert a C++ variable to the DSL, we provide a helper template function def<T>:

auto a = def(1.f);              // equivalent to auto a = def<float>(1.f);
auto b_host = make_float2(1.f); // host C++ variable float2(1.f, 1.f)
auto b_device = def(b_host);    // device DSL variable Float2(1.f, 1.f)
/* ... */

Structures

To export a C++ data struct to the DSL, we provide a helper macro LUISA_STRUCT, which (semi-)automatically reflects the member layouts of the input structure:

// A C++ data structure
namespace foo {
struct alignas(8) S {
    float a;
    int   b;
};
}

// A reflected DSL structure
LUISA_STRUCT(foo::S, a, b) {
/* device-side member functions, e.g., */
    [[nodiscard]] auto twice_a() const noexcept { return 2.f * a; }
};

⚠️ The LUISA_STRUCT may only be used in the global namespace. The C++ structure to be exported may only contain scalar, vector, matrix, array, and other already exported structure types. The alignment of the whole structure specified with alignas will be reflected but must be under 16B; member alignments specified with alignas are not supported.

Built-in Functions

For the DSL, we provide a rich set of built-in functions, in the following categories

  • Thread coordinate and launch configuration queries, including block_id, thread_id, dispatch_size, and dispatch_id;
  • Mathematical routines, such as max, abs, sin, pow, and sqrt;
  • Resource accessing and modification methods, such as texture sampling, buffer read/write, and ray intersection;
  • Variable construction and type conversion, e.g., the aforementioned make_*, cast<T> for static type casting, and as<T> for bitwise type casting; and
  • Optimization hints for backend compilers, which currently consist of assume and unreachable.

The mathematical functions basically mirrors GLSL. We are working on the documentations that will provide more descriptions on them.

Control Flows

The DSL in LuisaCompute supports device-side control flows. They are provided as special macros prefixed with $:

$if (cond) { /*...*/ };
$if (cond) { /*...*/ } $else { /*...*/ };
$if (cond) { /*...*/ } $elif (cond2) { /*...*/ };
$if (cond) { /*...*/ } $elif (cond2) { /*...*/ } $else { /*...*/ };

$while (cond) { /*...*/ };
$for (variable, n) { /*...*/ };
$for (variable, begin, end) { /*...*/ };
$for (variable, begin, end, step) { /*...*/ };
$loop { /*...*/ }; // infinite loop, unless $break'ed

$switch (variable) {
    $case (value) { /*...*/ }; // no $break needed inside, as we automatically add one
    $default { /*...*/ };      // no $break needed inside, as we automatically add one
};

$break;
$continue;

Note that users are still able to use the native C++ control flows, i.e., if, while, etc. without the $ prefix. In that case the native control flows acts like a meta-stage to the DSL that directly controls the generation of the callables/kernels. This can be a powerful means to achieve multi-stage programming patterns. Such usages can be found throughout LuisaRender. We will cover such usage in the tutorials in the future.

Callable and Kernels

LuisaCompute supports two categories of device functions: Kernels (Kernel1D, Kernel2D, or Kernel3D) and Callables. Kernels are entries to the parallelized computation tasks on the device (equivalent to CUDA's __global__ functions). Callables are function objects invocable from kernels or other callables (i.e., like CUDA's __device__ functions). Both kinds are template classes that are constructible from C++ functions or function objects including lambda expressions:

// Define a callable from a lambda expression
Callable add_one = [](Float x) { return x + 1.f; };

// A callable may invoke another callable
Callable add_two = [&add_one](Float x) {
    add_one(add_one(x));
};

// A callable may use captured device resources or resources in the argument list
auto buffer = device.create_buffer<float>(...);
Callable copy = [&buffer](BufferFloat buffer2, UInt index) {
    auto x = buffer.read(index); // use captured resource
    buffer2.write(index, x);     // use declared resource in the argument list
};

// Define a 1D kernel from a lambda expression
Kernel1D add_one_and_some = [&buffer, &add_one](Float some, BufferFloat out) {
    auto index = dispatch_id().x;    // query thread index in the whole grid with built-in dispatch_id()
    auto x = buffer.read(index);     // use resource through capturing
    auto result = add_one(x) + some; // invoke a callable
    out.write(index, result);        // use resource in the argument list
};

⚠️ Note that parameters of the definition functions for callables and kernels must be Var<T> or Var<T> & (or their aliases).

Kernels can be compiled into shaders by the device:

auto some_shader = device.compile(some_kernel);

⚠️ Note that the compilation blocks the calling thread. For large kernels this might take a considerably long time. You may accelerate the process by compiling multiple kernels concurrently, e.g., with thread pools.

Most backends support caching the compiled shaders to accelerate future compilations of the same shader. The cache files are at <build-folder>/bin/.cache.

Backends, Context, Devices and Resources

LuisaCompute currently supports these backends:

  • CUDA
  • DirectX
  • Metal
  • CPU (Clang + LLVM)

More backends might be added in the future. A device backend is implemented as a plug-in, which follows the lc-backend-<name> naming convention and is placed under <build-folder>/bin.

The Context object is responsible for loading and managing these plug-ins and creating/destroying devices. Users have to pass the executable path (typically, argv[0]) or the runtime directory to a context's constructor (so that it's able to locate the plug-ins), and pass the backend name to create the corresponding device object.

int main(int argc, char *argv[]) {
    Context context{argv[0]};
    Device device = context.create_device("cuda");
    /* ... */
}

⚠️ Creating multiple devices inside the same application is allowed. However, the resources are not shared across devices. Visiting one device's resources from another device's commands/shaders would lead to undefined behaviors.

The device object provides methods for backend-specific operations, typicall, creating resources. LuisaCompute supports the following rousource types:

  • Buffer<T>s, which are linear memory ranges on the device for structured data storage;
  • Image<T>s and Volume<T>s, which are 2D/3D textures of scalars or vectors readable and writable from the shader, possibly with hardware-accelerated caching and format conversion;
  • BindlessArrays, which provide slots for references to buffers and textures (Images or Volumes bound with texture samplers, read-only in the shader), helpful for reducing the overhead and bypassing the limitations of binding shader parameters;
  • Meshes and Accels (short for acceleration structures) for high-performance ray intersection tests, with hardware acceleration if available (e.g., on graphics cards that feature RT-Cores);

hardware_resources

Devices are also responsible for

  • Creating Streams and Events (the former are for command submission and the latter are for host-stream and stream-stream synchronization); and
  • Compiling kernels into shaders, as introduced before.

All resources, shaders, streams, and events are C++ objects with move contrutors/assignments and following the RAII idiom, i.e., automatically calling the Device::destroy_* interfaces when destructed.

⚠️ Users may need to pay attention not to dangle a resource, e.g., accidentally releases it before the dependent commands finish.

Command Submission and Synchronization

LuisaCompute adopts the explicit command-based execution model. Conceptually, commands are description units of atomic computation tasks, such as transferring data between the device and host, or from one resource to another; building meshes and acceleration structures; populating or updating bindless arrays; and most importantly, launching shaders.

Commands are organized into command buffers and then submitted to streams which are essentially queues forwarding commands to the backend devices in a logically first-in-first-out (FIFO) manner.

The resource wrappers provide convenient methods for creating commands, e.g.,

auto buffer_upload_command   = buffer.copy_from(host_data)
auto accel_build_command     = accel.build();
auto shader_dispatch_command = shader(args...).dispatch(n);

Command buffers are group commands that are submitted together:

auto command_buffer = stream.command_buffer();
command_buffer
    << raytrace_shader(framebuffer, accel, resolution)
        .dispatch(resolution)
    << accumulate_shader(accum_image, framebuffer)
        .dispatch(resolution)
    << hdr2ldr_shader(accum_image, ldr_image)
        .dispatch(resolution)
    << ldr_image.copy_to(host_image.data())
    << commit(); // the commands are submitted to the stream together on commit()

For convenience, a stream implicitly creates a proxy object, which submit commands in the internal command buffer at the end of statements:

stream << buffer.copy_from(host_data) // a stream proxy is created on Stream::operator<<()
       << accel.build()               // consecutive commands are stored in the implicit commad buffer in the proxy object
       << raytracing(image, accel, i)
           .dispatch(width, height);  // the proxy object automatically submits the commands at the end of the statement

⚠️ Since commands are asynchronously executed, users should pay attention to resource and host data lifetimes.

The backends in LuisaCompute can automatically determine the dependencies between the commands in a command buffer, and re-schedule them into an optimized order to improve hardware ultilization. Therefore, larger command buffers might be preferred for better computation throughput.

command scheduling

Multiple streams run concurrently. Therefore, users may require synchronizations between them or with respect to the host via Events, similar to condition variables that ensure ordering across threads:

auto event = device.create_event();
stream_a << command_a
         << event.signal(); // signals an event
stream_b << event.wait()    // waits until the event signals
         << command_b;      // will be executed after the event signals
         << event.signal(); // signals again
event.synchronize();        // blocks until the event signals

Automatic Differentiation

We implemented reverse mode autodiff using source-to-source transformation. The autodiff supports control flows such as if-else and switch, as well as callables. The following example shows how to use the autodiff to compute the gradient of a function f(t, x, y) = t < 1 ? x * y : x + y with respect to x and y:

Var<float> x = ...;
Var<float> y = ...;
Var<float> t = ...;
$autodiff {
    requires_grad(x, y);
    Var<float> z;
    $if(t < 1.0) {
        auto no_grad = some_non_differentiable_function(x, y);
        z = x * y;
    }$else {
        z = callable(x, y);
    };
    backward(z);
    dx->write(tid, grad(x));
    dy->write(tid, grad(y));
};

Limitation (might be removed in the future):

  • we don't support loop with dynamic iteration count. To differentiate a loop, users have to unroll it by using for(auto i = 0;i <count;i++) { dsl_body(i); }.

Applications

We implement several proof-of-concept examples in tree under src/tests (sorry for the misleading naming; they are also test programs we used during the development). Besides, you may also found the following applications interesting:

Documentation and Tutorials

Sorry that we are still working on them. Currently, we would recommand reading the original paper and learning through the examples and applications.

If you have any problem or suggestion, please just feel free to open an issue or start a discussion. We are very happy to hear from you!

Roadmap

See ROADMAP.md.

Citation

@article{Zheng2022LuisaRender,
    author = {Zheng, Shaokun and Zhou, Zhiqian and Chen, Xin and Yan, Difei and Zhang, Chuyan and Geng, Yuefeng and Gu, Yan and Xu, Kun},
    title = {LuisaRender: A High-Performance Rendering Framework with Layered and Unified Interfaces on Stream Architectures},
    year = {2022},
    issue_date = {December 2022},
    publisher = {Association for Computing Machinery},
    address = {New York, NY, USA},
    volume = {41},
    number = {6},
    issn = {0730-0301},
    url = {https://doi.org/10.1145/3550454.3555463},
    doi = {10.1145/3550454.3555463},
    journal = {ACM Trans. Graph.},
    month = {nov},
    articleno = {232},
    numpages = {19},
    keywords = {stream architecture, rendering framework, cross-platform renderer}
}

The publisher version of the paper is open-access. You may download it for free.

luisacompute's People

Contributors

111116 avatar coloredblack avatar comradez avatar dependabot[bot] avatar faithzl avatar frvdecqaq avatar gaoxinge avatar hercier avatar implode-nz avatar lastmc avatar leonkang130 avatar maxwellgeng avatar maxwellgengyf avatar mike-leo-smith avatar mugdxy avatar needsmoar avatar oldnew777 avatar saeruhikari avatar sailing-innocent avatar shiinamiyuki avatar shiinarinne avatar swfly avatar wrvsrx avatar zengyf131 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

luisacompute's Issues

Some meshes disappear after accel compaction

Describe the bug
Some meshes disappear after the top-level acceleration structure compaction.

To Reproduce
Steps to reproduce the behavior:
Enable accel compaction and render the Staircase scene.

Expected behavior
All meshes rendered.

Screenshots
None.

Desktop (please complete the following information):

  • OS: macOS

Additional context
Temporally disabling the compaction. May result in some increasing in VRAM usage. Will retry compaction some days later.

LLVM backend: linking errors

I am having problems with LLVM backend.

I am using LLVM 15.0.5 on Linux and I get the following runtime error:

Failed to load dynamic module '/tmp/LuisaCompute/build/bin/libluisa-compute-backend-llvm.so', reason: /tmp/LuisaCompute/build/bin/libluisa-compute-backend-llvm.so: undefined symbol: _ZN4absl12lts_2022062318container_internal11kEmptyGroupE. [/tmp/LuisaCompute/src/core/platform.cpp:165]

Any ideas where the missing abseil symbol went?

inspect 在交互模式(REPL)得不到源码

>>> import inspect
>>> inspect.getsourcelines(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/inspect.py", line 1006, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/inspect.py", line 835, in findsource
    raise OSError('could not get source code')
OSError: could not get source code

callable struct method?

def f(self, a:int):
    self.k += a
    return self.k

strt = luisa.StructType(k=int, f=f)

@luisa.kernel
f(s: strt):
    s.f(4)

Refactor `Accel` and `Mesh` interfaces? Honor `allow_update`

Planned modifications:

uint64_t Device::Interface::create_accel(AccelBuildQuality quality, bool allow_update) noexcept;
uint64_t Device::Interface::create_mesh(
    uint64_t v_buffer, size_t v_offset, size_t v_stride, size_t v_count,
    uint64_t t_buffer, size_t t_offset, size_t t_count,
    AccelBuildQuality quality, bool allow_update) noexcept;

where

enum struct AccelBuildQuality {
    HIGH,    // high-quality build, fast trace, typically with compaction
    DEFAULT, // backend decided, balance between build time and trace performance
    LOW      // fast build, possibly lower trace performance, no compaction
};

Unclear compile error information

when to_lctype is called on unsupported (non-data) types. e.g:

xx1 = dispatch_id.xy

error:

(kernel)f:5:10: Error: Exception: to_lctype(<class 'luisa.types.BuiltinFuncType'>): unrecognized type
    xx1 = dispatch_id.xy
         ~~~~~~~~~~~~~~~

crashes jupyter

Input:

import luisa
@luisa.kernel
def fill(x: int):
    b.write(dispatch_id().x, x)

Report:

Process:               Python [11639]
Path:                  /usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/Resources/Python.app/Contents/MacOS/Python
Identifier:            Python
Version:               3.9.10 (3.9.10)
Code Type:             X86-64 (Native)
Parent Process:        Python [11577]
Responsible:           Terminal [684]
User ID:               501

Date/Time:             2022-04-20 14:40:32.793 +0800
OS Version:            Mac OS X 10.15.7 (19H2)
Report Version:        12
Bridge OS Version:     5.4 (18P4663)
Anonymous UUID:        4A973336-E1A5-5C2F-38CB-EF3E8B8A3302

Sleep/Wake UUID:       CBE6D37B-50D4-4C27-ABF1-00A08BA1B74F

Time Awake Since Boot: 25000 seconds
Time Since Wake:       2700 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_CRASH (SIGABRT)
Exception Codes:       0x0000000000000000, 0x0000000000000000
Exception Note:        EXC_CORPSE_NOTIFY

Application Specific Information:
terminating with uncaught exception of type pybind11::error_already_set: Exception: error when building AST
 
At:
  /Users/bilibili/code/LuisaCompute/build_debug/bin/luisa/astbuilder.py(26): __call__
  /Users/bilibili/code/LuisaCompute/build_debug/bin/luisa/__init__.py(87): astgen
  /Users/bilibili/code/LuisaCompute/build_debug/bin/luisa/__init__.py(92): __init__
  /var/folders/9m/jl3vmk4d4cg5k2wjnfc7kzwm0000gn/T/ipykernel_11639/2580251621.py(2): <module>
  /usr/local/lib/python3.9/site-packages/IPython/core/interactiveshell.py(3457): run_code
  /usr/local/lib/python3.9/site-packages/IPython/core/interactiveshell.py(3377): run_ast_nodes
  /usr/local/lib/python3.9/site-packages/IPython/core/interactiveshell.py(3185): run_cell_async
  /usr/local/lib/python3.9/site-packages/IPython/core/async_helpers.py(78): _pseudo_sync_runner
  /usr/local/lib/python3.9/site-packages/IPython/core/interactiveshell.py(2960): _run_cell
  /usr/local/lib/python3.9/site-packages/IPython/core/interactiveshell.py(2914): run_cell
  /usr/local/lib/python3.9/site-packages/ipykernel/zmqshell.py(533): run_cell
  /usr/local/lib/python3.9/site-packages/ipykernel/ipkernel.py(353): do_execute
  /usr/local/lib/python3.9/site-packages/ipykernel/kernelbase.py(648): execute_request
  /usr/local/lib/python3.9/site-packages/ipykernel/kernelbase.py(353): dispatch_shell
  /usr/local/lib/python3.9/site-packages/ipykernel/kernelbase.py(446): process_one
  /usr/local/lib/python3.9/site-packages/ipykernel/kernelbase.py(457): dispatch_queue
  /usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py(80): _run
  /usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py(1890): _run_once
  /usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py(596): run_forever
  /usr/local/lib/python3.9/site-packages/tornado/platform/asyncio.py(199): start
  /usr/local/lib/python3.9/site-packages/ipykernel/kernelapp.py(677): start
  /usr/local/lib/python3.9/site-packages/traitlets/config/application.py(846): launch_instance
  /usr/local/lib/python3.9/site-packages/ipykernel_launcher.py(16): <module>
  /usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py(87): _run_code
  /usr/local/Cellar/[email protected]/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/runpy.py(197): _run_module_as_main
 
abort() called

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib        	0x00007fff681cf33a __pthread_kill + 10
1   libsystem_pthread.dylib       	0x00007fff6828be60 pthread_kill + 430
2   libsystem_c.dylib             	0x00007fff68156808 abort + 120
3   libc++abi.dylib               	0x00007fff653b5458 abort_message + 231
4   libc++abi.dylib               	0x00007fff653a68a7 demangling_terminate_handler() + 238
5   libobjc.A.dylib               	0x00007fff66ee15b1 _objc_terminate() + 104
6   libc++abi.dylib               	0x00007fff653b4887 std::__terminate(void (*)()) + 8
7   libc++abi.dylib               	0x00007fff653b4829 std::terminate() + 41
8   lcapi.cpython-39-darwin.so    	0x0000000110cb5f48 auto luisa::compute::detail::FunctionBuilder::_define<std::__1::function<void ()> const&>(luisa::compute::Function::Tag, std::__1::function<void ()> const&) + 120 (function_builder.h:230)
9   lcapi.cpython-39-darwin.so    	0x0000000110c88962 auto luisa::compute::detail::FunctionBuilder::define_kernel<std::__1::function<void ()> const&>(std::__1::function<void ()> const&) + 50 (function_builder.h:290)
10  lcapi.cpython-39-darwin.so    	0x0000000110cb5d31 eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> pybind11::detail::argument_loader<std::__1::function<void ()> const&>::call_impl<eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const>, eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&), 0ul, pybind11::detail::void_type>(eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&), std::__1::integer_sequence<unsigned long, 0ul>, pybind11::detail::void_type&&) && + 97 (cast.h:1207)
11  lcapi.cpython-39-darwin.so    	0x0000000110cb1059 std::__1::enable_if<!(std::is_void<eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> >::value), eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> >::type pybind11::detail::argument_loader<std::__1::function<void ()> const&>::call<eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const>, pybind11::detail::void_type, eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&)>(eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&)) && + 73 (cast.h:1179)
12  lcapi.cpython-39-darwin.so    	0x0000000110cb0e4f void pybind11::cpp_function::initialize<eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&), eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const>, std::__1::function<void ()> const&, pybind11::name, pybind11::is_method, pybind11::sibling>(eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&), eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*)(std::__1::function<void ()> const&), pybind11::name const&, pybind11::is_method const&, pybind11::sibling const&)::'lambda'(pybind11::detail::function_call&)::operator()(pybind11::detail::function_call&) const + 239 (pybind11.h:233)
13  lcapi.cpython-39-darwin.so    	0x0000000110cb0d45 void pybind11::cpp_function::initialize<eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&), eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const>, std::__1::function<void ()> const&, pybind11::name, pybind11::is_method, pybind11::sibling>(eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*&)(std::__1::function<void ()> const&), eastl::shared_ptr<luisa::compute::detail::FunctionBuilder const> (*)(std::__1::function<void ()> const&), pybind11::name const&, pybind11::is_method const&, pybind11::sibling const&)::'lambda'(pybind11::detail::function_call&)::__invoke(pybind11::detail::function_call&) + 21 (pybind11.h:210)
14  lcapi.cpython-39-darwin.so    	0x0000000110c6e41d pybind11::cpp_function::dispatcher(_object*, _object*, _object*) + 4941 (pybind11.h:835)
...

report11639.txt

Command reordering gives wrong results in LuisaRender

Describe the bug
After reordering, submitting the should-be-independent commands to a single CUDA stream in the REVERSED order triggers illegal memory access on the device.

To Reproduce
As aforementioned; when rendering the Glass-of-Water scene.

Expected behavior
The correct rendering.

Screenshots
N/A

Desktop (please complete the following information):

  • OS: Manjaro 21.5
  • CUDA backend
  • RTX-2080Ti

Additional context
TODO: construct a minimal reproducible example...

chained comparison with side effects

consider a<f()<c where f has side effects. The expression will be interpreted as a<f() and f()<c, causing f to be potentially executed twice.

Cannot build due to EASTL issue

Hi folks, I'm building with clang++15, ubuntu 20.04.

I encounter a compilation error that is related with EASTL

Err log:

In file included from /home/dev/LuisaCompute/src/ext/EASTL/include/EASTL/algorithm.h:243:
/home/dev/LuisaCompute/src/ext/EASTL/include/EASTL/internal/copy_help.h:135:90: error: no member named 'contiguous_iterator_tag' in namespace 'std'
                                                                  (eastl::is_pointer<InputIterator>::value  || eastl::is_same<IIC, EASTL_ITC_NS::contiguous_iterator_tag>::value) &&
                                                                                                                                   ~~~~~~~~~~~~~~^
/home/dev/LuisaCompute/src/ext/EASTL/include/EASTL/internal/copy_help.h:136:90: error: no member named 'contiguous_iterator_tag' in namespace 'std'
                                                                  (eastl::is_pointer<OutputIterator>::value || eastl::is_same<OIC, EASTL_ITC_NS::contiguous_iterator_tag>::value);
                                                                                                                                   ~~~~~~~~~~~~~~^
/home/dev/LuisaCompute/src/ext/EASTL/include/EASTL/internal/copy_help.h:138:51: error: non-type template argument is not a constant expression
                return eastl::move_and_copy_helper<IIC, isMove, canBeMemmoved>::move_or_copy(first, last, result); // Need to chose based on the input iterator tag and not the output iterator tag, because containers accept input ranges of iterator types different than self.
                                                                ^~~~~~~~~~~~~

This seems the same error with electronicarts/EASTL#482

EASTL commit hash b6f329dc9c09ffaf68a979c6591e66a12cf6c2b9

Do you have any suggestions about this?

Cannot import luisa (Python) after build and setup

Describe the bug
After following the build guide for Python, I cannot import luisa or run test files.

in build_release/bin I see lcapi.cpython-310-darwin.so but no .so to import luisa. I'm assuming this is a PyBind11 thing that the lcapi .so will allow importing luisa but it doesn't see to work:

import lcapi
dir(lcapi)
['Accel', 'AccelBuildCommand', 'AccelBuildRequest', 'AccelModification', 'AccelUsageHint', 'AccessExpr', 'BinaryExpr', 'BinaryOp', 'BindlessArrayUpdateCommand', 'BufferCopyCommand', 'BufferDownloadCommand', 'BufferToTextureCopyCommand', 'BufferUploadCommand', 'CallExpr', 'CallOp', 'CastExpr', 'CastOp', 'Command', 'Context', 'Device', 'DeviceInterface', 'Expression', 'ForStmt', 'FsPath', 'Function', 'FunctionBuilder', 'IfStmt', 'LiteralExpr', 'LoopStmt', 'MemberExpr', 'MeshBuildCommand', 'PixelFormat', 'PixelStorage', 'RefExpr', 'Sampler', 'ScopeStmt', 'ShaderDispatchCommand', 'Stream', 'TextureCopyCommand', 'TextureDownloadCommand', 'TextureToBufferCopyCommand', 'TextureUploadCommand', 'Type', 'UnaryExpr', 'UnaryOp', 'doc', 'file', 'loader', 'name', 'package', 'spec', '_vectorstorage_bool2', '_vectorstorage_bool3', '_vectorstorage_bool4', '_vectorstorage_float2', '_vectorstorage_float3', '_vectorstorage_float4', '_vectorstorage_int2', '_vectorstorage_int3', '_vectorstorage_int4', '_vectorstorage_uint2', '_vectorstorage_uint3', '_vectorstorage_uint4', 'abs', 'acos', 'asin', 'atan', 'atan2', 'bool2', 'bool3', 'bool4', 'builder', 'ceil', 'clamp', 'cos', 'cross', 'degrees', 'determinant', 'distance', 'dot', 'exp', 'float2', 'float2x2', 'float3', 'float3x3', 'float4', 'float4x4', 'floor', 'int2', 'int3', 'int4', 'inverse', 'length', 'lerp', 'log', 'log10', 'log2', 'log_level_error', 'log_level_info', 'log_level_verbose', 'log_level_warning', 'make_bool2', 'make_bool3', 'make_bool4', 'make_float2', 'make_float2x2', 'make_float3', 'make_float3x3', 'make_float4', 'make_float4x4', 'make_int2', 'make_int3', 'make_int4', 'make_uint2', 'make_uint3', 'make_uint4', 'max', 'min', 'normalize', 'pixel_storage_channel_count', 'pixel_storage_size', 'pixel_storage_to_format_float', 'pixel_storage_to_format_int', 'pow', 'radians', 'rotation', 'round', 'scaling', 'select', 'sin', 'sqrt', 'tan', 'to_bytes', 'translation', 'transpose', 'uint2', 'uint3', 'uint4']
import luisa
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'luisa'

To Reproduce
Steps to reproduce the behavior:

following https://github.com/LuisaGroup/LuisaCompute/blob/master/README_Python_en.md

  1. cmake -S . -B build_release -D CMAKE_BUILD_TYPE=Release -D CMAKE_C_COMPILER=clang -D CMAKE_CXX_COMPILER=clang++ -D LUISA_COMPUTE_ENABLE_PYTHON=ON (note I removed -G Ninja in instructions and used default generator)
  2. cmake --build build_release -j
  3. source set_python_path.sh build_release
  4. (note no test.py copied to build_release/bin directory as instructions imply)
  5. echo $PYTHONPATH
    /Users/bsavery/Code/LuisaCompute/build_release/bin:/Users/bsavery/Code/LuisaCompute/pyscenes:
  6. run python3 src/py/tests/test_path_tracing.py

Traceback (most recent call last):
File "/Users/bsavery/Code/LuisaCompute/src/py/tests/test_path_tracing.py", line 6, in
import luisa
ModuleNotFoundError: No module named 'luisa'

Desktop (please complete the following information):

  • OS: Macos 13
  • Version Python 3.10

Feature: array, struct & buffer

需求

arr = luisa.ArrayType(5, int)
sph = luisa.StructType(center=float3, radius=float)
geo = luisa.StructType(offset=float3, geometry=sph)

buf = luisa.Buffer(100000, dtype=geo)
buf.copy_from(...)
buf.copy_to(...)

@luisa.kernel
def f(a: arr, b: sph):
	a1 = arr()
	a2 = arr((1,2,3,4,5))
	a3 = arr([1,2,3,4,5])
	b1 = sph()
	b2 = sph(make_float3(1,2,3), 4)
	b3 = sph(center=make_float3(1,2,3), radius=4)
	# Note: 4 should be implicitly converted to float
	b0 = buf.read(dispatch_id().x)
	b0.geometry.radius += 1
	buf.write(dispatch_id().x, b0)

a = arr(...)
b = sph(...)
g = geo(...)
f(a,b, dispatch_size=...)

待定:Buffer上传下载对应的host数据类型

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.