IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /max/get-started.md). For the complete documentation index, see llms.txt.
Skip to main content
For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /max/get-started.md).

Mojo function

foreach

def foreach[dtype: DType, rank: Int, //, func: def[width: Int](Coord[_]) capturing -> SIMD[dtype, width], *, target: StringSlice[StaticConstantOrigin] = StringSlice("cpu"), simd_width: Int = get_kernel_simd_width[dtype, target](), _trace_name: StringSlice[StaticConstantOrigin] = StringSlice("mogg.for_each")](tensor: ManagedTensorSlice[static_spec=tensor.static_spec], ctx: DeviceContext)

Apply the function func to each element of the tensor slice.

The func body receives the element index as a Coord. Use coord_to_index_list to convert it to an IndexList if integer index arithmetic is needed.

Parameters:

  • ​dtype (DType): The data type of the elements in the tensor slice.
  • ​rank (Int): The rank of the tensor slice.
  • ​func (def[width: Int](Coord[_]) capturing -> SIMD[dtype, width]): The function to apply to each element of the tensor slice.
  • ​target (StringSlice[StaticConstantOrigin]): Indicates the type of the target device (e.g. "cpu", "gpu").
  • ​simd_width (Int): The SIMD width for the target (usually leave this as its default value).
  • ​_trace_name (StringSlice[StaticConstantOrigin]): Name of the executed operation displayed in the trace_description.

Args: