GAMES 201 Lecture 1 Taichi Programing language
Lecture 1
目录->GAMES201学习笔记
Phase of a taichi program
- Initialization: ti.init((debug=True),arch=ti....)
- Tensor allocation:
i) ti.var(现为 ti.field)
ii) ti.Vector - Computation (launch kernels, access tensors in Python-scope)
- Optional: restart the Taichi system
(i.e. clear memory, destory all variables and kernels):ti.reset()
- Note: For now, after the first kernel launch or tensor access in Python-scope, no more tensor allocation is allowed.
Data in Taichi programing language
Taichi is a data-oriented programing language where tensors are first-class citzens
-
Tensor
- Tensors are essentially multi-dimensional arrays.
- An element of a tensor can be either a scalar, a vector (ti.Vector) or a matrix (ti.Matrix)
- Tensor elements are always accessed via the a[i, j, k] synatx (No pointer!)
- Tensors can be spatially sparse
ex: a=ti.field (dt=ti.f32, shape=(42,63))
注:太极中的矩阵规模一般在2x2~3x3左右,更大规模的矩阵需要用tensor实现
Kernels
- Kernels must be decorated with @ti.kernel, kernel arguments and return values must be type-hinted.
ex:
@ti.kernel
def calc() -> ti.i32
... ...
return
- Taichi function can be called by Taichi kernels and other Taichi functions.->(But function can not call kernels)
Functions
- Functions must be decorated with @ti.func
ex:
@ti.func
def triple(x):
return x*3
@ti.kernel
def triple_array:
for i in range(128):
a[i]=triple(a[i])
- Note:Taichi functions will be force-inlined, recursion is not allowed.contain at most one return statement.
- Most python math operators are supported in taichi.
- Taichi supports chain comparisions, e.g. a<b<=c!=d
Matrices and linear algebra
- ti.Matrix is for small matrices only.
- NOTE:Differentiate element-wise product-> "*"
Matrix product->"@"
ex:A.transpose()->转置
A.inverse()->逆
A.trace()->迹
A.determinant(type)->行列式
A.normalized
A.cast(type)->类型转换
ti.sin(A)/cos(A)->element-wise的类型转换
- NOTE:Differentiate element-wise product-> "*"
For Loops in Taichi
Range-for loops
- no different from Python->for i in range(...): ...
- it will be paralleled when used at the outermost scope
- can be nested
Struct-for loops (稀疏数据结构常用)
- Iterates over(sparse)tensor elements
Taichi Kernel -> for loops 最外层自动并行化
Note: It is the loop at "the outermost scope" that gets parallized, not the outermost loop.
Atomic operations
- In taichi, augmented assignments (e.g. x[i]+=1) -> automatically atomic.
ex: total[None] += x[i] -> atomic
ti.atomic_add(total[None],x[i]) ->atomic
toatal[None] = total[None] + x[i] ->not atomic
Scope
Taichi-Scope
- ->Everything decorated with ti.kernel,ti.func.
- Code in Taichi-Scope will be compiled by the Taichi compiler and run on parallel devices.
Python-Scope
->Code outside the Taichi-Scope
- Code in Python-Scope is simply Python code and will executed by the Python interpreter.
补充:使用 yapf ( +PEP8 )实现代码的格式化 - ※:随着太极版本更新,更多更详细的内容请参照太极的文档->Taichi 文档
finished.