• Stars
    star
    14,110
  • Rank 2,093 (Top 0.05 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created about 1 year ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Minimalist ML framework for Rust

candle

discord server Latest version Documentation License

Candle is a minimalist ML framework for Rust with a focus on performance (including GPU support) and ease of use. Try our online demos: whisper, LLaMA2, T5, yolo, Segment Anything.

Get started

Make sure that you have candle-core correctly installed as described in Installation.

Let's see how to run a simple matrix multiplication. Write the following to your myapp/src/main.rs file:

use candle_core::{Device, Tensor};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let device = Device::Cpu;

    let a = Tensor::randn(0f32, 1., (2, 3), &device)?;
    let b = Tensor::randn(0f32, 1., (3, 4), &device)?;

    let c = a.matmul(&b)?;
    println!("{c}");
    Ok(())
}

cargo run should display a tensor of shape Tensor[[2, 4], f32].

Having installed candle with Cuda support, simply define the device to be on GPU:

- let device = Device::Cpu;
+ let device = Device::new_cuda(0)?;

For more advanced examples, please have a look at the following section.

Check out our examples

These online demos run entirely in your browser:

We also provide a some command line based examples using state of the art models:

  • Stable Diffusion: text to image generative model, support for the 1.5, 2.1, and SDXL 1.0 versions.

  • Wuerstchen: another text to image generative model.

  • Whisper: speech recognition model.
  • T5, Bert, JinaBert : useful for sentence embeddings.
  • DINOv2: computer vision model trained using self-supervision (can be used for imagenet classification, depth evaluation, segmentation).
  • BLIP: image to text model, can be used to generate captions for an image.
  • Marian-MT: neural machine translation model, generates the translated text from the input text.

Run them using commands like:

cargo run --example quantized --release

In order to use CUDA add --features cuda to the example command line. If you have cuDNN installed, use --features cudnn for even more speedups.

There are also some wasm examples for whisper and llama2.c. You can either build them with trunk or try them online: whisper, llama2, T5, Phi-v1.5, Segment Anything Model.

For LLaMA2, run the following command to retrieve the weight files and start a test server:

cd candle-wasm-examples/llama2-c
wget https://huggingface.co/spaces/lmz/candle-llama2/resolve/main/model.bin
wget https://huggingface.co/spaces/lmz/candle-llama2/resolve/main/tokenizer.json
trunk serve --release --port 8081

And then head over to http://localhost:8081/.

Useful External Resources

  • candle-tutorial: A very detailed tutorial showing how to convert a PyTorch model to Candle.
  • candle-lora: Efficient and ergonomic LoRA implemenation for Candle. candle-lora has
    out-of-the-box LoRA support for many models from Candle, which can be found here.
  • optimisers: A collection of optimisers including SGD with momentum, AdaGrad, AdaDelta, AdaMax, NAdam, RAdam, and RMSprop.
  • candle-vllm: Efficient platform for inference and serving local LLMs including an OpenAI compatible API server.
  • candle-ext: An extension library to Candle that provides PyTorch functions not currently available in Candle.
  • kalosm: A multi-modal meta-framework in Rust for interfacing with local pre-trained models with support for controlled generation, custom samplers, in-memory vector databases, audio transcription, and more.
  • candle-sampling: Sampling techniques for Candle.

If you have an addition to this list, please submit a pull request.

Features

  • Simple syntax, looks and feels like PyTorch.
  • Backends.
    • Optimized CPU backend with optional MKL support for x86 and Accelerate for macs.
    • CUDA backend for efficiently running on GPUs, multiple GPU distribution via NCCL.
    • WASM support, run your models in a browser.
  • Included models.
    • Language Models.
      • LLaMA v1 and v2.
      • Falcon.
      • StarCoder.
      • Phi v1.5.
      • Mistral 7b v0.1.
      • StableLM-3B-4E1T.
      • Replit-code-v1.5-3B.
      • Bert.
      • Yi-6B and Yi-34B.
    • Quantized LLMs.
      • Llama 7b, 13b, 70b, as well as the chat and code variants.
      • Mistral 7b, and 7b instruct.
      • Zephyr 7b a and b (Mistral based).
      • OpenChat 3.5 (Mistral based).
    • Text to text.
      • T5 and its variants: FlanT5, UL2, MADLAD400 (translation), CoEdit (Grammar correction).
      • Marian MT (Machine Translation).
    • Whisper (multi-lingual support).
    • Text to image.
      • Stable Diffusion v1.5, v2.1, XL v1.0.
      • Wurstchen v2.
    • Image to text.
      • BLIP.
    • Computer Vision Models.
      • DINOv2, ConvMixer, EfficientNet, ResNet, ViT.
      • yolo-v3, yolo-v8.
      • Segment-Anything Model (SAM).
  • File formats: load models from safetensors, npz, ggml, or PyTorch files.
  • Serverless (on CPU), small and fast deployments.
  • Quantization support using the llama.cpp quantized types.

