|
| 1 | +import functools |
| 2 | + |
| 3 | +import ninetoothed |
| 4 | +import ninetoothed.language as ntl |
| 5 | +from ninetoothed import Tensor |
| 6 | + |
| 7 | +BLOCK_SIZE = ninetoothed.block_size() |
| 8 | + |
| 9 | + |
| 10 | +def arrangement(input, output, dim): |
| 11 | + assert input.ndim == output.ndim |
| 12 | + |
| 13 | + def create_axis_tile_shape(dim, dim_block): |
| 14 | + return ( |
| 15 | + tuple(1 for _ in range(dim)) |
| 16 | + + (dim_block,) |
| 17 | + + tuple(1 for _ in range(input.ndim - dim - 1)) |
| 18 | + ) |
| 19 | + |
| 20 | + def arrange(input): |
| 21 | + input_arranged = input.tile(inner_block_shape).tile(outer_block_shape) |
| 22 | + |
| 23 | + input_arranged.dtype = input_arranged.dtype.squeeze( |
| 24 | + tuple(d for d in range(input.ndim) if d != dim) |
| 25 | + ) |
| 26 | + input_arranged.dtype.dtype = input_arranged.dtype.dtype.squeeze( |
| 27 | + tuple(d for d in range(input.ndim) if d != dim) |
| 28 | + ) |
| 29 | + return input_arranged |
| 30 | + |
| 31 | + inner_block_shape = create_axis_tile_shape(dim, BLOCK_SIZE) |
| 32 | + outer_block_shape = create_axis_tile_shape(dim, -1) |
| 33 | + |
| 34 | + return arrange(input), arrange(output) |
| 35 | + |
| 36 | + |
| 37 | +def _exp(x, dtype): |
| 38 | + exp_dtype = dtype if dtype != ntl.float16 else ntl.float32 |
| 39 | + return ntl.cast(ntl.exp(ntl.cast(x, exp_dtype)), dtype) |
| 40 | + |
| 41 | + |
| 42 | +def application(input, output): |
| 43 | + dtype = output.dtype.dtype |
| 44 | + prev_max = ntl.cast(float("-inf"), dtype) |
| 45 | + denominator = ntl.cast(0, dtype) |
| 46 | + |
| 47 | + for i in range(input.shape[0]): |
| 48 | + input_i = ntl.cast(input[i], dtype) |
| 49 | + curr_max = ntl.cast(ntl.maximum(prev_max, ntl.max(input_i)), dtype) |
| 50 | + input_max_diff_exp = _exp(input_i - curr_max, dtype) |
| 51 | + prev_curr_max_diff_exp = _exp(prev_max - curr_max, dtype) |
| 52 | + denominator = denominator * prev_curr_max_diff_exp + ntl.sum(input_max_diff_exp) |
| 53 | + prev_max = curr_max |
| 54 | + |
| 55 | + for i in range(input.shape[0]): |
| 56 | + numerator = _exp(input[i] - prev_max, dtype) |
| 57 | + output[i] = numerator / denominator |
| 58 | + |
| 59 | + |
| 60 | +@functools.cache |
| 61 | +def make(ndim, dim): |
| 62 | + return ninetoothed.make( |
| 63 | + functools.partial(arrangement, dim=dim), |
| 64 | + application, |
| 65 | + ( |
| 66 | + Tensor(ndim, other=float("-inf"), shape_options={"constexpr": True}), |
| 67 | + Tensor(ndim), |
| 68 | + ), |
| 69 | + ) |
0 commit comments