Skip to content

Commit

Permalink
Add bounds checks for fold and reduce axis inline operations (#608)
Browse files Browse the repository at this point in the history
Also fixes a small typo in ast_utils.nim.
  • Loading branch information
AngelEzquerra committed Dec 30, 2023
1 parent 9016729 commit f809e7f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/arraymancer/private/ast_utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ proc replaceSymsByIdents*(ast: NimNode): NimNode =
return node
of nnkLiterals:
return node
of nnkHiddenStdConv: # see `test_fancy_indexing,nim` why needed
of nnkHiddenStdConv: # see `test_fancy_indexing.nim` why needed
expectKind(node[1], nnkSym)
return ident($node[1])
else:
Expand Down
9 changes: 9 additions & 0 deletions src/arraymancer/tensor/higher_order_foldreduce.nim
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ template fold_inline*[T](arg: Tensor[T], op_initial, op_middle, op_final: untype
template reduce_axis_inline*[T](arg: Tensor[T], reduction_axis: int, op: untyped): untyped =
let z = arg # ensure that if t is the result of a function it is not called multiple times
var reduced: type(z)
when compileOption("boundChecks"):
if arg.rank <= reduction_axis:
raise newException(IndexDefect, "Input tensor rank (" & $arg.rank &
") must be greater than reduction axis (" & $reduction_axis &
") when executing reduce_axis_inline: " & astToStr(op))
let weight = z.size div z.shape[reduction_axis]
omp_parallel_reduce_blocks(reduced, block_offset, block_size, z.shape[reduction_axis], weight, op) do:
x = z.atAxisIndex(reduction_axis, block_offset).clone()
Expand All @@ -55,6 +60,10 @@ template reduce_axis_inline*[T](arg: Tensor[T], reduction_axis: int, op: untyped
template fold_axis_inline*[T](arg: Tensor[T], accumType: typedesc, fold_axis: int, op_initial, op_middle, op_final: untyped): untyped =
let z = arg # ensure that if t is the result of a function it is not called multiple times
var reduced: accumType
when compileOption("boundChecks"):
if arg.rank <= fold_axis:
raise newException(IndexDefect, "Input tensor rank (" & $arg.rank &
") must be greater than fold axis (" & $fold_axis & ") when executing fold_axis_inline")
let weight = z.size div z.shape[fold_axis]
omp_parallel_reduce_blocks(reduced, block_offset, block_size, z.shape[fold_axis], weight, op_final) do:
let y {.inject.} = z.atAxisIndex(fold_axis, block_offset).clone()
Expand Down

0 comments on commit f809e7f

Please sign in to comment.