How to use

Cheatsheet:

Using PyTorch Using Candle
Creation torch.Tensor([[1, 2], [3, 4]]) Tensor::new(&[[1f32, 2.], [3., 4.]], &Device::Cpu)?
Creation torch.zeros((2, 2)) Tensor::zeros((2, 2), DType::F32, &Device::Cpu)?
Indexing tensor[:, :4] tensor.i((.., ..4))?
Operations tensor.view((2, 2)) tensor.reshape((2, 2))?
Operations a.matmul(b) a.matmul(&b)?
Arithmetic a + b &a + &b
Device tensor.to(device="cuda") tensor.to_device(&Device::new_cuda(0)?)?
Dtype tensor.to(dtype=torch.float16) tensor.to_dtype(&DType::F16)?
Saving torch.save({"A": A}, "model.bin") candle::safetensors::save(&HashMap::from([("A", A)]), "model.safetensors")?
Loading weights = torch.load("model.bin") candle::safetensors::load("model.safetensors", &device)

Structure

FAQ

Why should I use Candle?

Candle's core goal is to make serverless inference possible. Full machine learning frameworks like PyTorch are very large, which makes creating instances on a cluster slow. Candle allows deployment of lightweight binaries.

Secondly, Candle lets you remove Python from production workloads. Python overhead can seriously hurt performance, and the GIL is a notorious source of headaches.

Finally, Rust is cool! A lot of the HF ecosystem already has Rust crates, like safetensors and tokenizers.

Other ML frameworks

  • dfdx is a formidable crate, with shapes being included in types. This prevents a lot of headaches by getting the compiler to complain about shape mismatches right off the bat. However, we found that some features still require nightly, and writing code can be a bit daunting for non rust experts.

    We're leveraging and contributing to other core crates for the runtime so hopefully both crates can benefit from each other.

  • burn is a general crate that can leverage multiple backends so you can choose the best engine for your workload.

  • tch-rs Bindings to the torch library in Rust. Extremely versatile, but they bring in the entire torch library into the runtime. The main contributor of tch-rs is also involved in the development of candle.

Common Errors

Missing symbols when compiling with the mkl feature.

If you get some missing symbols when compiling binaries/tests using the mkl or accelerate features, e.g. for mkl you get:

  = note: /usr/bin/ld: (....o): in function `blas::sgemm':
          .../blas-0.22.0/src/lib.rs:1944: undefined reference to `sgemm_' collect2: error: ld returned 1 exit status

  = note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
  = note: use the `-l` flag to specify native libraries to link
  = note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo

or for accelerate:

Undefined symbols for architecture arm64:
            "_dgemm_", referenced from:
                candle_core::accelerate::dgemm::h1b71a038552bcabe in libcandle_core...
            "_sgemm_", referenced from:
                candle_core::accelerate::sgemm::h2cf21c592cba3c47 in libcandle_core...
          ld: symbol(s) not found for architecture arm64

This is likely due to a missing linker flag that was needed to enable the mkl library. You can try adding the following for mkl at the top of your binary:

extern crate intel_mkl_src;

or for accelerate:

extern crate accelerate_src;

Cannot run the LLaMA examples: access to source requires login credentials

Error: request error: https://huggingface.co/meta-llama/Llama-2-7b-hf/resolve/main/tokenizer.json: status code 401

This is likely because you're not permissioned for the LLaMA-v2 model. To fix this, you have to register on the huggingface-hub, accept the LLaMA-v2 model conditions, and set up your authentication token. See issue #350 for more details.

