TorchSharp Examples and Tutorials

repository·main·Indexed 41 days ago

https://github.com/dotnet/torchsharpexamples

Practical examples and tutorials for TorchSharp, .NET-only bindings to libtorch. Includes C# and F# implementations for deep learning, Jupyter Notebook tutorials covering tensors, CUDA, and models, and sample implementations for CIFAR-10 architectures (AlexNet, ResNet, MobileNet, VGG) and Sequence-to-Sequence Transformer models.

Tokens
17.6K
Snippets
67
Records
74
Agent score
51%

What's inside TorchSharp

  1. Understand the TorchSharp Examples structure

    main

    The repository provides examples in both C# and F#.

    • C# Implementation: Consists of a Models library and a XXXExamples console application. The console apps are designed for batch training and require you to specify the model via the command line.
    • F# Implementation: Models are bundled directly with the training code.
    • Utility Library: A C# library used by both C# and F# implementations.

    Note on Data Sets: The repository does not contain actual data sets. You must download and extract them manually as described in the Data Sets section.

  2. Install TorchSharp via NuGet

    main

    To use TorchSharp, you must install the main package along with a backend package. Since version 0.93.4, the package structure is simplified: you only need to select one of the following three packages, and it will automatically include the necessary dependencies:

    • TorchSharp-cpu: For CPU-based training and inference.
    • TorchSharp-cuda-windows: For CUDA-accelerated training on Windows.
    • TorchSharp-cuda-linux: For CUDA-accelerated training on Linux.

    If you are using an existing project that references libtorch-cpu, you must replace those references with the appropriate CUDA package if you intend to train on an NVIDIA GPU.

    Packages:
    - TorchSharp-cpu
    - TorchSharp-cuda-windows
    - TorchSharp-cuda-linux
  3. Manage upstream repository for contributions

    main

    If you are contributing to the repository, it is recommended to add the original repository as an upstream remote to keep your fork synchronized.

    # Add the upstream remote
    git remote add upstream https://github.com/dotnet/TorchSharpExamples.git
    
    # Update your local main branch
    git checkout main
    git pull upstream main
    git push origin main
    
    # Merge updates into your development branch
    git checkout <<your dev branch>>
    git merge main
  4. How to run TorchSharp tutorials using interactive notebooks

    main

    Most TorchSharp tutorials are provided as interactive notebooks designed to be executed using .NET Interactive.

    To follow these tutorials, it is recommended to use Visual Studio Code with the .NET Interactive extension installed. This environment allows for an interactive, step-by-step learning experience where you can execute code cells and view results immediately.

    # Recommended setup:
    # 1. Install Visual Studio Code
    # 2. Install the .NET Interactive extension in VS Code
  5. Choose a tutorial language: C# or F#

    main

    TorchSharp tutorials are organized by programming language. You should choose the tutorial path that matches your preferred language:

    • C# Tutorials: For developers working in C#.
    • F# Tutorials: For developers working in F#.
    # Choose your path:
    - [C# Tutorials](./CSharp/README.md)
    - [F# Tutorials](./FSharp/README.md)
  6. Access F# TorchSharp Tutorials

    main

    The tutorials/FSharp/ directory contains a series of Jupyter Notebook tutorials (.ipynb) designed to teach TorchSharp usage using the F# language. The tutorials cover the progression from environment setup to advanced topics like CUDA and model building.

    Available tutorials include:

    • Tutorial 1: Setting Things Up
    • Tutorial 2: Tensors
    • Tutorial 3: Basic Numerics
    • Tutorial 4: Random Numbers and Distributions
    • Tutorial 5: CUDA
    • Tutorial 6: Models
    • Tutorial 7: Learning Rate Schedulers
    • Tutorial 8: TorchVision
  7. Install CUDA support for TorchSharp

    main

    To use GPU acceleration, you must install the appropriate CUDA backend package for your operating system instead of the standard TorchSharp-cpu package.

    • Windows: Use TorchSharp-cuda-windows.
    • Linux: Use TorchSharp-cuda-linux.
    • MacOS: CUDA is not supported.

    Note: For training vision models, ensure your GPU has sufficient dedicated memory (at least 8MB is recommended for basic tasks like CIFAR10; 6MB may be insufficient).

    #r "nuget: TorchSharp-cuda-windows"
  8. Access C# TorchSharp Tutorials

    main

    The torchsharpexamples repository provides a series of Jupyter Notebook tutorials for learning TorchSharp using C#. These tutorials cover the progression from environment setup to advanced deep learning concepts like models and learning rate schedulers.

    Available tutorials include:

    • Tutorial 1: Setting Things Up - Initial environment configuration.
    • Tutorial 2: Tensors - Working with the core tensor data structure.
    • Tutorial 3: Basic Numerics - Fundamental numerical operations.
    • Tutorial 4: Random Numbers and Distributions - Generating random data.
    • Tutorial 5: CUDA - Utilizing GPU acceleration.
    • Tutorial 6: Models - Building neural network architectures.
    • Tutorial 7: Learning Rate Schedulers - Managing optimization schedules.
    • Tutorial 8: TorchVision - Computer vision utilities.
  9. What is a Learning Rate Scheduler and why use one?

    main

    A Learning Rate (LR) Scheduler is an object that has access to the internal state of an optimizer and can modify the learning rate as training progresses.

    Using a constant learning rate can be problematic:

    • Too small: Training becomes extremely slow and wastes compute resources.
    • Too large: Training may fail to converge, result in numeric overflow, or produce NaNs.

    Schedulers allow you to start with a relatively large learning rate and decrease it as you approach a solution, which often leads to better convergence. Some schedulers can also modify other optimizer states, such as momentum.

  10. Implement a custom Dataset and DataLoader for advanced training

    main

    For more robust training pipelines, implement a custom torch.utils.data.Dataset. This allows you to leverage torch.utils.data.DataLoader, which provides features like automatic batching and data shuffling.

    To implement a custom dataset:

    1. Inherit from torch.utils.data.Dataset.
    2. Implement the constructor to load your data (e.g., via torch.Tensor.load()).
    3. Override GetTensor(long index) to return a Dictionary<string, torch.Tensor> containing the sample and its label.
    4. Override the Count property to return the number of items.

    Once implemented, pass the dataset to a DataLoader with desired batch_size and shuffle settings.

    class SyntheticDataset : torch.utils.data.Dataset {
        public SyntheticDataset(string fileName) {
            _data = torch.Tensor.load(fileName + ".x");
            _labels = torch.Tensor.load(fileName + ".y");
        }
    
        public override Dictionary<string, torch.Tensor> GetTensor(long index) {
            return new Dictionary<string, torch.Tensor> {
                { "data", _data[(int)index] },
                { "label", _labels[(int)index] }
            };
        }
    
        public override long Count => _data.shape[0];
        private torch.Tensor _data;
        private torch.Tensor _labels;
    }
    
    // Usage:
    var training_data = new SyntheticDataset("train.dat");
    var train = new torch.utils.data.DataLoader(training_data, 200, shuffle: true);
  11. Understand Broadcasting in TorchSharp

    main

    Broadcasting allows TorchSharp to perform arithmetic between tensors of different shapes without allocating new memory for the smaller tensor. TorchSharp automatically adjusts the shape of a tensor to be compatible with another tensor during an operation.

    This works for:

    • Singletons: Tensors with no shape (e.g., a single scalar value).
    • Compatible Shapes: Any tensors whose dimensions follow broadcasting rules (e.g., adding a (4) shape tensor to a (3, 4) shape tensor).
    let a = torch.ones(3,4)
    // Broadcasting a (4) shape tensor to (3, 4)
    (a + torch.ones(4)).print()
    
    // Broadcasting a (1, 4) shape tensor to (3, 4)
    a + torch.ones(1,4)