关于kernel的参数写法

taichi语言要求kernel必须要给所有参数提供type hint,是不是说只能用taichi的type system中已有的整型和浮点型作为参数?比如说能不能把一个Gui event作为参数传给kernel呢?
如果说不能的话,是否意味着这些处理就应该去交给Python scope的函数去处理?

You can pass special Python-scope object to kernels using ti.template() as type-hint:

import taichi as ti

def func(gui: ti.template()):
  print(gui.get_cursor_pos()[0])

gui = ti.GUI('Window')
while gui.running:
    func(gui)
    gui.show()
1 个赞

正如楼上说的那样,ti.template() 理论上可以接受任何参数。

PS: 楼上的代码有点小瑕疵:func 需要@ti.kernel,在Taichi scope里面调用·print(gui.get_cursor_pos()[0])的行为也可能和想象的不一样:gui.get_cursor_pos()[0]`会在编译期被求值。

2 个赞

Right, Taichi kernel should be computation-bounded (ji suan luo ji), not IO-bounded (ye wu luo ji).
Always keep in mind that codes in Taichi-scope should be able to execute on GPU, therefore we should process the complex stuff on CPU with Python interpreter, and make GPU programs as focus as possible at the first place:

def func(mx: ti.f32, my: ti.f32):
  print(mx, my)

gui = ti.GUI('Window')
while gui.running:
  mx, my = gui.get_cursor_pos()
  func(gui)
  gui.show()

If you learn OpenGL, then Python-scope = C/C++, Taichi-scope = GLSL.

1 个赞

多谢两位的解释!
的确听课以后有一个疑惑就是应该怎么合理地去施加@kernel和@func。从最佳实践来说,一个处理Gui event的函数是不是推荐写成kernel呢?
上面讲到计算逻辑和业务逻辑的代码有些没看懂,求稍微详细解释。是不是说处理大规模的矩阵数据的函数尽量去用kernel,而其他的则不一定需要?

For example, try-except is 业务逻辑, x += 1 is 计算逻辑.

You are right, 业务逻辑 should always be put in Python-scope, since Taichi-scope is not good at deal with it. @kernel and @func are prepared for computation tasks.