Missing cute/cutlass headers when compiling flash-attn

  In file included from kernels/flash_fwd_launch_template.h:11:0,
                   from kernels/flash_fwd_hdim224_fp16_sm80.cu:5:
  kernels/flash_fwd_kernel.h:8:10: fatal error: cute/algorithm/copy.hpp: No such file or directory
   #include <cute/algorithm/copy.hpp>
            ^~~~~~~~~~~~~~~~~~~~~~~~~
  compilation terminated.
  Error: nvcc error while compiling:

cutlass is provided as a git submodule so you may want to run the following command to check it in properly.

git submodule update --init

Compiling with flash-attention fails

/usr/include/c++/11/bits/std_function.h:530:146: error: parameter packs not expanded with β€˜...’:

This is a bug in gcc-11 triggered by the Cuda compiler. To fix this, install a different, supported gcc version - for example gcc-10, and specify the path to the compiler in the CANDLE_NVCC_CCBIN environment variable.

env CANDLE_NVCC_CCBIN=/usr/lib/gcc/x86_64-linux-gnu/10 cargo ...

Linking error on windows when running rustdoc or mdbook tests

Couldn't compile the test.
---- .\candle-book\src\inference\hub.md - Using_the_hub::Using_in_a_real_model_ (line 50) stdout ----
error: linking with `link.exe` failed: exit code: 1181
//very long chain of linking
 = note: LINK : fatal error LNK1181: cannot open input file 'windows.0.48.5.lib'

Make sure you link all native libraries that might be located outside a project target, e.g., to run mdbook tests, you should run:

mdbook test candle-book -L .\target\debug\deps\ `
-L native=$env:USERPROFILE\.cargo\registry\src\index.crates.io-6f17d22bba15001f\windows_x86_64_msvc-0.42.2\lib `
-L native=$env:USERPROFILE\.cargo\registry\src\index.crates.io-6f17d22bba15001f\windows_x86_64_msvc-0.48.5\lib

Extremely slow model load time with WSL

This may be caused by the models being loaded from /mnt/c, more details on stackoverflow.

Tracking down errors

You can set RUST_BACKTRACE=1 to be provided with backtraces when a candle error is generated.

More Repositories

1

transformers

πŸ€— Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.
Python
129,666
star
2

pytorch-image-models

PyTorch image models, scripts, pretrained weights -- ResNet, ResNeXT, EfficientNet, NFNet, Vision Transformer (ViT), MobileNet-V3/V2, RegNet, DPN, CSPNet, Swin Transformer, MaxViT, CoAtNet, ConvNeXt, and more
Python
28,073
star
3

diffusers

πŸ€— Diffusers: State-of-the-art diffusion models for image and audio generation in PyTorch and FLAX.
Python
24,200
star
4

datasets

πŸ€— The largest hub of ready-to-use datasets for ML models with fast, easy-to-use and efficient data manipulation tools
Python
17,530
star
5

peft

πŸ€— PEFT: State-of-the-art Parameter-Efficient Fine-Tuning.
Python
14,585
star
6

tokenizers

πŸ’₯ Fast State-of-the-Art Tokenizers optimized for Research and Production
Rust
8,645
star
7

trl

Train transformer language models with reinforcement learning.
Python
8,483
star
8

text-generation-inference

Large Language Model Text Generation Inference
Python
8,458
star
9

accelerate

πŸš€ A simple way to launch, train, and use PyTorch models on almost any device and distributed configuration, automatic mixed precision (including fp8), and easy-to-configure FSDP and DeepSpeed support
Python
7,306
star
10

chat-ui

Open source codebase powering the HuggingChat app
TypeScript
6,584
star
11

lerobot

πŸ€— LeRobot: End-to-end Learning for Real-World Robotics in Pytorch
Python
4,284
star
12

alignment-handbook

Robust recipes to align language models with human and AI preferences
Python
4,118
star
13

deep-rl-class

This repo contains the syllabus of the Hugging Face Deep Reinforcement Learning Course.
MDX
3,680
star
14

notebooks

Notebooks using the Hugging Face libraries πŸ€—
Jupyter Notebook
3,329
star
15

distil-whisper

Distilled variant of Whisper for speech recognition. 6x faster, 50% smaller, within 1% word error rate.
Python
3,286
star
16

autotrain-advanced

πŸ€— AutoTrain Advanced
Python
3,283
star
17

diffusion-models-class

Materials for the Hugging Face Diffusion Models Course
Jupyter Notebook
3,280
star
18

