Lecture02

Metaprogramming

产生最终实际运行程序的程序/编程方式

Metaprogramming in Taichi:

  • Unify the development of dimensionality-dependent code, such as 2D/3D physical simulations

  • Improve run-time performance by taking run-time costs to compile time

维度无关代码

Template

ti.template()

  • The Taichi kernels and functions with ti.template() arguments are template functions

  • Template functions are instantiated when needed. (Depends on the arguments.)

Allows you to pass "anything" supported by Taichi

  • Pass-by-reference, use with cautions

    • Computations in the Taichi scope can NOT modify Python scope data

    • Computations in the Taichi scope can modify Taichi fields

    • Computations in the Taichi scope can modify Taichi scope data 未使用模板时,由于是 pass-by-value 不会改变传入参数的值

  • Taichi kernels are instantiated whenever seeing a new parameter (even same typed) 根据变量的地址决定,如果为一个变量重新赋值,或者使用其他相同类型的变量,由于地址不同,Taichi 均会重新实例化模板函数

Dimension independent programming

ti.grouped()

Metadata

  • Field

    • field.dtype: type of a field

    • field.shape: shape of a field

  • Matrix / Vector

    • matrix.n: rows of a mat

    • matrix.m: cols of a mat / vec

运行时性能

static

ti.static()

  • Compile-time branching

  • Forced loop unrolling for performance

  • Forced loop unrolling for element index access

    • Indices into compound Taichi types must be a compile-time constant

Object-oriented programming

Python OOP + Taichi DOP = ODOP

Objective data-oriented programming (ODOP)

@ti.data_oriented

Compared with Python, the Taichi classes are more data_oriented:

Python class:

Taichi class:

Taichi 更多使用面向数据的方法,因为使用数组计算效率更高

  • PDOP: Use Python scope variables in Taichi scope with caution

  • ODOP: Use Python scope members in Taichi scope with caution

Last updated