ztcl::tensor attention
Gives the attention of one query row of each head over a key-value cache.
ztcl::tensor attention Q K V SCALE
Description
Q is H by hs: one query row for each of H heads. K and V are n by Hk by hs: the keys and the values of n positions for Hk heads, and H is a multiple of Hk. Head h reads the cache head h / (H / Hk), as in grouped-query attention. The result is H by hs.
The steps have the bits of the separate commands: the score of head h and position t is sum over hs of the products of Q and K (each product in the dtype, the sum in f64, as sum adds), times SCALE in the dtype. Then softmax runs over the positions of each head. The output of head h is the sum over the positions of each weight times V, in f64 from the first position. So one command replaces mul, sum, transpose, softmax, and the broadcast of the heads, with no temporary tensors of n by H by hs. The cost is 4 * H * n * hs cheap operations and 2 * H * n math operations.
Returns
A tensor of H by hs.
Examples
Each example of this page runs after package require ztcl::tensor.
% ztcl::tensor attention [ztcl::tensor of {{1 0}}] [ztcl::tensor of {{{1 0}} {{0 1}}}] [ztcl::tensor of {{{2 2}} {{4 0}}}] 1
tensor f32 {1 2} {2.5378828 1.4621172}
Errors
% ztcl::tensor attention [ztcl::tensor zeros {2 3}] [ztcl::tensor zeros {0 1 3}] [ztcl::tensor zeros {0 1 3}] 1
tensor attention: the cache is empty
-errorcode ZTCL TENSOR
Facts
- Capability
- None.
- Tcl release
- Tcl 9.1 and 8.6.
- Since
- ztcl 1.0.0-beta.4
- Compute cost
- A cost for each element operation by its kind (a copy, an add, a division, a math function, a multiply-add of a matmul), set so that one compute unit takes about the time of one unit of plain Tcl. docs/modules/tensor.md has the table.