repo_id
stringlengths
15
89
file_path
stringlengths
27
180
content
stringlengths
1
2.23M
__index_level_0__
int64
0
0
hf_public_repos/candle/candle-book
hf_public_repos/candle/candle-book/src/lib.rs
#[cfg(test)] pub mod simplified; #[cfg(test)] mod tests { use anyhow::Result; use candle::{DType, Device, Tensor}; use parquet::file::reader::SerializedFileReader; // NOTE: Waiting on https://github.com/rust-lang/mdBook/pull/1856 #[rustfmt::skip] #[tokio::test] async fn book_hub_1() { // A...
0
hf_public_repos/candle/candle-book
hf_public_repos/candle/candle-book/src/error_manage.md
# Error management You might have seen in the code base a lot of `.unwrap()` or `?`. If you're unfamiliar with Rust check out the [Rust book](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html) for more information. What's important to know though, is that if you want to know *where* a particu...
0
hf_public_repos/candle/candle-book
hf_public_repos/candle/candle-book/src/README.md
# Introduction {{#include ../../README.md:features}} This book will introduce step by step how to use `candle`.
0
hf_public_repos/candle/candle-book
hf_public_repos/candle/candle-book/src/chapter_1.md
# Chapter 1
0
hf_public_repos/candle/candle-book
hf_public_repos/candle/candle-book/src/simplified.rs
//! #A simplified example in Rust of training a neural network and then using it based on the Candle Framework by Hugging Face. //! Author: Evgeny Igumnov 2023 igumnovnsk@gmail.com //! This program implements a neural network to predict the winner of the second round of elections based on the results of the first round...
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/guide/cheatsheet.md
# Pytorch cheatsheet {{#include ../../../README.md:cheatsheet}}
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/guide/hello_world.md
# Hello world! We will now create the hello world of the ML world, building a model capable of solving MNIST dataset. Open `src/main.rs` and fill in this content: ```rust # extern crate candle_core; use candle_core::{Device, Result, Tensor}; struct Model { first: Tensor, second: Tensor, } impl Model { ...
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/guide/installation.md
# Installation **With Cuda support**: 1. First, make sure that Cuda is correctly installed. - `nvcc --version` should print information about your Cuda compiler driver. - `nvidia-smi --query-gpu=compute_cap --format=csv` should print your GPUs compute capability, e.g. something like: ```bash compute_cap 8.9 ``` You...
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/advanced/mkl.md
# Using MKL
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/cuda/porting.md
# Porting a custom kernel
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/cuda/README.md
# Advanced Cuda usage
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/cuda/writing.md
# Writing a custom kernel
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/training/simplified.md
# Simplified ## How its works This program implements a neural network to predict the winner of the second round of elections based on the results of the first round. Basic moments: 1. A multilayer perceptron with two hidden layers is used. The first hidden layer has 4 neurons, the second has 2 neurons. 2. The inpu...
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/training/serialization.md
# Serialization
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/training/training.md
# Training Training starts with data. We're going to use the huggingface hub and start with the Hello world dataset of machine learning, MNIST. Let's start with downloading `MNIST` from [huggingface](https://huggingface.co/datasets/mnist). This requires [`hf-hub`](https://github.com/huggingface/hf-hub). ```bash ca...
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/training/mnist.md
# MNIST So we now have downloaded the MNIST parquet files, let's put them in a simple struct. ```rust,ignore {{#include ../lib.rs:book_training_3}} ``` The parsing of the file and putting it into single tensors requires the dataset to fit the entire memory. It is quite rudimentary, but simple enough for a small data...
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/training/finetuning.md
# Fine-tuning
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/inference/inference.md
# Running a model In order to run an existing model, you will need to download and use existing weights. Most models are already available on https://huggingface.co/ in [`safetensors`](https://github.com/huggingface/safetensors) format. Let's get started by running an old model : `bert-base-uncased`.
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/inference/hub.md
# Using the hub Install the [`hf-hub`](https://github.com/huggingface/hf-hub) crate: ```bash cargo add hf-hub ``` Then let's start by downloading the [model file](https://huggingface.co/bert-base-uncased/tree/main). ```rust # extern crate candle_core; # extern crate hf_hub; use hf_hub::api::sync::Api; use candle_c...
0
hf_public_repos/candle/candle-book/src/inference
hf_public_repos/candle/candle-book/src/inference/cuda/porting.md
# Porting a custom kernel
0
hf_public_repos/candle/candle-book/src/inference
hf_public_repos/candle/candle-book/src/inference/cuda/README.md
# Advanced Cuda usage
0
hf_public_repos/candle/candle-book/src/inference
hf_public_repos/candle/candle-book/src/inference/cuda/writing.md
# Writing a custom kernel
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/apps/dekstop.md
# Creating a desktop Tauri app
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/apps/wasm.md
# Creating a WASM app
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/apps/README.md
# Creating apps
0
hf_public_repos/candle/candle-book/src
hf_public_repos/candle/candle-book/src/apps/rest.md
# Creating a REST api webserver
0
hf_public_repos/candle
hf_public_repos/candle/candle-wasm-tests/Cargo.toml
[package] name = "candle-wasm-tests" version.workspace = true edition.workspace = true description = "WASM tests for candle" keywords.workspace = true categories.workspace = true [dependencies] candle = { path = "../candle-core", version = "0.3.1", package = "candle-core" } rand = { workspace = true } getrandom = { ve...
0
hf_public_repos/candle
hf_public_repos/candle/candle-wasm-tests/README.md
Run the tests with: ```bash RUST_LOG=wasm_bindgen_test_runner wasm-pack test --chrome --headless ``` Or: ```bash wasm-pack test --chrome ``` If you get an "invalid session id" failure in headless mode, check that logs and it may well be that your ChromeDriver is not at the same version as your browser.
0
hf_public_repos/candle
hf_public_repos/candle/candle-wasm-tests/webdriver.json
{ "moz:firefoxOptions": { "prefs": { "media.navigator.streams.fake": true, "media.navigator.permission.disabled": true }, "args": [] }, "goog:chromeOptions": { "args": [ "--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream" ] } }
0
hf_public_repos/candle/candle-wasm-tests
hf_public_repos/candle/candle-wasm-tests/tests/quantized_tests.rs
use candle::{ quantized::{self, k_quants, GgmlDType, GgmlType}, test_utils::to_vec2_round, Device, Module, Result, Tensor, }; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn quantized_matmul_neg() -> Result<()> { let cpu = &Device::Cpu; let (m, k, n)...
0
hf_public_repos/candle/candle-wasm-tests
hf_public_repos/candle/candle-wasm-tests/src/lib.rs
pub fn add(left: usize, right: usize) -> usize { left + right } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let result = add(2, 2); assert_eq!(result, 4); } }
0
hf_public_repos/candle
hf_public_repos/candle/candle-metal-kernels/Cargo.toml
[package] name = "candle-metal-kernels" version = "0.3.1" edition = "2021" description = "Metal kernels for Candle" repository = "https://github.com/huggingface/candle" keywords = ["blas", "tensor", "machine-learning"] categories = ["science"] license = "MIT OR Apache-2.0" [dependencies] metal = { version = "0.27.1",...
0
hf_public_repos/candle
hf_public_repos/candle/candle-metal-kernels/README.md
# candle-metal-kernels This crate contains Metal kernels used from candle.
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/examples/affine.rs
use candle_metal_kernels::{call_affine, Kernels}; use metal::objc::rc::autoreleasepool; use metal::{Device, MTLResourceOptions}; use rand; use std::any::type_name; use std::time::Instant; fn main() { let device = Device::system_default().unwrap(); let kernels = Kernels::new(); let f32_1k = (0..1000).map(|...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/examples/cast.rs
use candle_metal_kernels::{call_cast_contiguous, Kernels}; use metal::objc::rc::autoreleasepool; use metal::{Device, MTLResourceOptions}; use rand; use std::any::type_name; use std::time::Instant; fn main() { let device = Device::system_default().unwrap(); let kernels = Kernels::new(); let f32_1k = (0..10...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/examples/binary.rs
use candle_metal_kernels::{binary, call_binary_contiguous, call_binary_strided, Kernels}; use half::{bf16, f16}; use metal::objc::rc::autoreleasepool; use metal::{Device, MTLResourceOptions}; use rand; use std::any::type_name; use std::time::Instant; fn main() { let device = Device::system_default().unwrap(); ...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/examples/unary.rs
use candle_metal_kernels::{call_unary_contiguous, call_unary_strided, unary, Kernels}; use half::{bf16, f16}; use metal::objc::rc::autoreleasepool; use metal::{Device, MTLResourceOptions}; use rand; use std::any::type_name; use std::time::Instant; fn main() { let device = Device::system_default().unwrap(); let...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/unary.metal
#include <metal_stdlib> METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (idx % dims[dim_idx]) * str...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/binary.metal
#include <metal_stdlib> METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (idx % dims[dim_idx]) * str...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/reduce.metal
#include <metal_stdlib> using namespace metal; METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (idx...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/lib.rs
use metal::{ Buffer, CommandBufferRef, CompileOptions, ComputeCommandEncoderRef, ComputePipelineDescriptor, ComputePipelineState, Device, Function, Library, MTLSize, }; use std::collections::HashMap; use std::ffi::c_void; use std::sync::RwLock; const AFFINE: &str = include_str!("affine.metal"); const INDEXING:...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/indexing.metal
#include <metal_stdlib> using namespace metal; # define INDEX_OP(NAME, INDEX_TYPENAME, TYPENAME) \ kernel void NAME( \ constant size_t &dst_size, \ constant size_t &left_size, \ constant size_t &src_dim_size, \ constant size_t &right_size, \ constant size_t &ids_size, \ const device TYPENAME *i...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/ternary.metal
#include <metal_stdlib> # using namespace metal; METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (i...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/tests.rs
use super::*; use half::f16; use metal::{CompileOptions, Device, MTLResourceOptions, MTLSize, NSUInteger}; fn new_buffer<T>(device: &Device, data: &[T]) -> Buffer { let options = MTLResourceOptions::StorageModeManaged; let ptr = data.as_ptr() as *const core::ffi::c_void; let size = (data.len() * std::mem::...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/affine.metal
#include <metal_stdlib> METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (idx % dims[dim_idx]) * str...
0
hf_public_repos/candle/candle-metal-kernels
hf_public_repos/candle/candle-metal-kernels/src/cast.metal
#include <metal_stdlib> METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (idx % dims[dim_idx]) * str...
0
hf_public_repos/candle
hf_public_repos/candle/candle-nn/Cargo.toml
[package] name = "candle-nn" version.workspace = true edition.workspace = true description.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true license.workspace = true readme = "README.md" [dependencies] accelerate-src = { workspace = true, optional = true } candle = { pa...
0
hf_public_repos/candle
hf_public_repos/candle/candle-nn/README.md
# candle-nn
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/group_norm.rs
/* Equivalent PyTorch code. import torch from torch.nn.functional import group_norm t = torch.tensor( [[[-0.3034, 0.2726, -0.9659], [-1.1845, -1.3236, 0.0172], [ 1.9507, 1.2554, -0.8625], [ 1.0682, 0.3604, 0.3985], [-0.4957, -0.4461, -0.9721], [ 1.5157, -0....
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/rnn.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::{test_utils::to_vec2_round, DType, Device, Result, Tensor}; use candle_nn::RNN; /* The following test can be verified against PyTorch using the following snippet. import torch from torch import...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/optim.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::test_utils::{to_vec0_round, to_vec2_round}; use anyhow::Result; use candle::{Device, Tensor, Var}; use candle_nn::{AdamW, Linear, Module, Optimizer, ParamsAdamW, SGD}; #[test] fn sgd_optim() -...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/layer_norm.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use candle::{test_utils, Device, Tensor}; use candle_nn::{LayerNorm, Module}; #[test] fn layer_norm() -> Result<()> { let device = &Device::Cpu; let w = Tensor::new(&[3f32], dev...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/batch_norm.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use candle::{test_utils, DType, Device, Tensor}; use candle_nn::BatchNorm; /* The test below has been generated using the following PyTorch code: import torch torch.manual_seed(19551105...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/loss.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::test_utils::to_vec0_round; use candle::{Device, Result, Tensor}; /* Equivalent python code: import torch import torch.nn.functional as F input = torch.tensor([ [ 1.1050, 0.3013, -1.5394, -...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/tests/ops.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::{test_utils::to_vec3_round, Device, Result, Tensor}; #[test] fn softmax() -> Result<()> { let device = &Device::Cpu; let data = &[[[3f32, 1., 4.], [1., 5., 9.]], [[2., 1., 7.], [8., 2.,...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/examples/cpu_benchmarks.rs
/// This example contains some simple benchmarks so that it's easy to run them in perf etc. #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::quantized::GgmlType; use candle::{CpuStorage, Device, Layout, Module, Result, Shape, Tensor, D}; use c...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/examples/basic_optimizer.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::{DType, Device, Result, Tensor}; use candle_nn::{linear, AdamW, Linear, Module, Optimizer, ParamsAdamW, VarBuilder, VarMap}; fn gen_data() -> Result<(Tensor, Tensor)> { // Generate some sam...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/group_norm.rs
//! Group Normalization. //! //! This layer applies Group Normalization over a mini-batch of inputs. use candle::{DType, Result, Tensor}; // This group norm version handles both weight and bias so removes the mean. #[derive(Clone, Debug)] pub struct GroupNorm { weight: Tensor, bias: Tensor, eps: f64, n...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/linear.rs
//! Linear layer //! //! This layer applies a linear transformation to the incoming data, `y = x@w.t() + b`. //! The bias is optional. The `forward` method can be used to apply the layer, it supports input //! with a batch dimension (so of shape `(b_sz, in_c)`) or without (of shape `(in_c,)`), the //! output has shape ...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/embedding.rs
//! Embedding Layer. use candle::{Result, Tensor}; #[derive(Clone, Debug)] pub struct Embedding { embeddings: Tensor, hidden_size: usize, } impl Embedding { pub fn new(embeddings: Tensor, hidden_size: usize) -> Self { Self { embeddings, hidden_size, } } pub...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/lib.rs
pub mod activation; pub mod batch_norm; pub mod conv; pub mod embedding; pub mod func; pub mod group_norm; pub mod init; pub mod layer_norm; pub mod linear; pub mod loss; pub mod ops; pub mod optim; pub mod rnn; pub mod sequential; pub mod var_builder; pub mod var_map; pub use activation::{prelu, Activation, PReLU}; p...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/rnn.rs
//! Recurrent Neural Networks use candle::{DType, Device, IndexOp, Result, Tensor}; /// Trait for Recurrent Neural Networks. #[allow(clippy::upper_case_acronyms)] pub trait RNN { type State: Clone; /// A zero state from which the recurrent network is usually initialized. fn zero_state(&self, batch_dim: us...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/optim.rs
//! Various optimization algorithms. use candle::{Result, Tensor, Var}; /// The interface optimizers should implement. pub trait Optimizer: Sized { type Config: Sized; fn new(vars: Vec<Var>, config: Self::Config) -> Result<Self>; fn step(&mut self, grads: &candle::backprop::GradStore) -> Result<()>; ...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/layer_norm.rs
//! Layer Normalization. //! //! This layer applies Layer Normalization over a mini-batch of inputs as described in [`Layer //! Normalization`]. The input is expected to have three dimensions: a batch dimension, a length, //! and a hidden size, the normalization is applied over the last dimension. //! //! # Example //!...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/func.rs
//! Layers defined by closures. use candle::{Result, Tensor}; use std::sync::Arc; /// A layer defined by a simple closure. #[derive(Clone)] pub struct Func<'a> { #[allow(clippy::type_complexity)] f: Arc<dyn 'a + Fn(&Tensor) -> Result<Tensor> + Send + Sync>, } impl<'a> std::fmt::Debug for Func<'a> { fn fmt...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/conv.rs
//! Convolution Layers. use crate::BatchNorm; use candle::{Result, Tensor}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Conv1dConfig { pub padding: usize, pub stride: usize, pub dilation: usize, pub groups: usize, } impl Default for Conv1dConfig { fn default() -> Self { Self { ...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/batch_norm.rs
//! Batch Normalization. //! //! This layer applies Batch Normalization over a mini-batch of inputs as described in [`Batch //! Normalization`]. The input is expected to have at least three dimensions. //! //! Note that this implementation is for inference only, there is no possibility to track the //! running stats. /...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/var_builder.rs
//! A `VarBuilder` is used to retrieve variables used by a model. These variables can either come //! from a pre-trained checkpoint, e.g. using `VarBuilder::from_mmaped_safetensors`, or initialized //! for training, e.g. using `VarBuilder::from_varmap`. use crate::VarMap; use candle::{safetensors::Load, DType, Device, ...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/init.rs
//! Variable initialization. // This is based on: // https://github.com/pytorch/pytorch/blob/07107919297db3f8ab37f11c12666b6d6d5f692e/torch/nn/init.py# use candle::{DType, Device, Result, Shape, Tensor, Var}; /// Number of features as input or output of a layer. /// In Kaiming initialization, choosing `FanIn` preserve...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/var_map.rs
use candle::{DType, Device, Result, Shape, Tensor, Var}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; /// A `VarMap` is a store that holds named variables. Variables can be retrieved from the stores /// and new variables can be added by providing some initialization config in case they are /// missing. ...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/loss.rs
use candle::{Result, Tensor}; /// The negative log likelihood loss. /// /// Arguments /// /// * [inp]: The input tensor of dimensions `N, C` where `N` is the batch size and `C` the number /// of categories. This is expected to contain log probabilities. /// * [target]: The ground truth labels as a tensor of u...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/ops.rs
use candle::{CpuStorage, Layout, Result, Shape, Tensor}; use rayon::prelude::*; /// Applies the softmax function to the input tensor, rescaling the element so that elements on /// a slice of fixed index on dimension `dim` are between 0 and 1 and sum to 1. /// /// ```rust /// use candle::{Tensor, Device, test_utils::to...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/sequential.rs
//! A sequential layer used to chain multiple layers and closures. use candle::{Module, Result, Tensor}; /// A sequential layer combining multiple other layers. pub struct Sequential { layers: Vec<Box<dyn Module>>, } /// Creates a new empty sequential layer. pub fn seq() -> Sequential { Sequential { layers: v...
0
hf_public_repos/candle/candle-nn
hf_public_repos/candle/candle-nn/src/activation.rs
use candle::{Result, Tensor}; use serde::Deserialize; #[derive(Debug, Clone, Copy, PartialEq, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Activation { #[default] Gelu, NewGelu, Relu, Relu2, Relu6, Silu, Sigmoid, HardSigmoid, Swiglu, Swish, HardSwis...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/Cargo.toml
[package] name = "candle-pyo3" version.workspace = true edition.workspace = true description.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true license.workspace = true readme = "README.md" [lib] name = "candle" crate-type = ["cdylib"] [dependencies] accelerate-src = { ...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/e5.py
from candle.utils import load_safetensors, save_gguf, load_gguf from candle.models.bert import BertModel, Config import json from candle import Tensor from tqdm import tqdm from dataclasses import fields import os import time from huggingface_hub import hf_hub_download from transformers import BertTokenizer, AutoModel...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/quant-llama.py
# This example shows how the candle Python api can be used to replicate llama.cpp. import sys from typing import Dict, Tuple, Any import candle from candle.models.llama import QuantizedLlama from candle import utils MAX_SEQ_LEN = 4096 def gguf_rename(tensor_name: str): if tensor_name == "token_embd.weight": ...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/pyproject.toml
[project] name = 'candle-nn' requires-python = '>=3.7' authors = [ {name = 'The Candle Team'}, ] dynamic = [ 'description', 'license', 'readme', ] [project.urls] Homepage = 'https://github.com/huggingface/candle' Source = 'https://github.com/huggingface/candle' [build-system] requires = ["maturin>=1....
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/build.rs
fn main() { pyo3_build_config::add_extension_module_link_args(); }
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/test.py
import candle print(f"mkl: {candle.utils.has_mkl()}") print(f"accelerate: {candle.utils.has_accelerate()}") print(f"num-threads: {candle.utils.get_num_threads()}") print(f"cuda: {candle.utils.cuda_is_available()}") t = candle.Tensor(42.0) print(t) print(t.shape, t.rank, t.device) print(t + t) t = can...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/README.md
## Installation From the `candle-pyo3` directory, enable a virtual env where you will want the candle package to be installed then run. ```bash maturin develop -r python test.py ``` ## Generating Stub Files for Type Hinting For type hinting support, the `candle-pyo3` package requires `*.pyi` files. You can automa...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/test_pytorch.py
import candle import torch # convert from candle tensor to torch tensor t = candle.randn((3, 512, 512)) torch_tensor = t.to_torch() print(torch_tensor) print(type(torch_tensor)) # convert from torch tensor to candle tensor t = torch.randn((3, 512, 512)) candle_tensor = candle.Tensor(t) print(candle_tensor) print(type...
0
hf_public_repos/candle
hf_public_repos/candle/candle-pyo3/stub.py
# See: https://raw.githubusercontent.com/huggingface/tokenizers/main/bindings/python/stub.py import argparse import inspect import os from typing import Optional import black from pathlib import Path import re INDENT = " " * 4 GENERATED_COMMENT = "# Generated content DO NOT EDIT\n" TYPING = """from typing import Any,...
0
hf_public_repos/candle/candle-pyo3/py_src
hf_public_repos/candle/candle-pyo3/py_src/candle/__init__.pyi
# Generated content DO NOT EDIT from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from os import PathLike from candle.typing import _ArrayLike, Device, Scalar, Index, Shape class bf16(DType): pass @staticmethod def cat(tensors: List[Tensor], dim: int) -> Tensor: """ Concatenat...
0
hf_public_repos/candle/candle-pyo3/py_src
hf_public_repos/candle/candle-pyo3/py_src/candle/__init__.py
import logging try: from .candle import * except ImportError as e: # If we are in development mode, or we did not bundle the DLLs, we try to locate them here # PyO3 wont give us any infomration about what DLLs are missing, so we can only try to load the DLLs and re-import the module logging.warning("DL...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/nn/linear.py
import math from typing import Any import candle from candle import Tensor from .module import Module # See https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/linear.py class Identity(Module): r"""A placeholder identity operator that is argument-insensitive. Args: args: any argument (unu...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/nn/__init__.py
from .module import Module from .container import Sequential, ModuleList, ModuleDict from .sparse import Embedding from .normalization import LayerNorm from .linear import Linear
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/nn/container.py
# see https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/container.py from .module import Module from typing import ( Any, Dict, Iterable, Iterator, Mapping, Optional, overload, Tuple, TypeVar, Union, ) from collections import OrderedDict, abc as container_abcs import ...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/nn/sparse.py
from .module import Module from typing import Optional, Tuple, Any from candle import Tensor import candle class Embedding(Module): """A simple lookup table that stores embeddings of a fixed dictionary and size. This module is often used to store word embeddings and retrieve them using indices. The input...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/nn/module.py
from candle import Tensor, QTensor, DType from typing import ( Dict, Tuple, Any, Optional, Union, Iterator, Set, overload, Mapping, TypeVar, List, ) from collections import OrderedDict, namedtuple TensorLike = Union[Tensor, QTensor] T = TypeVar("T", bound="Module") class _...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/nn/normalization.py
import candle from candle import Tensor from .module import Module from typing import Union, List, Tuple, Optional, Any _shape_t = Union[int, List[int]] import numbers class LayerNorm(Module): r"""Applies Layer Normalization over a mini-batch of inputs as described in the paper `Layer Normalization <https://...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/onnx/__init__.pyi
# Generated content DO NOT EDIT from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from os import PathLike from candle.typing import _ArrayLike, Device, Scalar, Index, Shape from candle import Tensor, DType, QTensor class ONNXModel: """ A wrapper around an ONNX model. """ d...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/onnx/__init__.py
# Generated content DO NOT EDIT from .. import onnx ONNXModel = onnx.ONNXModel ONNXTensorDescription = onnx.ONNXTensorDescription
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/utils/__init__.pyi
# Generated content DO NOT EDIT from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from os import PathLike from candle.typing import _ArrayLike, Device, Scalar, Index, Shape from candle import Tensor, DType, QTensor @staticmethod def cuda_is_available() -> bool: """ Returns true if ...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/utils/__init__.py
# Generated content DO NOT EDIT from .. import utils cuda_is_available = utils.cuda_is_available get_num_threads = utils.get_num_threads has_accelerate = utils.has_accelerate has_mkl = utils.has_mkl load_ggml = utils.load_ggml load_gguf = utils.load_gguf load_safetensors = utils.load_safetensors save_gguf = utils.save...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/models/llama.py
import candle from typing import Dict, Tuple, Any from candle import Tensor, QTensor, utils, nn from candle.nn import Module, ModuleList def masked_fill(on_false: Tensor, mask: Tensor, on_true: Tensor): shape = mask.shape on_true = candle.tensor(on_true).broadcast_as(shape) return mask.where_cond(on_true,...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/models/bert.py
from dataclasses import dataclass from typing import Optional from candle.nn import Module, Embedding, LayerNorm, Linear, ModuleList from candle import Tensor import candle import candle.functional as F from typing import Tuple, Optional @dataclass class Config: vocab_size: int = 30522 hidden_size: int = 768 ...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/typing/__init__.py
from typing import TypeVar, Union, Sequence _T = TypeVar("_T") _ArrayLike = Union[ _T, Sequence[_T], Sequence[Sequence[_T]], Sequence[Sequence[Sequence[_T]]], Sequence[Sequence[Sequence[Sequence[_T]]]], ] CPU: str = "cpu" CUDA: str = "cuda" Device = TypeVar("Device", CPU, CUDA) Scalar = Union[i...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/testing/__init__.py
import candle from candle import Tensor _UNSIGNED_DTYPES = set([str(candle.u8), str(candle.u32)]) def _assert_tensor_metadata( actual: Tensor, expected: Tensor, check_device: bool = True, check_dtype: bool = True, check_layout: bool = True, check_stride: bool = False, ): if check_device:...
0
hf_public_repos/candle/candle-pyo3/py_src/candle
hf_public_repos/candle/candle-pyo3/py_src/candle/functional/__init__.pyi
# Generated content DO NOT EDIT from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from os import PathLike from candle.typing import _ArrayLike, Device, Scalar, Index, Shape from candle import Tensor, DType, QTensor @staticmethod def avg_pool2d(tensor: Tensor, ksize: int, stride: int = 1) -...
0