taichi-dev / taichi

Productive, portable, and performant GPU programming in Python.
https://taichi-lang.org
Apache License 2.0
25.04k stars 2.26k forks source link

Inheritance of taichi data-oriented #5788

Open Jingzheng-Li opened 1 year ago

Jingzheng-Li commented 1 year ago

Dear Taichi staff, I want to use data_oriented to complete an inheritance class, define the field in the first class, and modify the field in the second class (such as the following simplified program), but if I use the such "root place" way to write it, there will be an error that some fileds are not placed:

import taichi as ti

ti.init(arch=ti.gpu, dynamic_index=True)

@ti.data_oriented
class MyClass1():

    def __init__(self):
        self.testfield = ti.Vector.field(3, dtype=ti.f32)

    @ti.kernel
    def init_field(self):
        ti.root.dense(ti.i, 10).place(self.testfield)

@ti.data_oriented
class MyClass2(MyClass1):

    def __init__(self):
        super().__init__()

    @ti.kernel
    def edit_field(self):
        self.testfield[1] = ti.Vector([2,2,2])

myclass2 = MyClass2()

myclass2.init_field()
myclass2.edit_field()
print(myclass2.testfield)

However, if I define field with a specified field, the code will be normal

import taichi as ti

ti.init(arch=ti.gpu, dynamic_index=True)

@ti.data_oriented
class MyClass1():

    def __init__(self):
        self.testfield = ti.Vector.field(3, dtype=ti.f32, shape=10)

@ti.data_oriented
class MyClass2(MyClass1):

    def __init__(self):
        super().__init__()

    @ti.kernel
    def edit_field(self):
        self.testfield[1] = ti.Vector([2,2,2])

myclass2 = MyClass2()
myclass2.edit_field()
print(myclass2.testfield)

Therefore, my question is that how can I modify the first code to get correct answer?

PENGUINLIONG commented 1 year ago

I think the key problem is that you placed the field in a kernel.

    @ti.kernel
    def init_field(self):
        ti.root.dense(ti.i, 10).place(self.testfield)

Please checkout the raster example for the normal usage :) https://github.com/taichi-dev/taichi/blob/master/python/taichi/examples/rendering/rasterizer.py#L24-L43