Integrating torchsharp functionality into Bonsai#48
Merged
Conversation
d2cada1 to
e35980f
Compare
This was referenced Jan 23, 2025
glopesdev
reviewed
Mar 15, 2025
Member
glopesdev
left a comment
There was a problem hiding this comment.
@ncguilbeault This all looks great, only very few things I noticed for this round, it's in great shape and almost there I think!
…ateTensor` at initialization.
…fixed property validation for single-valued tensors, and updated `BuildTensorFromScalarValue` method to use the return type and corrected call to `Expression.Block`.
…rom code review.
…cumentation and method signatures.
… with single and multiple indices.
…e input tensor to the correct `ScalarType` before copying to the output array and changed class names to `ConvertToArray` and `ConvertToNDArray` arrays to convey this. Updated `ScalarTypeConverter` to only handle `ScalarType` conversions and changed properties to ScalarType instead of .NET type.
…ement. Replaced approach of validating string values inside of the class in favour of using the `TensorConverter` class to return the correctly formatted Tensor automatically. Adjusted Process methods to return a single copy of the tensor but ensure that the tensor is moved to the correct device once the device has been initialized.
782e398 to
bb5e34b
Compare
…String` methods in `TensorConverter` class to public to allow tensor conversion operations outside of package namespace
… method of `TensorConverter` class
… classes with ScalarType `Type` property instead of locking it to `CreateTensor` class
glopesdev
reviewed
Apr 4, 2025
…y` and instead convert the ScalarType directly in the `Build` method
glopesdev
approved these changes
Apr 4, 2025
| The `Bonsai.ML.Torch` package primarily provides tooling and functionality for users to interact with and manipulate `Tensor` objects, the core data type of torch which underlies most advanced operations. Additionally, the package provides some capabilities for defining neural network architectures, running forward inference, and learning via back propagation. | ||
|
|
||
| ## Tensor Operations | ||
| The package provides several ways to work with tensors. Users can initialize tensors, (`Ones`, `Zeros`, etc.), create tensors from .NET data types, (`ToTensor`), and define custom tensors using Python-like syntax (`CreateTensor`). Tensors can be converted back to .NET types using the `ToArray` node (for flattening tensors into a unidimensional array) or the `ToNDArray` node (for preserving multidimensional array shapes). Furthermore, the `Tensor` object contains many extension methods which can be used via scripting with `ExpressionTransform` (for example, `it.sum()` to sum a tensor, or `it.T` to transpose), and works with overloaded operators (for example, `Zip` -> `Multiply`). It is also possible to use the `ExpressionTransform` node to access individual elements of a tensor, using the syntax `it.ReadCpuT(0)` where `T` is a primitive .NET data type (i.e. `Single`, `Double`, `Int64`, etc.). |
Member
There was a problem hiding this comment.
This is a really nice overview of available operations, I wonder if we should include docfx xref links to each operator so that people would be able to navigate to them directly from here, but not strictly necessary at this point.
Member
There was a problem hiding this comment.
Example syntax:
[`ToTensor`](xref:Bonsai.ML.Torch.ToTensor)f972dd8 to
922e8d4
Compare
…alization of `Device`
922e8d4 to
ba36f9e
Compare
…ly passed to creation of the `ScriptModule` if it is not null
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Overview
This pull request introduces a new package,
Bonsai.ML.Torch, which adds functionality from the TorchSharp package into Bonsai. It adds functions to perform basic tensor manipulations, linear algebra, inference with neural networks, and more. TheBonsai.ML.Torchpackage is still under heavy development and there are still many features in the TorchSharp package which have not been included. For the first release, this PR focuses on operators that support creating, manipulating, and transformingTensorobjects.Summary of Changes
Addition of New
Bonsai.ML.TorchPackage:Bonsai.ML.Torchproject was added to the solution fileBonsai.ML.sln.Bonsai.ML.Torchadds a reference to the TorchSharp package.Tensor Operations:
Tensorobjects using theToTensorclass.ToTensorhas overloads for key OpenCV.Net data types (IplImage,Mat).IplImageandMatdata types can be converted toTensorobjects using zero-copy, but current conversions fromTensortoMatorIplImageobjects require a complete data copy. One possible solution to this: Support zero-copy OpenCV <-> TorchSharp conversions #55.Tensorobjects can be initialized in various ways, including initializing tensors withOnes,Zeros,ARange,LinSpace,Empty, etc. Custom tensors can be defined using theCreateTensorclass and specifying the values using Python-like syntax(e.g. "[0]" for 1D tensor with a single value, "[[0, 1]]" for a 1x2 tensor, "1.4" for single values, or "[]" for a 1D empty tensor).Tensorobjects can be converted back to .NET arrays using theConvertToArraynode (for flattening data) and theConvertToNDArraynode (for specifying ranked multidimensional arrays).Tensorobjects can be manipulated in various ways. For example,Reshapecan be used to change the dimensions of aTensor,Concatcan be used to concatenate tensors along a specified dimension,ConvertScalarTypecan convert the data type of aTensor, etc.InitializeDeviceTypewith CUDA-compatible GPUs on startup. From there, theCUDAobject can be passed to theDeviceparameter of manyTensorcreation methods. Alternatively computedTensorobjects can be transferred to/fromCUDAdevices using theToDevicenode and setting theDeviceparameter using the desired device object.Tensorobject contains many static extension methods which can be accessed using theExpressionTransformnode. For example, it is possible to callit.sum()to sum all elements of a tensor, orit.Tto transpose a tensor.Tensoroperators. For example, twoTensorobjects can be passed toZip->Multiply.Tensorobjects can be indexed using theIndexclass. TheIndexnode allows specifying the indices using Python-like syntax. It is also possible to define tensor indices explicitly (e.g.,BooleanIndex,ColonIndex, etc.), and use standard Bonsai reactive operators for indexing (e.g.,Zip->Index).Neural Networks:
nn.Moduleclass, the base class for instantiating neural network objects.Moduleobject can be loaded from predefined architectures (e.g., AlexNet, MNIST, and MobileNet) and can optionally load a set of weights from disk. The weights must come from a model with an identical architecture. Model weights can be saved usingSaveModel. For more information about this and how to convert PyTorch modules to the correct format, see this wiki article.Moduleobject can be done using theForwardnode. Currently, theForwardmethod will always work by transforming aTensorobject as input into aTensoroutput.Modulecan be done using theBackwardclass. At this time, only a very small subset of optimizers (Adam), loss functions (NegativeLogLikelihood), and learning rate schedulers are supported. in the future, we plan to bring additional support for customizing training protocols in Bonsai workflows.ITorchModuleinterface and an adapter class,TorchModuleAdapter, to allow bothnn.Moduleobjects andjit.ScriptModuleobjects to be loaded and used in a similar way.Linear Algebra:
Determinant,EigenvalueDecomposition,Inverse, etc.Vision:
Normalize, for transforming image tensors using means and standard deviations for each channel.