neuralcoref

✨Fast Coreference Resolution in spaCy with Neural Networks
C
2,819
star
19

parler-tts

Inference and training library for high-quality TTS models.
Python
2,735
star
20

knockknock

πŸšͺ✊Knock Knock: Get notified when your training ends with only two additional lines of code
Python
2,682
star
21

safetensors

Simple, safe way to store and distribute tensors
Python
2,572
star
22

swift-coreml-diffusers

Swift app demonstrating Core ML Stable Diffusion
Swift
2,406
star
23

optimum

πŸš€ Accelerate training and inference of πŸ€— Transformers and πŸ€— Diffusers with easy to use hardware optimization tools
Python
2,290
star
24

text-embeddings-inference

A blazing fast inference solution for text embeddings models
Rust
2,201
star
25

blog

Public repo for HF blog posts
Jupyter Notebook
2,136
star
26

setfit

Efficient few-shot learning with Sentence Transformers
Jupyter Notebook
2,060
star
27

course

The Hugging Face course on Transformers
MDX
2,005
star
28

awesome-papers

Papers & presentation materials from Hugging Face's internal science day
1,996
star
29

evaluate

πŸ€— Evaluate: A library for easily evaluating machine learning models and datasets.
Python
1,825
star
30

datatrove

Freeing data processing from scripting madness by providing a set of platform-agnostic customizable pipeline processing blocks.
Python
1,657
star
31

transfer-learning-conv-ai

πŸ¦„ State-of-the-Art Conversational AI with Transfer Learning
Python
1,654
star
32

swift-coreml-transformers

Swift Core ML 3 implementations of GPT-2, DistilGPT-2, BERT, and DistilBERT for Question answering. Other Transformers coming soon!
Swift
1,543
star
33

pytorch-openai-transformer-lm

πŸ₯A PyTorch implementation of OpenAI's finetuned transformer language model with a script to import the weights pre-trained by OpenAI
Python
1,464
star
34

cookbook

Open-source AI cookbook
Jupyter Notebook
1,416
star
35

huggingface_hub

All the open source things related to the Hugging Face Hub.
Python
1,311
star
36

Mongoku

πŸ”₯The Web-scale GUI for MongoDB
TypeScript
1,300
star
37

huggingface.js

Utilities to use the Hugging Face Hub API
TypeScript
1,277
star
38

gsplat.js

JavaScript Gaussian Splatting library.
TypeScript
1,233
star
39

hmtl

🌊HMTL: Hierarchical Multi-Task Learning - A State-of-the-Art neural network model for several NLP tasks based on PyTorch and AllenNLP
Python
1,185
star
40

llm-vscode

LLM powered development for VSCode
TypeScript
1,160
star
41

pytorch-pretrained-BigGAN

πŸ¦‹A PyTorch implementation of BigGAN with pretrained weights and conversion scripts.
Python
986
star
42

nanotron

Minimalistic large language model 3D-parallelism training
Python
897
star
43

torchMoji

πŸ˜‡A pyTorch implementation of the DeepMoji model: state-of-the-art deep learning model for analyzing sentiment, emotion, sarcasm etc
Python
880
star
44

optimum-nvidia

Python
839
star
45

awesome-huggingface

πŸ€— A list of wonderful open-source projects & applications integrated with Hugging Face libraries.
821
star
46

naacl_transfer_learning_tutorial

Repository of code for the tutorial on Transfer Learning in NLP held at NAACL 2019 in Minneapolis, MN, USA
Python
718
star
47

dataset-viewer

Lightweight web API for visualizing and exploring any dataset - computer vision, speech, text, and tabular - stored on the Hugging Face Hub
Python
640
star
48

optimum-quanto

A pytorch quantization backend for optimum
Python
620
star
49

llm.nvim

LLM powered development for Neovim
Lua
607
star
50

exporters

Export Hugging Face models to Core ML and TensorFlow Lite
Python
559
star
51

transformers-bloom-inference

Fast Inference Solutions for BLOOM
Python
551
star
52

swift-transformers

Swift Package to implement a transformers-like API in Swift
Swift
530
star
53

pytorch_block_sparse

Fast Block Sparse Matrices for Pytorch
C++
523
star
54

llm-ls

LSP server leveraging LLMs for code completion (and more?)
Rust
513
star
55

node-question-answering

