started the burn developer book (#1184)

---------

Co-authored-by: Sylvain Benner <sylvain@benner.online>
Co-authored-by: Dilshod Tadjibaev <939125+antimora@users.noreply.github.com>
This commit is contained in:
Joshua Ferguson 2024-02-05 10:03:24 -06:00 committed by GitHub
parent bfebf22e1a
commit 3eab141608
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 855 additions and 1 deletions

18
contributor-book/.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
target
# MacOS temp file
.DS_Store
book-test
guide/book
.vscode
tests/burn-book/book/
book/
# Ignore Jetbrains specific files.
.idea/
# Ignore Vim temporary and swap files.
*.sw?
*~

View File

@ -0,0 +1,4 @@
{
"printWidth": 100,
"proseWrap": "always"
}

View File

@ -0,0 +1 @@
../LICENSE-APACHE

View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -0,0 +1,17 @@
[book]
authors = [
"Wouter Doppenberg",
"Nathaniel Simard",
"Louis Fortier-Dubois",
"Dilshod Tadjibaev",
"Guillaume Lagrange",
"Joshua Ferguson",
"The Burn Community",
]
language = "en"
multilingual = false
src = "src"
title = "The Burn Contributor Book 🔥"
[output.html]
mathjax-support = true

View File

@ -0,0 +1,16 @@
- [Overview](./overview.md)
- [How to Read This Book](./how-to-read-this-book.md)
- [Getting Started](./getting-started/ReadMe.md)
- [Setting Up The Environment](./getting-started/setting-up-the-environment.md)
- [Configuring Your Editor(Optional)](./getting-started/configuring-your-editor.md)
- [testing](./getting-started/testing.md)
- [Architecture Overview](./project-architecture/ReadMe.md)
- [Modules](./project-architecture/module.md)
- [Serialization](./project-architecture/serialization.md)
- [Tensor](./project-architecture/Tensor.md)
- [Backend](./project-architecture/backend.md)
- [Guides for Contributors](./guides/ReadMe.md)
- [Onnx To Burn Conversion Tool: A Development Guide](./guides/onnx-to-burn-conversion-tool.md)
- [Adding a New Operation to Burn](./guides/adding-a-new-operation-to-burn.md)
- [Frequently Encountered Issues](./guides/frequently-encountered-issues/ReadMe.md)
- [Issues Related To Adding Operators](./guides/frequently-encountered-issues/issues-while-adding-ops.md)

View File

@ -0,0 +1,3 @@
# Frequently Encountered Issues
This is a collection of issues people have encountered and asked about on the discord, and is separate from the guides since it often involves a wall of text that is only relevant to a small subset of contributors.

View File

@ -0,0 +1,41 @@
# Issues encountered while adding ops
Below are some of the issues that were encountered while adding ops to the project. If you encounter
an issue while adding an op that isn't listed here, and it's not obvious how to fix it, please add
it to this list. Also, reach out on the [discord server](https://discord.gg/uPEBbYYDB6) if you need help.
## Off by .000001 errors
```sh
---- fusion::base::tests::maxmin::tests::test_mean_dim_2d stdout ---- thread 'fusion::base::tests::maxmin::tests::test_mean_dim_2d' panicked at burn-wgpu/src/fusion/base.rs:185:5: assertion `left == right` failed left: Data { value: [1.0, 4.0], shape: Shape { dims: [2, 1] } } right: Data { value: [0.99999994, 3.9999998], shape: Shape { dims: [2, 1] } } ----
tests::maxmin::tests::test_mean_dim_2d stdout ---- thread 'tests::maxmin::tests::test_mean_dim_2d' panicked at burn-wgpu/src/lib.rs:49:5: assertion `left == right` failed left: Data { value: [1.0, 4.0], shape: Shape { dims: [2, 1] } } right: Data { value: [0.99999994, 3.9999998], shape: Shape { dims: [2, 1] } }
```
If you encounter this, swap out the `assert_eq!` in the failing test for `tensor1.assert_approx_eq` with `3` as the second argument. The second arguments specifies the level of precision. `3` is equivalent to a less than 0.001 difference between the elements of the two tensors.
## Mismatched types and missing functions
```sh
error[E0308]: mismatched types --> {burn_dir}/target/debug/build/onnx-tests-fed12aaf3671687f/out/model/pow.rs:48:45 | 48 | let pow1_out1 = input1.clone().powf(input1); | ---- ^^^^^^ expected `f32`, found `Tensor<B, 4>` | | | arguments to this method are incorrect | = note: expected type `f32` found struct `Tensor<B, 4>`
note: method defined here --> {burn_dir}/burn-tensor/src/tensor/api/float.rs:65:12 | 65 | pub fn powf(self, value: f32) -> Self { | ^^^^
error[E0599]: no method named `powf_scalar` found for struct `Tensor` in the current scope --> {burn_dir}/target/debug/build/onnx-tests-fed12aaf3671687f/out/model/pow.rs:50:35 | 50 | let pow2_out1 = pow1_out1.powf_scalar(cast1_out1); | ^^^^^^^^^^^ method not found in `Tensor<B, 4>`
error[E0599]: no method named `powi` found for struct `Tensor` in the current scope --> {burn_dir}/target/debug/build/onnx-tests-fed12aaf3671687f/out/model/pow_int.rs:49:40 | 49 | let pow1_out1 = input1.clone().powi(input1); | ^^^^ method not found in `Tensor<B, 4, Int>` Some errors have detailed explanations: E0308, E0599.
For more information about an error, try `rustc --explain E0308`. error: could not compile `onnx-tests` (test "onnx_tests") due to 3 previous errors
```
If you are getting this error, you probably didn't implement your operator for the actual Tensor struct.
This issue was encountered when adding the Pow operator. The operation was added to the
`FloatTensorOps` and `IntTensorOp` traits, but not for the numeric trait (under
`burn-tensor/src/tensor/api/numeric.rs`). This, coupled with `powf` existing prior to the PR though
only for scalar values (which had been renamed, just not in the right place), led to this confusing
issue where it looked like the function was found, but the type was wrong. If that's the case, make
sure that it's implemented for the appropriate type, in this case `Float` under
[burn-tensor/src/tensor/api/numeric.rs](https://github.com/tracel-ai/burn/blob/4ca3e31601228952bb1c1492bc9cd2adf15b5cf1/burn-tensor/src/tensor/api/numeric.rs#L2186),
and calling the `TensorOp.foo_op` defined under
[burn-tensor/src/ops/tensor.rs](https://github.com/tracel-ai/burn/blob/4ca3e31601228952bb1c1492bc9cd2adf15b5cf1/burn-tensor/src/tensor/ops/tensor.rs#L873)

View File

@ -0,0 +1,3 @@
# Getting Started
This section is for setting up the environment and how to do basic development tasks such as running tests and checking your code before committing. If you need help with the process or run into issues, feel free to ask in the [discord server](https://discord.gg/uPEBbYYDB6)

View File

@ -0,0 +1,28 @@
# Configuring your editor
These are not required, and most of this isn't specific to Burn, but it's definitely helpful if you
haven't already done it.
## VSCode
Install the following extensions:
- [rust-lang.rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
- [tamasfe.even-better-toml](https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml)
- [serayuzgur.crates](https://marketplace.visualstudio.com/items?itemName=serayuzgur.crates)
- [vadimcn.vscode-lldb](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb)
### Setting up the Debugger
To use the debugger, follow these steps:
1. Open `Command Palette` with `Ctrl+Shift+P` or `F1` and type `LLDB: Generate Launch Configurations from Cargo.toml` then select it, this will generate a file that should be saved as `.vscode/launch.json`.
2. Select the configuration from the "run and debug" side panel (it have a infested play button), then select the target from
3. Now you can enable breakpoint on code through IDE and then start debugging the library/binary you want, such as the following example:
![debug-options](debug-options-vscode.png)
If you're creating a new library or binary, keep in mind to repeat the step 1. to always keep a fresh list of targets.
## Have another editor? Open a PR!

View File

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 189 KiB

View File

@ -0,0 +1,41 @@
# Setting up the environment
There are a couple of tools that need to be installed, and commands to be familiar with, depending
on what part of the project you plan on contributing to. This section should be up to date with
current project practices (as of 2024-01-26)
## General
There are a few commands you want to run prior to any commit for a non-draft PR:
1. `cargo clippy --fix --allow-dirty`, this will run clippy and fix any issues it can, the allow
dirty flag is required whenever you have uncommitted changes
2. `cargo fmt --all`, this will run rustfmt on all files in the project
3. `./run_checks.sh all`, this is a script located in the project root that builds and tests the
project. It is required that this passes prior to merging a PR. Fair warning, running these tests
can take a while[^linux_mem_note].
## Updating the burn semver version
If for some reason you need to bump for the next version (though that should probably be left to the maintainers), edit the semantic version number in `burn/Cargo.toml`, and then run
`cargo update` to update the lock file.
## Contributing to either the Burn Book or Contributor Book
Both the Burn Book and the Contributor Book are built with mdbook. If in the process of adding or modifying a page in the books, if you need to inspect the generated output(such as when using mathjax which seems prone to breakage), run use `mdbook --open <path/to/book>` or run `cargo xtask books {burn|contributor} open` which will install and use mdbook automatically.
Alternatively, if you want to install mdbook directly, run the
following command[^update_note]:
```bash
cargo install mdbook
```
Also instead of running `./run_checks.sh all`, you can run `./run_checks.sh typo`, or `cargo xtasks run-checks typo`, to only check for
misspellings. This will install [typo](https://crates.io/crates/typos-cli), and if any are
encountered you should be able to run `typo -w /path/to/book` to fix them.
[^linux_mem_note]: If your system is running into issues with memory and you are on linux, you may want to switch to a [virtual console](https://wiki.archlinux.org/title/Linux_console#Virtual_consoles) to run the tests. To do this, press `ctrl+alt+f3` to switch to a virtual console (and log in), and either `ctrl+alt+f2` or `ctrl+alt+f1` to switch back to your graphical session.
[^update_note]: You might also want to install [cargo-update](https://github.com/nabijaczleweli/cargo-update) to easily keep your tools up to date, though it is in no way required.

View File

@ -0,0 +1,32 @@
# Testing
## Test for TensorOps
The following examples use matrix multiplication operation.
Test for Tensor operations (as in given this input, expect it match or approximate this output) are
defined only in
[`burn-tensor/src/test/ops`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-tensor/src/tests/ops/matmul.rs#L1)
and not in the backends, with the exception of `burn-autodiff`. These tests are added to the
`testgen_all` macro rule in
[`burn-tensor/src/test/mod.rs`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-tensor/src/tests/mod.rs#L59).
This is then propagated to the existing backends without any additional work.
### Test for Autodiff
The following examples use the power operation.
Tests for autodiff go under
[burn-autodiff/src/tests/{op_name}.rs](https://github.com/tracel-ai/burn/blob/4ca3e31601228952bb1c1492bc9cd2adf15b5cf1/burn-autodiff/src/tests/pow.rs#L31)
(replace `op_name` with whatever makes sense for your op), and for tensor operations both the left and
right sides need to be verified. The easiest way to do this, is to:
1. use small tensors with simple values
2. pop open a terminal, launch `ipython` and import `numpy` then do the calculations by hand. You
can also use [google colab](https://colab.google/) if you prefer so that you don't have to
install the packages on your system.
3. compare the actual output to the expected output for lhs, rhs and regular operation
Generally, it seems preferable to use
`actual_output_tensor.into_data().assert_approx_eq(&expected_tensor_data,3)` to `assert_eq!(...` due
to occasional hiccups with floating point calculations.

View File

@ -0,0 +1,3 @@
# Guides for Contributors
The following guides are meant to help contributors trying to accomplish specific tasks, such as adding new operations to Burn or generating test models for `burn-import`.

View File

@ -0,0 +1 @@
# Guides for Contributors

View File

@ -0,0 +1,201 @@
# Adding a new operation to burn
Let's discuss how one might go about adding new operators to Burn, using the example of the
pow operator added in [this PR](https://github.com/tracel-ai/burn/pull/1133/files). In that
PR, the following things took place (albeit not in this order)
## Adding the Op to burn-tensor
`burn-tensor` is the crate that defines all tensor operations that need to be implemented by the
various backends. The core of this lies in `burn-tensor/src/tensor/api/numeric.rs`, which is home to
the numeric trait and its implementation for the different tensor types. The numeric trait is the
home of all tensor operations that are numeric in nature and that are shared by `Int` and `Float`
Tensor types. More information on the relationship between Tensor modules can be found under the
section for [Tensor Architecture](../project-architecture/Tensor.md#tensorops).
Here is where pow was added to `burn-tensor/src/tensor/api/numeric.rs`:
1. for the
[`Tensor<Backend,Dimension,Kind>` struct](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/api/numeric.rs#L553)
2. for the
[numeric trait](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/api/numeric.rs#L1618)
3. for the implementation of numeric for
[float](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/api/numeric.rs#L2186)
and
[int](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/api/numeric.rs#L1903)
Tensor is a struct that has a single member: `primitive` (defined
[here](https://github.com/tracel-ai/burn/blob/main/burn-tensor/src/tensor/api/base.rs)), that is
defined by it's
[`Kind`](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/api/kind.rs#L15):
one of `Bool`, `Float`, or `Int` (those linked in 3). These call the ops for that data type defined
in the
[`Backend`](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/backend/base.rs#L52)
supertrait[^supertrait]. This is the trait that is then implemented by the different `burn-` backends (such
as `burn-ndarray` and `burn-wgpu`) which implement the functions if no default is provided.
In this case, we don't need to worry about `Bool` Tensors. Ops for `Float` is implemented under
[burn-tensor/src/tensor/ops/tensor.rs](https://github.com/tracel-ai/burn/blob/3b7d9feede702cd616c273fa9eba9fbf14f66964/burn-tensor/src/tensor/ops/tensor.rs#L873),
and for `Int` under
[`burn-tensor/src/tensor/ops/int_tensor.rs`](https://github.com/tracel-ai/burn/blob/e1d873abe2c2fa0bb316719c4761eaf796291166/burn-tensor/src/tensor/ops/int_tensor.rs#L486).
The current convention is ops of each type, if not unique to that type, are prefixed with the type. So `powf` and sundry would be defined as `int_powf` for `IntTensorOps` and `float_powf` for `FloatTensorOps`. If an op is unique to a type, then it should be implemented under `burn-tensor/src/api/{type}.rs`. For example, here is an implementation for [`sin` under `burn-tensor/src/api/float.rs`](https://github.com/tracel-ai/burn/blob/2acf6561dc9e173870d4209ed40ebbdcf7e3888c/burn-tensor/src/tensor/api/float.rs#L78) which obviously doesn't make sense for `Int` or `Bool` tensors.
The `Int` Tensor function uses the ones defined for Float with 2 extra casts (LHS to a `Float` tensor,
Output to an `Int`). Given that the rest of the code will only look at the float implementations.
### Adding Test
Additional Test should be added to `burn-tensor` under
[`burn-tensor/src/tests/ops/{op_name}.rs`](https://github.com/tracel-ai/burn/burn-tensor/src/tests/ops/powf.rs),
inserting the module name into `burn-tensor/src/tests/ops/mod.rs`. Then add it to the `testgen_all`
macro under `burn-tensor/src/tests/mod.rs`. This macro is called from the `lib.rs` file in each backend, which autogenerates the tests for that specific backend. It isn't necessary to define tests in the backends directly, save for those that require specific testing such
as`burn-autodiff`
## Adding the Op to the burn-autodiff
Since this is probably the hardest and the least straightforward, we'll cover this backend
separately. Burn-autodiff enables other backends to use autodifferentiation[^autodiff]. Ops for float types
are implemented in
[burn-autodiff/src/ops/tensor.rs](https://github.com/tracel-ai/burn/blob/e1d873abe2c2fa0bb316719c4761eaf796291166/burn-autodiff/src/ops/tensor.rs#L1523)
and need to:
1. define a unit struct [^absolute_units] that implements a backward (pass) function
2. Within the backward function, as this is an elementwise binary operation it implements the binary
function (from backward.rs under the same directory), the last 2 arguments are two closures that
define the left and right partial derivatives.
3. Then defines what happens when a specific operation is tracked or untracked, where untracked just
calls the function in the normal way, and tracked executes the backward function defined above
Steps 1 and 3 are boilerplate, so much so that you can probably just copy the contents of another op
of the same type (binary, unary) and change the name of the struct, and ensure that either both
sides have the data they need (if they need to have a copy of the opposite sided tensor, clone its
contents).
For those that need it, here is a quick refresher on the necessary calculus. If you
are familiar with how to calculate partial derivatives, you can skip this section.
Since pow is a binary operation, the left and right functions are the partial
derivatives with respect to the left and right sided tensors.
Let's define the operator as a function \\(f(x,y)=x^{y}\\) , where \\(x\\) is the left hand tensor
and \\(y\\) is the right handed tensor. The two closures are defining the partial derivatives of
\\(f\\) with respect to \\(x\\),\\(y\\). Treat the other variables as a constant
$$\frac{\delta }{\delta x} (x^{y})= y \cdot x^{y-1}$$ is the left handed closure, and
$$\frac{\delta }{\delta y} (x^{y}) = x^{y} \cdot ln(x)$$
is the right. If you aren't sure how to calculate these by hand, I recommend using
[symbolab](<https://www.symbolab.com/solver/partial-derivative-calculator/%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial%20x%7D%5Cleft(x%5E%7By%7D%5Cright)?or=input>),
plug in your operator in terms of \\(x\\) and \\(y\\), and just swap out the variable
\\(x\\)|\\(y\\) in the partial derivative to get the other side.
### Testing autodiff
Test for autodiff go under
[burn-autodiff/src/tests/{op_name}.rs](https://github.com/tracel-ai/burn/blob/4ca3e31601228952bb1c1492bc9cd2adf15b5cf1/burn-autodiff/src/tests/pow.rs#L31)
(replacing `op_name` with whatever makes sense for your op), and for tensor operations both the left and
right side need to be verified. The easiest way to do this, is to
1. use small tensors with simple values
2. Compute the expected results for the chosen tensors, using some independent and reliable tool. For instance, you can pop open a terminal and launch `ipython` import `numpy` (or just use
[google colab](https://colab.google/) if you don't have the packages installed and don't want to
install them), and do the calculations by hand.
3. comparing the actual to expected output for lhs, rhs and regular operation
generally, it seems preferable to use
`actual_output_tensor.to_data().assert_approx_eq(&expected_tensor_data,3)` to `assert_eq!(...` due
to occasional hiccups with floating point calculations.
## Adding the Op to other backends
Most of these are fairly straightforward implementations. For reference here's pow's float
implementation for torch, ndarray and candle backends:
1. Torch implementation in
[burn-tch/src/ops/tensor.rs](https://github.com/tracel-ai/burn/blob/main/burn-tch/src/ops/tensor.rs#L461)
and the Op used in
[burn-tch/src/ops/base.rs](https://github.com/tracel-ai/burn/blob/4ca3e31601228952bb1c1492bc9cd2adf15b5cf1/burn-tch/src/ops/base.rs#L443)
2. NdArray in
[burn-ndarray/src/ops/tensor.rs](https://github.com/tracel-ai/burn/blob/main/burn-ndarray/src/ops/tensor.rs#L443)
3. Candle in
[burn-candle/src/ops/tensor.rs](https://github.com/tracel-ai/burn/blob/4ca3e31601228952bb1c1492bc9cd2adf15b5cf1/burn-candle/src/ops/tensor.rs#L481)
This is where any calculation happens currently. Playing a guessing game with method names and
seeing what completions are suggested will take you far. If you are having trouble figuring out how
to do it from the docs for that backend,
[try searching github for relevant function calls](https://docs.github.com/en/search-github/github-code-search/understanding-github-code-search-syntax).
## Adding the Op to fusion and wgpu backends
Adding an operator to these backends is fairly straightforward, though due to what these backends
are for, involves a bit more indirection. Fusion, like autodiff, is not a target backend as much as
a backend that enables certain functionality for other backends, in this case kernel fusion (which
is currently only supported for `burn-wgpu`), so adding the operator won't involve doing any
calculation, you'll just be describing how the generated code should look. Most of this can be
copy/pasted/adjusted from other functions.
Here's how powf was added to burn fusion:
1. added powf to the float ops under
[`burn-fusion/src/ops/float.rs`](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-fusion/src/ops/float.rs#L1758)
2. added powf to the `FloatOperationDescription` enum under
[burn-fusion/src/stream/operation.rs](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-fusion/src/stream/operation.rs#L385)
3. added powf to the implementations of `FloatOperationDescription` enum under
[burn-fusion/src/stream/context.rs](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-fusion/src/stream/context.rs#L726)
Adding pow to wgpu was actually pretty easy due to the design. The way wgpu handles tensor-scalar operations is by transforming both into a sequence of vectorized scalar operations. Since powf already existed in burn-wgpu, It was pretty easy to reuse the existing implementation for the situation where both sides of the operation were tensors.
Here is where code was added for powf in burn-wgpu:
1. to the implementation of
[`TensorOps` under `burn-wgpu/src/ops/float_ops.rs`](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-wgpu/src/ops/float_ops.rs#L513)
2. the function being called was added to
[burn-wgpu/src/ops/numeric.rs](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-wgpu/src/ops/numeric.rs#L199)
3. the call to the fmt function use to generate wgsl code in
[`burn-wgpu/src/codegen/kernel.rs`](https://github.com/tracel-ai/burn/blob/main/burn-wgpu/src/codegen/kernel.rs#L208)
4. A custom function generator was added to
[`burn-wgpu/src/codegen/function.rs`](https://github.com/tracel-ai/burn/blob/main/burn-wgpu/src/codegen/function.rs#L99)
We needed to generate some custom wgsl code for powf, primarily due to issues with proper case handling of the wgsl pow function, like 0 to
the 0 power being 1, and any negative number to an even power being positive. We reused as much as
the existing logic as possible, such as the operation output description generation in
[`burn-wgpu/src/fusion/elemwise/builder.rs`](https://github.com/tracel-ai/burn/blob/main/burn-wgpu/src/fusion/elemwise/optimization.rs)
and then branched at the last point based off the var type of the rhs.
## Adding the Op to burn-import
I won't comment on generating the ONNX test files or the tests, as this is already covered
[in the ONNX to burn guide](onnx-to-burn-conversion-tool.md#adding-new-operators), this is more
about the specific changes you need to make when adding new operators after you have generated the
tests.
The crate is divided into two sections `src/burn` and `src/onnx`. The code under the former
corresponds to the operation you've implemented earlier in this guide, and the latter to the
operations defined in the ONNX specification. So when you are loading a model, the operator is first
parsed to an intermediate representation defined by `src/onnx`, and then mapped to a Burn operations
defined under `src/burn/node`.
Let's review the changes made for pow starting from `src/burn` and moving to `src/onnx`:
1. determine the type of operator and add your operator to the appropriate node (operation) type, in
this case
[BinaryNode under burn-import/src/burn/node/binary.rs](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-import/src/burn/node/binary.rs#L160)
along with its
[`to_str` definition](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-import/src/burn/node/binary.rs#L9)
2. add an arm to the match statement inside the `into_burn` function in
[burn-import/src/onnx/to_burn.rs](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-import/src/onnx/to_burn.rs#L269)
for the ONNX `NodeType` (which corresponds to an op in the ONNX spec), and make a
[`foo_conversion` function](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-import/src/onnx/to_burn.rs#L667)
that maps the ONNX node to the binary type
3. specify how dimensions for the output should be derived in
[burn-import/src/onnx/dim_inference.rs](https://github.com/tracel-ai/burn/blob/0368409eb3a7beaeda598c0c8ce1dc0c2c8c07cc/burn-import/src/onnx/dim_inference.rs#L103)
And you're done! Congrats, you just fully added a new op to burn, and we are all one step closer to
the answer to [are we learning yet?](https://www.arewelearningyet.com/) being "Yes, and it's
freaking fast!". Buy yourself a coffee
[^supertrait]: for more on supertraits see [the advanced trait section of the rust book](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-supertraits-to-require-one-traits-functionality-within-another-trait)
[^autodiff]: wiki link for [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation)
[^absolute_units]: for more information on unit structs see [the defining and instantiating structs section of the rust book](https://doc.rust-lang.org/book/ch05-01-defining-structs.html#unit-like-structs-without-any-fields)

View File

@ -0,0 +1 @@
# Frequently Encountered Issues

View File

@ -0,0 +1 @@
# Issues Related To Adding Operators

View File

@ -0,0 +1,80 @@
# ONNX to Burn Conversion Tool: Development Guide
This guide offers in-depth design insights and step-by-step procedures for developers working on the
ONNX to Burn conversion tool. This tool allows the importation of ONNX models into the Burn deep
learning framework written in Rust. It converts both ONNX models to Rust source code and model
weights to Burn state files.
## Table of Contents
1. [Design Overview](#Design-Overview)
1. [Design Goals](#Design-Goals)
2. [Design Decisions](#Design-Decisions)
2. [Adding New Operators](#Adding-New-Operators)
3. [Testing](#Testing)
4. [Resources](#Resources)
## Design Overview
### Design Goals
- Perform best-effort conversion of ONNX models to Rust source code via Burn APIs.
- Convert ONNX model weights to Burn state files.
- Support ONNX models generated by PyTorch (ONNX Opset 16).
- Produce easy-to-understand and modifiable models.
- Ensure the generated models are trainable using Burn APIs.
### Design Decisions
- Limit interaction with ONNX to the Intermediate Representation (IR) stage to simplify the process.
- Ensure operator behavior consistency across different OpSet versions.
- Exclude any ONNX/Protobuf-specific logic from the Burn graph.
The conversion process involves three main stages:
1. Convert ONNX model to Intermediate Representation (IR).
2. Translate IR to a Burn graph.
3. Generate Rust source code from the Burn graph.
## Adding New Operators
To extend `burn-import` with support for new ONNX operators, follow these steps:
1. **Create PyTorch Script**: Place a PyTorch script using the new operator under
`./burn-import/onnx-tests/tests/<op>/<op>.py`. Make sure to print both input and output tensors
for end-to-end testing.
2. **Generate ONNX Model**: Run the PyTorch script to produce an ONNX model.
3. **Visualize ONNX Model**: Use [Netron](https://github.com/lutzroeder/netron) to verify the ONNX
model contains the expected operators.
4. **Generate IR and Burn Graph**: Navigate to `./burn-import/` and run:
```
cargo r -- ./onnx-tests/tests/<op>/<op>.onnx ./out
```
5. **Implement Missing Operators**: If you encounter an error stating that an operator is
unsupported, implement it. The `./out/my-model.graph.txt` should provide relevant information.
6. **Inspect Generated Files**: The `my-model.graph.txt` contains IR details, `my-model.rs` holds
the Burn model in Rust code, and `my-model.json` includes the model data.
7. **Add End-to-End Test**: Include the test in `./burn-import/onnx-tests/tests/onnx_tests.rs`.
Further details can be found in the [onnx-tests README](./burn-import/onnx-tests/README.md).
## Testing
- Unit tests for the Burn graph to Rust source code conversion are mandatory.
- End-to-end tests should include a test ONNX model and its expected output for each operator.
## Resources
1. [PyTorch to ONNX](https://pytorch.org/docs/stable/onnx.html)
2. [ONNX to PyTorch](https://github.com/ENOT-AutoDL/onnx2torch)
3. [ONNX Introduction](https://onnx.ai/onnx/intro/)
4. [ONNX Operators](https://onnx.ai/onnx/operators/index.html)
5. [ONNX Protos](https://onnx.ai/onnx/api/classes.html)
6. [ONNX Optimizer](https://github.com/onnx/optimizer)
7. [Netron](https://github.com/lutzroeder/netron)

View File

@ -0,0 +1,22 @@
# How to read this book
Throughout this book, we try to keep the following structure
## Linking
When referring to structures or functions within codebase, we provide permalinks to the lines in
specific commits, and indicate them by the relative path of their parent file from the project root.
For example this is a reference to the `Tensor` struct in
[`burn-tensor/src/tensor/api/base.rs`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-tensor/src/tensor/api/base.rs#L23)
When some reference information is useful but is beyond the scope of contributing to burn, we
provide that information in a footnote. To build on the previous example, the `Tensor` mentioned is
what's referred to as a newtype struct[^1].
Direct hyperlinks are for tools and resources that are not part of the burn project, but are useful
for contributing to it. For example, when working on implementing an op for autodiff, it is useful
to use [symbolab](https://www.symbolab.com/) to calculate the left and right partial derivatives.
[^1]:
for more information on newtype please refer to
[the Advanced Types chapter of the Rust Book](https://doc.rust-lang.org/book/ch19-04-advanced-types.html#using-the-newtype-pattern-for-type-safety-and-abstraction)

View File

@ -0,0 +1,25 @@
# Overview
Welcome to The Burn Contributor's Book 👋
This book will help you get acquainted with the internals of the Burn deep learning framework and
provide some detailed guidance on how to contribute to the project.
We have crafted some sections for you:
- [Getting Started](./getting-started): Much like the Burn Book for users, we'll start with the
fundamentals, guiding you through tasks like setting up the development environment, how to run
tests, and what you should check prior to each commit.
- [Project Architecture](./project-architecture): This section will give you a more in-depth look at
the architecture of Burn
- [Guides](./guides): We'll provide some guides on how to do specific tasks, such as adding a new
operation to Burn.
- [Frequently Encountered Issues](./frequently-encountered-issues): If you are running into an issue
that has you stumped, this is the section to check out prior to asking on the [discord](https://discord.gg/uPEBbYYDB6). It's a
collection of errors encountered by contributors, what caused them, and how they were resolved.
As this book is geared towards contributors and not towards users of Burn, we'll assume you have a
good understanding of software development, but will make efforts to explain anything outside of
that scope, or at least provide links to resources that explain it better than we can.

View File

@ -0,0 +1,19 @@
# Project Architecture
This Section documents most major architectural decisions with the reasoning behind them.
**Sections**
- [Module](./module.md)
- [Optimization](./module.md#optimization)
- [Constraints](./module.md#constraints)
- [Solution](./module.md#solution)
- [Serialization](./serialization.md)
- [Constraints](./serialization.md#constraints)
- [Solution](./serialization.md#solution)
- [Pros](./serialization.md#pros)
- [Cons](./serialization.md#cons)
- [Compatibility](./serialization.md#compatibility)
- [Tensor](./tensor.md)
- [Backend](./backend.md)
- [Autodiff](./backend.md#autodiff)

View File

@ -0,0 +1 @@
# Architecture Overview

View File

@ -0,0 +1,62 @@
# Tensor
A proper deep learning framework should have a fast tensor implementation with autodiff support, and
Burn is no exception. The tensor API abstracts away backend implementation details and focuses on
usability without compromising performance. To make it as easy as possible to use, there is only one
tensor type, which is different from multiple tensor and deep learning crates in Rust. Generic
parameters are used instead to specialize the tensor type.
- **B: Backend:** The first argument is the backend on which the tensor implementation lies.
- **const D: usize:** The second argument is the dimensionality of the tensor.
- **K: TensorKind:** The third argument is the tensor kind, which can be either Float, Int or Bool.
By default, the tensor kind is set to Float, so for most tensors, the kind argument is not
necessary.
Having one struct for tensors reduces the complexity of the tensor API, which also means less
duplicated documentation to write and maintain.
Tensors are thread-safe, which means that you can send a tensor to another thread, and everything
will work, including auto-differentiation. Note that there are no in-place tensor operations since
all tensor operations take owned tensors as parameters, which make it possible to mutate them.
Tensors can be shared simply by cloning them, but if there is only one reference to a tensor, the
backend implementation is free to reuse the tensor's allocated data. For more information about how
it is done, you can have a look at this
[blog post](https://burn.dev/blog/burn-rusty-approach-to-tensor-handling).
## TensorOps
Operations on Tensors are defined in traits (generally part of the Backend Supertrait) and
implemented for the Tensor struct. The appropriate parent trait of an op depends on the type of
operation:
- `base` => All tensor kinds should implement these operations (Reshape, into_data, etc.). The
implementation is in `burn-tensor/src/tensor/api/base.rs`.
- `numeric` => All tensors that are numeric by nature should implement these operations (Add, Sub,
Div, etc.). The implementation is in `burn-tensor/src/tensor/api/numeric.rs`.
- `Float` => Tensor operations are only available for float tensors. The implementation is in
`burn-tensor/src/tensor/api/float.rs`.
- `Int` => Tensor operations are only available for int tensors. The implementation is in
`burn-tensor/src/tensor/api/int.rs`.
- `bool` => Tensor operations are only available for bool tensors. The implementation is in
`burn-tensor/src/tensor/api/bool.rs`.
`Numeric` is directly implemented for `Float` and `Int` tensors, and in general, The implementations
for these methods are calling the corresponding `{Int|Float}TensorOp` method defined in the backend
supertrait.
Anything that is implemented by numeric should have an implementation in the `{Int|Float}TensorOp`
traits, though it may be avoidable if the operation for one type requires casting to the other type.
To provide an example, Powf should be implemented for `Int` tensors, but it should not be an Int
Tensor Operation. The LHS should be converted to a float, and the output should be converted back to
an int. So it's possible to avoid implementing `IntTensorOp` altogether.
Additionally there are some operations that should be defined as functions instead of tensor/tensor
op methods. these are:
`module` => These should be exported as functions instead of methods on tensors. The implementation
is in `burn-tensor/src/tensor/module.rs` (Might be moved to `tensor/api/module.rs`). `activation` =>
These should also be exported as functions instead of methods on tensors. The implementation is in
`burn-tensor/src/tensor/activation/base.rs` (Might be moved to `tensor/api/activation.rs`).
Note that some activations are just a combination of backend operations and are not declared in
`burn-tensor/src/tensor/ops/activation.rs`

View File

@ -0,0 +1,39 @@
# Backend
The Backend trait abstracts multiple things:
- Device type
- Float tensor type
- Bool tensor type
- Int tensor type
- Float element type
- Int element type
- Float tensor operations (kernels)
- Int tensor operations (kernels)
- Bool tensor operations (kernels)
Even though having one type for tensors is convenient for the tensor API, it can be cumbersome when
implementing a backend. Therefore, backends can decide, through associated types, what types they
want to use for their int, float, and bool tensors. Since float and int can have multiple
precisions, the float and int element types are also associated types that must be declared by the
backend.
Note that the backend chooses the precision and not the user. Since not all backends will support
the same element types, no assumptions must be made. Therefore, there are no methods on tensors to
change the precision, except for the `to_full_precision` function, which ensures numerical stability
on the current backend. Backend implementations can provide a way to choose the precision, which can
be accomplished with a generic parameter (e.g. `NdArray<f32>`).
To be as general as possible, tensor operations are implemented as plain functions. There is no
object or self, just functions that take tensors as input and often return tensors as output as
well. Backend implementations are free to use their own patterns to implement these kernels. Note
that Burn is a dynamic graph deep learning framework, so backends may have to implement asynchronous
kernel executions for performance reasons.
## Autodiff
As of now, there is only one backend decorator that supports autodiff. It follows the decorator
pattern, making any backend differentiable. However, the `AutodiffBackend` trait abstracts how
gradients are calculated, and other approaches to autodiff might be added later. For more
information about how the current autodiff backend works, you can read this
[blog post](https://burn.dev/blog/burn-rusty-approach-to-tensor-handling).

View File

@ -0,0 +1,93 @@
# Module
Modules are a way of creating neural network structures that can be easily optimized, saved, and
loaded with little to no boilerplate. Unlike other frameworks, a module does not force the
declaration of the forward pass, leaving it up to the implementer to decide how it should be
defined.
Additionally, most modules are created using a (de)serializable configuration, which defines the
structure of the module and its hyper-parameters. Parameters and hyper-parameters are not serialized
into the same file and both are normally necessary to load a module for inference.
## Optimization
Optimization is normally done with gradient descent (or ascent for reinforcement learning), and it
is important to provide an easy API for optimizing modules.
### Constraints
1. **Users should be able to control what is optimized.** Modules can contain anything for maximum
flexibility, but not everything needs to be optimized.
2. **Optimizers should have a serializable state that is updated during training.** Many optimizers
keep track of previous gradients to implement some form of momentum. However, the state can be
anything, not just tensors, allowing for easy implementation of any kind of optimizer.
3. **The learning rate can be updated during training.** Learning rate schedulers are often used
during training and should be considered as a key aspect.
### Solution
`Module` trait defined in
[`burn-core/src/module/base.rs`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-core/src/module/base.rs#L83)
`Optimizer` trait defined in
[`burn-core/src/optim/base.rs`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-core/src/optim/base.rs#L8)
The solution to this problem comprises multiple parts. Firstly, the `Optimizer` trait is quite
similar to the `Module` trait, in terms of saving and loading the state. Please refer to the
[serialization](./serialization.md) section for more details.
Secondly, two traits were created. The `Optimizer` trait is general and relatively unopinionated,
with a simple `step` method that takes a learning rate, a module, and the gradients. The other
trait, `SimpleOptimizer`, aims to provide an easier API for implementing new optimizers. The goal is
to allow implementations to avoid handling missing gradients, loading and exporting records,
navigating the module parameter structure, handling tracked and untracked tensors, and other such
tasks.
Thirdly, each tensor that will be optimized needs to be wrapped into a `Param` struct, which gives
them an ID used for (de)serialization and to associate the state of the optimizer to each parameter.
The `Module` trait has two ways to navigate over parameters. The first one is the `map` function,
which returns `Self` and makes it easy to implement any transformation and mutate all parameters.
The second one is the `visit` function, which has a similar signature but does not mutate the
parameter tensors.
#### SimpleOptimizer
Located in
[`burn-core/src/optim/simple/base.rs`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-core/src/optim/simple/base.rs#L9)
The `SimpleOptimizer` has two major assumptions:
1. The state of the optimizer is linked to each parameter. In other words, each parameter has its
own optimizer state, decoupled from the other parameters.
2. The state of the optimizer implements `Record`, `Clone`, and has a `'static` lifetime.
The benefits of those assumptions materialize in simplicity with little loss in flexibility. The
state associative type is also generic over the dimension, making it extremely easy to include
tensors in the state that share the same dimensionality as its parameter.
To wrap a simple optimizer into the more general `Optimizer` trait, the `OptimizerAdaptor` struct is
used.
#### OptimizerAdaptor
Located in in
[`burn-core/src/optim/simple/adapter.rs`](https://github.com/tracel-ai/burn/blob/b9bd42959b0d3e755a25e383cb5b38beb25559b8/burn-core/src/optim/simple/adaptor.rs#L14)
The `OptimizerAdaptor` is a simple struct composed of a `SimpleOptimizer` and a hashmap with all
records associated with each parameter ID.
When performing an optimization step, the adaptor handles the following:
1. Updates each parameter tensor in the given module using the `Module::map` function.
2. Checks if a gradient for the current tensor exists.
3. Makes sure that the gradient, the tensor, and the optimizer state associated with the current
parameter are on the same device. The device can be different if the state is loaded from disk to
restart training.
4. Performs the simple optimizer step using the inner tensor since the operations done by the
optimizer should not be tracked in the autodiff graph.
5. Updates the state for the current parameter and returns the updated tensor, making sure it's
properly registered into the autodiff graph if gradients are marked as required.
Note that a parameter can still be updated by another process, as it is the case with running metrics
used in batch norm. These tensors are still wrapped using the `Param` struct so that they are
included in the module's state and given a proper parameter ID, but they are not registered in the
autodiff graph.

View File

@ -0,0 +1,101 @@
# Serialization
An important aspect of a deep learning framework is the ability to save and load models from disk.
Despite appearing as a simple feature, it involves numerous constraints that require a proper
solution.
## Constraints
1. **Users should be able to declare the precision of the model to be saved, independent of the
backend in use.**
The modules should not be duplicated in RAM in another precision to support this. Conversion
should be done lazily during (de)serialization.
2. **Users should be able to add any field to a module, even fields that are not serializable.**
This can include constants, database connections, other module references, or any other
information. Only parameters should be serialized since the structure of the module itself should
be encapsulated with module configurations (hyper-parameters).
3. **Users should be able to declare the format in which the module should be saved.**
This can involve saving to a compressed JSON file or directly to bytes in memory for `no-std`
environments.
4. **Users should be able to create a module with its saved parameters without having to initialize
the module first.**
This will avoid unnecessary module initialization and tensor loading, resulting in reduced cold
start when dealing with inference.
In addition to all of these constraints, the solution should be easy to use.
## Solution
In order to be able to add any field to a module without requiring it to be (de)serializable, we
decouple the module type from its state. We create a new type for each module that only contains the
parameters that need to be saved. To generate that type automatically, the user must either declare
which field is a parameter or a constant, or we assume that each field implements the module trait.
The second solution was chosen as it simplifies the code generation and reduces the size of the user
API. This means that the `Module` trait should be implemented by
[primitives types](./burn-core/src/module/param/primitive.rs). The following diagrams highlight the
main types and traits used in the solution.
<div align="center">
<h4>Module Serialization Types</h4>
<img src="./assets/ModuleSerialization.png" width="700px"/>
<div align="left">
The way the types interact with each other is pretty straightforward. First, a module can be
converted into a record using `into_record()`. Note that tensors can be cloned, but it won't
actually copy any data; it will create another reference to the same data.
Then, a `Recorder` instance can be used to serialize any record. The `Recorder` has the
`PrecisionSettings` type as associate type, so any record will be serialized using the settings
provided at the creation of the `Recorder` instance. Note that tensors implement record, and their
item is just a wrapper struct that contains information about the precision in which the tensor
should be saved or loaded. No actual copy of the tensor is made until this point. The tensor is
converted to the `Data` struct and then converted into the specified precision only when
`serialize()` or `deserialize()` are called, which makes the whole process lazy.
To recapitulate, the `Module` trait has an associated type that implements `Record`, which only
contains the parameters of the model. The `Record` trait has a generic associated type (GAT) that
specifies a family of types that can be (de)serialized given any `PrecisionSettings`. Records are
therefore decoupled from the backend in use, and the saved items can be loaded on any backend with
any precision, since the conversion is type-safe and done when `serialize()` and `deserialize()` are
called. All of the types are generated using simple derive macros without any conditional statements
or complex syntax, as `Record` and `Module` are implemented for all primitive types. This makes the
code simple and easy to maintain. In addition, you can extend the current system with your own
`Recorder` and `PrecisionSettings` to control how your modules should be saved and loaded.
### Pros
- All constraints are respected.
- The code is simple and easy to maintain, with very few conditional statements. It is just
recursive data structures, where all the complexity is handled by the framework in primitive
implementations.
- The user API is simple and small, with only two derives (`Record` and `Module`) and no additional
attributes.
- Users can create their own `Module` and `Record` primitive types, which gives them the flexibility
to control how their data is serialized without having to fork the framework.
### Cons
- There are more types, but most of them are automatically generated and single-purpose, so users
don't need to interact with them for common use cases. However, they can do so if necessary.
- When instantiating a new record manually, each field must be set to something, even if the type
itself is `()`, which represents no value. Since the code generation step uses associative types,
it doesn't know that a field type is actually nothing. Creating a record manually without using
the generated function `into_record` or loading it from a file is only useful to load a set of
parameters into a module from an arbitrary source. Using the record may not be the optimal
solution to this problem, and another API could be created in the future.
### Compatibility
Record may become incompatible with previous versions of Burn, depending on the chosen format. The
more compact format (bincode) store minimal information about the type, making it significantly
smaller but less resilient to type changes such adding an optional field. At some point, it might be
necessary to provide a translation script that can translate a more resilient format from a previous
version to a more compact one.

View File

@ -72,7 +72,7 @@ impl Book {
const BURN_BOOK_PATH: &'static str = "./burn-book"; const BURN_BOOK_PATH: &'static str = "./burn-book";
const CONTRIBUTOR_BOOK_NAME: &'static str = "Contributor Book"; const CONTRIBUTOR_BOOK_NAME: &'static str = "Contributor Book";
const CONTRIBUTOR_BOOK_PATH: &'static str = "./burn-book"; const CONTRIBUTOR_BOOK_PATH: &'static str = "./contributor-book";
pub(crate) fn run(book_arg: &BookKind) -> anyhow::Result<()> { pub(crate) fn run(book_arg: &BookKind) -> anyhow::Result<()> {
let (book, command) = match book_arg { let (book, command) = match book_arg {