Skip to content

Commit

Permalink
Extend important types and functions
Browse files Browse the repository at this point in the history
  • Loading branch information
charleskawczynski committed Jan 28, 2025
1 parent 34be0f5 commit 5deabc7
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions docs/src/broadcast_background.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,51 @@ If you want to avoid adding dots for selected function calls in expr, splice
those function calls in with `$`. For example, `@. sqrt(abs($sort(x)))` is
equivalent to `sqrt.(abs.(sort(x)))` (no dot for sort).

## Important `Base.Broadcast` types and functions

There are some important types and functions that are helpful for understanding
Julia's broadcasting.

- `Base.Broadcast.Broadcasted` (or just `Broadcasted`)
- `Base.Broadcast.broadcasted` (or just `broadcasted`, please note the difference in capitalization)
- `Base.Broadcast.instantiate` (or just `instantiate`)
- `Base.Broadcast.materialize` (or just `materialize`)
- `Base.Broadcast.materialize!` (or just `materialize!`)
- `Base.Broadcast.copyto` (or just `copyto`)
- `Base.Broadcast.copyto!` (or just `copyto!`)

For brevity, we'll use a suffix `(!)` to denote the functional or in-place
methods.

The default type in Julia Base's broadcast software layer is `Broadcasted`. This
is a "lazy" object that contains

- `style`, used for [traits](https://en.wikipedia.org/wiki/Trait_(computer_programming)), or dispatch
- `f`, the function to be broadcasted
- `args`, the arguments to the function `f`
- `axes`, the "shape" or "size" of the broadcasted object, when materialized

When broadcast expressions are _lowered_ (a step in the Julia compilation
procedure), they are lowered to `broadcasted` calls, which are then passed to
`materialize(!)`. For example:

```@example
a = [1]
Base.Meta.@lower @. a+=1
```

!!! note

The result of `Base.Meta.@lower` is an intermediate representation (IR) of
the given expression.

The responsibility of `broadcasted`, here, is to return `Broadcasted` objects.
This function allows users to overload `broadcasted` to return special types of
`Broadcasted` objects.


Finally, `materialize(!)` does two things:

- Calls `instantiate`, which reconstructs a new `Broadcasted`
object with the `axes` populated (by default it's populated with `nothing`).
- Calls `copyto(!)`, which executes the broadcasted expression per element.

0 comments on commit 5deabc7

Please sign in to comment.