Fast and production-ready question answering in Node.js
TypeScript
459
star
56

lighteval

LightEval is a lightweight LLM evaluation suite that Hugging Face has been using internally with the recently released LLM data processing library datatrove and LLM training library nanotron.
Python
442
star
57

large_language_model_training_playbook

An open collection of implementation tips, tricks and resources for training large language models
Python
441
star
58

ratchet

A cross-platform browser ML framework.
Rust
424
star
59

llm_training_handbook

An open collection of methodologies to help with successful training of large language models.
Python
416
star
60

swift-chat

Mac app to demonstrate swift-transformers
Swift
392
star
61

tflite-android-transformers

DistilBERT / GPT-2 for on-device inference thanks to TensorFlow Lite with Android demo apps
Java
368
star
62

community-events

Place where folks can contribute to πŸ€— community events
Jupyter Notebook
368
star
63

text-clustering

Easily embed, cluster and semantically label text datasets
Python
367
star
64

optimum-intel

πŸ€— Optimum Intel: Accelerate inference with Intel optimization tools
Jupyter Notebook
361
star
65

nn_pruning

Prune a model while finetuning or training.
Jupyter Notebook
360
star
66

controlnet_aux

Python
352
star
67

speechbox

Python
339
star
68

100-times-faster-nlp

πŸš€100 Times Faster Natural Language Processing in Python - iPython notebook
HTML
325
star
69

education-toolkit

Educational materials for universities
Jupyter Notebook
320
star
70

unity-api

C#
302
star
71

datablations

Scaling Data-Constrained Language Models
Jupyter Notebook
296
star
72

open-muse

Open reproduction of MUSE for fast text2image generation.
Python
293
star
73

cosmopedia

Python
285
star
74

audio-transformers-course

The Hugging Face Course on Transformers for Audio
MDX
279
star
75

hf_transfer

Rust
242
star
76

hub-docs

Docs of the Hugging Face Hub
221
star
77

optimum-benchmark

πŸ‹οΈ A unified multi-backend utility for benchmarking Transformers, Timm, PEFT, Diffusers and Sentence-Transformers with full support of Optimum's hardware optimizations & quantization schemes.
Python
217
star
78

dataspeech

Python
207
star
79

diarizers

Python
206
star
80

simulate

🎒 Creating and sharing simulation environments for embodied and synthetic data research
Python
185
star
81

instruction-tuned-sd

Code for instruction-tuning Stable Diffusion.
Python
181
star
82

optimum-neuron

Easy, fast and very cheap training and inference on AWS Trainium and Inferentia chips.
Jupyter Notebook
176
star
83

llm-swarm

Manage scalable open LLM inference endpoints in Slurm clusters
Python
176
star
84

OBELICS

Code used for the creation of OBELICS, an open, massive and curated collection of interleaved image-text web documents, containing 141M documents, 115B text tokens and 353M images.
Python
170
star
85

olm-datasets

Pipeline for pulling and processing online language model pretraining data from the web
Python
170
star
86

data-is-better-together

Let's build better datasets, together!
Jupyter Notebook
162
star
87

diffusion-fast

Faster generation with text-to-image diffusion models.
Python
157
star
88

workshops

Materials for workshops on the Hugging Face ecosystem
Jupyter Notebook
146
star
89

api-inference-community

Python
145
star
90

jat

Distributed online training of a general multi-task Deep RL Agent
Python
136
star
91

chug

Minimal sharded dataset loaders, decoders, and utils for multi-modal document, image, and text datasets.
Python
136
star
92

optimum-habana

Easy and lightning fast training of πŸ€— Transformers on Habana Gaudi processor (HPU)
Python
132
star
93

sharp-transformers

A Unity plugin for using Transformers models in Unity.
C#
129
star
94

hf-hub

Rust client for the huggingface hub aiming for minimal subset of features over `huggingface-hub` python package
Rust
109
star
95

competitions

Python
104
star
96

frp

FRP Fork
Go
102
star
97

coreml-examples

Swift Core ML Examples
Swift
98
star
98

olm-training

Repo for training MLMs, CLMs, or T5-type models on the OLM pretraining data, but it should work with any hugging face text dataset.
Python
92
star
99

fuego

[WIP] A πŸ”₯ interface for running code in the cloud
Python
85
star
100

tune

Python
83
star