repo_id
stringlengths
15
89
file_path
stringlengths
27
180
content
stringlengths
1
2.23M
__index_level_0__
int64
0
0
hf_public_repos
hf_public_repos/candle/LICENSE-MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the ...
0
hf_public_repos
hf_public_repos/candle/.pre-commit-config.yaml
repos: - repo: https://github.com/Narsil/pre-commit-rust rev: 2eed6366172ef2a5186e8785ec0e67243d7d73d0 hooks: - id: fmt name: "Rust (fmt)" - id: clippy name: "Rust (clippy)" args: [ "--tests", "--examples", "--", "-D...
0
hf_public_repos
hf_public_repos/candle/test.onnx
 backend-test:J  xytest"Relu SingleReluZ x   b y   B
0
hf_public_repos
hf_public_repos/candle/README.md
# candle [![discord server](https://dcbadge.vercel.app/api/server/hugging-face-879548962464493619)](https://discord.gg/hugging-face-879548962464493619) [![Latest version](https://img.shields.io/crates/v/candle-core.svg)](https://crates.io/crates/candle-core) [![Documentation](https://docs.rs/candle-core/badge.svg)](htt...
0
hf_public_repos
hf_public_repos/candle/LICENSE-APACHE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
0
hf_public_repos
hf_public_repos/candle/CHANGELOG.md
# Changelog This documents the main changes to the `candle` crate. ## v0.3.1 - Unreleased ### Added ### Modified ## v0.3.0 - 2023-10-01 ### Added - Added the Mistral 7b v0.1 model [983](https://github.com/huggingface/candle/pull/983). - Quantized version of the Mistral model [1009](https://github.com/huggingf...
0
hf_public_repos
hf_public_repos/candle/Makefile
.PHONY: clean-ptx clean test clean-ptx: find target -name "*.ptx" -type f -delete echo "" > candle-kernels/src/lib.rs touch candle-kernels/build.rs touch candle-examples/build.rs touch candle-flash-attn/build.rs clean: cargo clean test: cargo test all: test
0
hf_public_repos
hf_public_repos/candle/Cargo.toml
[workspace] members = [ "candle-core", "candle-datasets", "candle-examples", "candle-book", "candle-nn", "candle-pyo3", "candle-transformers", "candle-wasm-examples/*", "candle-wasm-tests", ] exclude = [ "candle-flash-attn", "candle-kernels", "candle-metal-kernels", "cand...
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/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/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
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/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/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/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/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 information about what DLLs are missing, so we can only try to load # the DLLs and re-import the module logging.warni...
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/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/__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/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/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/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/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/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/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/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/functional/__init__.py
# Generated content DO NOT EDIT from .. import functional avg_pool2d = functional.avg_pool2d gelu = functional.gelu max_pool2d = functional.max_pool2d relu = functional.relu silu = functional.silu softmax = functional.softmax tanh = functional.tanh
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
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/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/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/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/tests
hf_public_repos/candle/candle-pyo3/tests/bindings/test_testing.py
import candle from candle import Tensor from candle.testing import assert_equal, assert_almost_equal import pytest @pytest.mark.parametrize("dtype", [candle.f32, candle.f64, candle.f16, candle.u32, candle.u8, candle.i64]) def test_assert_equal_asserts_correctly(dtype: candle.DType): a = Tensor([1, 2, 3]).to(dtype...
0
hf_public_repos/candle/candle-pyo3/tests
hf_public_repos/candle/candle-pyo3/tests/bindings/test_linear.py
import candle from candle import Tensor from candle.nn import Linear def test_linear_layer_can_be_constructed(): linear = Linear(10, 10) assert linear is not None def test_linear_layer_can_forward_a_singular_input(): linear = Linear(384, 1536) input_tensor = candle.randn((8, 384)) output = linea...
0
hf_public_repos/candle/candle-pyo3/tests
hf_public_repos/candle/candle-pyo3/tests/bindings/test_module.py
import candle from candle import Tensor, QTensor from candle.nn import Module, Linear from candle.utils import cuda_is_available import pytest def test_module_can_be_constructed(): class A(Module): pass a = A() assert a is not None assert len(list(a.buffers())) == 0 def test_module_registe...
0
hf_public_repos/candle/candle-pyo3/tests
hf_public_repos/candle/candle-pyo3/tests/native/test_shape.py
from candle import Tensor from candle import rand import pytest def test_absolute_shapes_are_valid(): a = rand((10, 20)) assert a.shape == (10, 20) b = rand(10, 20) assert b.shape == (10, 20) pytest.raises(OverflowError, lambda: rand((10, 20, -1))) pytest.raises(OverflowError, lambda: rand(-1...
0
hf_public_repos/candle/candle-pyo3/tests
hf_public_repos/candle/candle-pyo3/tests/native/test_tensor.py
import candle from candle import Tensor from candle.utils import cuda_is_available from candle.testing import assert_equal import pytest def test_tensor_can_be_constructed(): t = Tensor(42.0) assert t.values() == 42.0 def test_tensor_can_be_constructed_from_list(): t = Tensor([3.0, 1, 4, 1, 5, 9, 2, 6])...
0
hf_public_repos/candle/candle-pyo3/tests
hf_public_repos/candle/candle-pyo3/tests/native/test_utils.py
import candle from candle import Tensor, QTensor from candle.utils import load_safetensors, save_gguf, load_gguf, save_safetensors from pathlib import Path TEST_DIR = Path(__file__).parent.parent / "_workdir" TEST_DIR.mkdir(exist_ok=True) def test_can_roundtrip_safetensors(): tensors = { "a": candle.rand...
0
hf_public_repos/candle/candle-pyo3
hf_public_repos/candle/candle-pyo3/_additional_typing/README.md
This python module contains external typehinting for certain `candle` classes. This is only necessary for `magic` methodes e.g. `__add__` as their text signature cant be set via pyo3. The classes in this module will be parsed by the `stub.py` script and interleafed with the signatures of the actual pyo3 `candle.candle...
0
hf_public_repos/candle/candle-pyo3
hf_public_repos/candle/candle-pyo3/_additional_typing/__init__.py
from typing import Union, Sequence class Tensor: """ This contains the type hints for the magic methodes of the `candle.Tensor` class. """ def __add__(self, rhs: Union["Tensor", "Scalar"]) -> "Tensor": """ Add a scalar to a tensor or two tensors together. """ pass ...
0
hf_public_repos/candle/candle-pyo3
hf_public_repos/candle/candle-pyo3/src/lib.rs
#![allow(clippy::redundant_closure_call)] use pyo3::exceptions::{PyTypeError, PyValueError}; use pyo3::prelude::*; use pyo3::pyclass::CompareOp; use pyo3::types::{IntoPyDict, PyDict, PyTuple}; use pyo3::ToPyObject; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::os::raw::c_long; u...
0
hf_public_repos/candle/candle-pyo3
hf_public_repos/candle/candle-pyo3/src/shape.rs
use ::candle::Tensor; use pyo3::prelude::*; #[derive(Clone, Debug)] /// Represents an absolute shape e.g. (1, 2, 3) pub struct PyShape(Vec<usize>); impl<'source> pyo3::FromPyObject<'source> for PyShape { fn extract(ob: &'source PyAny) -> PyResult<Self> { if ob.is_none() { return Err(PyErr::new...
0
hf_public_repos/candle/candle-pyo3
hf_public_repos/candle/candle-pyo3/src/utils.rs
use pyo3::exceptions::PyValueError; use pyo3::prelude::*; pub fn wrap_err(err: ::candle::Error) -> PyErr { PyErr::new::<PyValueError, _>(format!("{err:?}")) }
0
hf_public_repos/candle/candle-pyo3
hf_public_repos/candle/candle-pyo3/src/onnx.rs
use std::collections::HashMap; use crate::utils::wrap_err; use crate::{PyDType, PyTensor}; use candle_onnx::eval::{dtype, get_tensor, simple_eval}; use candle_onnx::onnx::tensor_proto::DataType; use candle_onnx::onnx::tensor_shape_proto::dimension::Value; use candle_onnx::onnx::type_proto::{Tensor as ONNXTensor, Value...
0
hf_public_repos/candle
hf_public_repos/candle/candle-core/README.md
# candle Minimalist ML framework for Rust
0
hf_public_repos/candle
hf_public_repos/candle/candle-core/Cargo.toml
[package] name = "candle-core" 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 } byteorder =...
0
hf_public_repos/candle
hf_public_repos/candle/candle-core/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/benches/bench_main.rs
mod benchmarks; use criterion::criterion_main; criterion_main!( benchmarks::matmul::benches, benchmarks::affine::benches, benchmarks::where_cond::benches );
0
hf_public_repos/candle/candle-core/benches
hf_public_repos/candle/candle-core/benches/benchmarks/mod.rs
pub(crate) mod affine; pub(crate) mod matmul; pub(crate) mod where_cond; use candle_core::{Device, Result}; pub(crate) trait BenchDevice { fn sync(&self) -> Result<()>; fn bench_name<S: Into<String>>(&self, name: S) -> String; } impl BenchDevice for Device { fn sync(&self) -> Result<()> { match ...
0
hf_public_repos/candle/candle-core/benches
hf_public_repos/candle/candle-core/benches/benchmarks/affine.rs
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle_core::{DType, Device, Tensor}; use criterion::{black_box, criterion_group, Criterion, Throughput}; use std::time::Instant; fn run(a: &Tensor) { a.affine(12.34, 56.78).unwrap(); } fn run_affine_benchmark(c: &mut Criterion, device: &Device, dtype:...
0
hf_public_repos/candle/candle-core/benches
hf_public_repos/candle/candle-core/benches/benchmarks/matmul.rs
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle_core::{DType, Device, Tensor}; use criterion::{black_box, criterion_group, Criterion, Throughput}; use std::time::Instant; fn run(a: &Tensor, b: &Tensor) { a.matmul(&b.t().unwrap()).unwrap(); } fn run_bench(c: &mut Criterion, device: &Device) { ...
0
hf_public_repos/candle/candle-core/benches
hf_public_repos/candle/candle-core/benches/benchmarks/where_cond.rs
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle_core::{DType, Device, Tensor}; use criterion::{black_box, criterion_group, Criterion, Throughput}; use std::time::Instant; fn run(a: &Tensor, b: &Tensor, c: &Tensor) { a.where_cond(b, c).unwrap(); } const fn create_cond_arr<const N: usize>() -> ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/examples/cuda_sum_benchmark.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use std::str::FromStr; use anyhow::Result; use candle_core::{Device, Tensor}; fn cos_sin(n: usize, device: &Device) -> Result<Tensor> { let thetas: Vec<_> = (0..n).map(|i| (i as f32 / n as f32)).colle...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/examples/tensor-tools.rs
use candle_core::quantized::{gguf_file, GgmlDType, QTensor}; use candle_core::{Device, Result}; use clap::{Parser, Subcommand, ValueEnum}; use rayon::prelude::*; #[derive(ValueEnum, Debug, Clone)] enum QuantizationMode { /// The default quantization includes all 2d tensors, except the output tensor which always ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/examples/basics.rs
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use candle_core::{Device, Tensor}; fn main() -> Result<()> { let a = Tensor::new(&[[0.0f32, 1.0, 2.0], [3.0, 4.0, 5.0]], &Device::Cpu)?; let b = Tensor::new(&[[88.0f32, 99.0]], ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/examples/cuda_basics.rs
#[cfg(feature = "accelerate")] extern crate accelerate_src; #[cfg(feature = "mkl")] extern crate intel_mkl_src; use anyhow::Result; use candle_core::{Device, Tensor}; fn main() -> Result<()> { let device = Device::new_cuda(0)?; let in_t = Tensor::rand(-1f32, 1f32, (1, 3, 12, 7), &device)?; let k_t = Tens...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/display_tests.rs
use anyhow::Result; use candle_core::{DType, Device::Cpu, Tensor}; #[test] fn display_scalar() -> Result<()> { let t = Tensor::new(1234u32, &Cpu)?; let s = format!("{t}"); assert_eq!(&s, "[1234]\nTensor[[], u32]"); let t = t.to_dtype(DType::F32)?.neg()?; let s = format!("{}", (&t / 10.0)?); ass...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/layout_tests.rs
use candle::{test_device, Device, IndexOp, Result, Tensor}; use candle_core as candle; fn contiguous(device: &Device) -> Result<()> { let tensor = Tensor::arange(0u32, 24u32, device)?.reshape((2, 3, 4))?; assert_eq!( tensor.to_vec3::<u32>()?, &[ [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 1...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/grad_tests.rs
use anyhow::{Context, Result}; use candle_core::{test_device, test_utils, Device, Shape, Tensor, Var}; fn simple_grad(device: &Device) -> Result<()> { let x = Var::new(&[3f32, 1., 4.], device)?; let x = x.as_tensor(); let y = (((x * x)? + x * 5f64)? + 4f64)?; let grads = y.backward()?; let grad_x =...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/tensor_tests.rs
use candle_core::{test_device, test_utils, DType, Device, IndexOp, Result, Tensor, D}; fn zeros(device: &Device) -> Result<()> { let tensor = Tensor::zeros((5, 2), DType::F32, device)?; let (dim1, dim2) = tensor.dims2()?; assert_eq!(dim1, 5); assert_eq!(dim2, 2); Ok(()) } fn ones(device: &Device) ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/indexing_tests.rs
use anyhow::Result; use candle_core::{Device, IndexOp, Tensor}; #[test] fn integer_index() -> Result<()> { let dev = Device::Cpu; let tensor = Tensor::arange(0u32, 2 * 3, &dev)?.reshape((2, 3))?; let result = tensor.i(1)?; assert_eq!(result.dims(), &[3]); assert_eq!(result.to_vec1::<u32>()?, &[3, ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/custom_op_tests.rs
use candle_core::backend::BackendStorage; use candle_core::cpu_backend; use candle_core::test_utils::to_vec1_round; use candle_core::{CpuStorage, CustomOp1, DType, Device, Error, Layout, Result, Shape, Tensor}; fn fwd<T: num_traits::Float>(v: T, alpha: f64) -> T { if v.is_sign_positive() { v } else { ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/serialization_tests.rs
use candle_core::{DType, Result, Tensor}; #[test] fn npy() -> Result<()> { let npy = Tensor::read_npy("tests/test.npy")?; assert_eq!( npy.to_dtype(DType::U8)?.to_vec1::<u8>()?, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ); Ok(()) } #[test] fn npz() -> Result<()> { let npz = Tensor::read_npz("t...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/quantized_tests.rs
use candle_core::{ bail, quantized::{self, GgmlDType}, test_device, test_utils::to_vec2_round, Device, Module, Result, Tensor, }; use quantized::{k_quants, GgmlType}; use rand::prelude::*; const GGML_TEST_SIZE: usize = 32 * 128; const GGML_MAX_QUANTIZATION_TOTAL_ERROR: f32 = 0.002; const GGML_MAX_...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/pool_tests.rs
use candle_core::{test_device, test_utils, Device, IndexOp, Result, Tensor}; // https://github.com/huggingface/candle/issues/364 fn avg_pool2d(dev: &Device) -> Result<()> { let data: Vec<f32> = vec![ 1., 1., 1., 1., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., ]; let t = Tensor::from_vec(data, (...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/npy.py
import numpy as np x = np.arange(10) # Write a npy file. np.save("test.npy", x) # Write multiple values to a npz file. values = { "x": x, "x_plus_one": x + 1 } np.savez("test.npz", **values)
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/tests/conv_tests.rs
use anyhow::Result; use candle_core::{test_device, test_utils, Device, IndexOp, Tensor}; /* This test is based on the following script. import torch torch.manual_seed(4242) t = torch.randn((1, 4, 5)) w = torch.randn((2, 4, 3)) print(t.flatten()) print(w.flatten()) res = torch.nn.functional.conv1d(t, w) print(res.flat...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/layout.rs
use crate::{Error, Result, Shape}; #[derive(Debug, PartialEq, Eq, Clone)] pub struct Layout { shape: Shape, // The strides are given in number of elements and not in bytes. stride: Vec<usize>, start_offset: usize, } impl Layout { pub fn new(shape: Shape, stride: Vec<usize>, start_offset: usize) ->...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/device.rs
use crate::backend::BackendDevice; use crate::cpu_backend::CpuDevice; use crate::{CpuStorage, DType, Result, Shape, Storage, WithDType}; /// A `DeviceLocation` represents a physical device whereas multiple `Device` /// can live on the same location (typically for cuda devices). #[derive(Debug, Copy, Clone, PartialEq, ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/dtype.rs
//! Types for elements that can be stored and manipulated using tensors. #![allow(clippy::redundant_closure_call)] use crate::backend::BackendStorage; use crate::{CpuStorage, Error, Result}; /// The different types of elements allowed in tensors. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum DType { ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/cudnn.rs
use crate::WithDType; use cudarc; use cudarc::cudnn::safe::{Conv2dForward, Cudnn}; use cudarc::driver::{CudaSlice, CudaView, DeviceRepr, ValidAsZeroBits}; use std::cell::RefCell; use std::collections::HashMap; use std::sync::Arc; // The cudnn handles are stored per thread here rather than on the CudaDevice as they are...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/storage.rs
use crate::backend::BackendStorage; use crate::op::{self, CmpOp, CustomOp1, CustomOp2, CustomOp3, ReduceOp}; use crate::{CpuStorage, CudaStorage, DType, Device, Error, Layout, MetalStorage, Result, Shape}; // We do not want to implement Clone on Storage as cloning may fail because of // out of memory. Instead try_clon...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/conv.rs
use crate::{op::BackpropOp, op::Op, Error, Result, Tensor}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParamsConv1D { pub(crate) b_size: usize, // Maybe we should have a version without l_in as this bit depends on the input and not only on // the weights. pub(crate) l_in: usize, pub(crate) c...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/scalar.rs
use crate::{Result, Tensor, WithDType}; pub enum TensorScalar { Tensor(Tensor), Scalar(Tensor), } pub trait TensorOrScalar { fn to_tensor_scalar(self) -> Result<TensorScalar>; } impl TensorOrScalar for &Tensor { fn to_tensor_scalar(self) -> Result<TensorScalar> { Ok(TensorScalar::Tensor(self....
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/lib.rs
//! ML framework for Rust //! //! ```rust //! use candle_core::{Tensor, DType, Device}; //! # use candle_core::Error; //! # fn main() -> Result<(), Error>{ //! //! let a = Tensor::arange(0f32, 6f32, &Device::Cpu)?.reshape((2, 3))?; //! let b = Tensor::arange(0f32, 12f32, &Device::Cpu)?.reshape((3, 4))?; //! //! let c =...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/backprop.rs
use crate::op::{BinaryOp, Op, ReduceOp, UnaryOp}; use crate::{Error, Result, Tensor, TensorId}; use std::collections::HashMap; // arg has been reduced to node via reduce_dims, expand it back to arg. // This has to handle keepdims. fn broadcast_back(arg: &Tensor, node: &Tensor, reduced_dims: &[usize]) -> Result<Tensor>...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/strided_index.rs
use crate::Layout; /// An iterator over offset position for items of an N-dimensional arrays stored in a /// flat buffer using some potential strides. #[derive(Debug)] pub struct StridedIndex<'a> { next_storage_index: Option<usize>, multi_index: Vec<usize>, dims: &'a [usize], stride: &'a [usize], } im...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/dummy_cuda_backend.rs
#![allow(dead_code)] use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{CpuStorage, DType, Error, Layout, Result, Shape}; #[derive(Debug, Clone)] pub struct CudaDevice; #[derive(Debug)] pub struct CudaStorage; macro_rules! fail { () => { unimplemented!("cuda support has not been enabled, ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/dummy_metal_backend.rs
#![allow(dead_code)] use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{CpuStorage, DType, Error, Layout, Result, Shape}; #[derive(Debug, Clone)] pub struct MetalDevice; #[derive(Debug)] pub struct MetalStorage; #[derive(thiserror::Error, Debug)] pub enum MetalError { #[error("{0}")] Message(...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/mkl.rs
#![allow(dead_code)] use libc::{c_char, c_double, c_float, c_int}; mod ffi { use super::*; extern "C" { pub fn vsTanh(n: c_int, a: *const c_float, y: *mut c_float); pub fn vdTanh(n: c_int, a: *const c_double, y: *mut c_double); pub fn vsExp(n: c_int, a: *const c_float, y: *mut c_float);...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/cpu_backend.rs
use crate::backend::{BackendDevice, BackendStorage}; use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{DType, Error, IntDType, Layout, Result, Shape, WithDType}; use half::{bf16, f16}; use rayon::prelude::*; const USE_IM2COL_CONV1D: bool = true; const USE_IM2COL_CONV2D: bool = true; // TODO: Maybe we...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/convert.rs
//! Implement conversion traits for tensors use crate::{DType, Device, Error, Tensor, WithDType}; use half::{bf16, f16, slice::HalfFloatSliceExt}; use std::convert::TryFrom; impl<T: WithDType> TryFrom<&Tensor> for Vec<T> { type Error = Error; fn try_from(tensor: &Tensor) -> Result<Self, Self::Error> { ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/shape.rs
//! The shape of a tensor is a tuple with the size of each of its dimensions. #![allow(clippy::redundant_closure_call)] use crate::{Error, Result}; #[derive(Clone, PartialEq, Eq)] pub struct Shape(Vec<usize>); pub const SCALAR: Shape = Shape(vec![]); impl std::fmt::Debug for Shape { fn fmt(&self, f: &mut std::fm...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/cuda_backend.rs
use crate::backend::{BackendDevice, BackendStorage}; use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{CpuStorage, DType, Layout, Result, Shape, WithDType}; pub use candle_kernels as kernels; pub use cudarc; use cudarc::cublas::{Gemm, GemmConfig, StridedBatchedConfig}; use cudarc::driver::{ CudaFun...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/utils.rs
use std::str::FromStr; pub fn get_num_threads() -> usize { // Respond to the same environment variable as rayon. match std::env::var("RAYON_NUM_THREADS") .ok() .and_then(|s| usize::from_str(&s).ok()) { Some(x) if x > 0 => x, Some(_) | None => num_cpus::get(), } } pub fn...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/npy.rs
//! Numpy support for tensors. //! //! The spec for the npy format can be found in //! [npy-format](https://docs.scipy.org/doc/numpy-1.14.2/neps/npy-format.html). //! The functions from this module can be used to read tensors from npy/npz files //! or write tensors to these files. A npy file contains a single tensor (u...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/variable.rs
// Variables are wrappers around tensors that can be modified, they are typically used for holding // weights and being modified by gradient descent. // We do not expose a public way to create variables as this would break the invariant that the // tensor within a variable is actually with `is_variable` set to `true`. ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/accelerate.rs
#![allow(dead_code)] use libc::{c_char, c_double, c_float, c_int, c_long, c_ulong}; mod ffi { use super::*; extern "C" { // It would be nice to be able to switch to the NEWLAPACK version of the function but this // seems to trigger some link error. Available function names can be seen here: ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/pickle.rs
// Just enough pickle support to be able to read PyTorch checkpoints. // This hardcodes objects that are required for tensor reading, we may want to make this a bit more // composable/tensor agnostic at some point. use crate::{DType, Error as E, Layout, Result, Tensor}; use byteorder::{LittleEndian, ReadBytesExt}; use ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/indexer.rs
use crate::{Error, Tensor}; use std::ops::{ Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive, }; impl Tensor { /// Intended to be use by the trait `.i()` /// /// ``` /// # use candle_core::{Tensor, DType, Device, IndexOp}; /// let a = Tensor::zeros((2, ...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/display.rs
/// Pretty printing of tensors /// This implementation should be in line with the PyTorch version. /// https://github.com/pytorch/pytorch/blob/7b419e8513a024e172eae767e24ec1b849976b13/torch/_tensor_str.py use crate::{DType, Result, Tensor, WithDType}; use half::{bf16, f16}; impl Tensor { fn fmt_dt<T: WithDType + s...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/safetensors.rs
use crate::{DType, Device, Error, Result, Tensor, WithDType}; use safetensors::tensor as st; use safetensors::tensor::SafeTensors; use std::borrow::Cow; use std::collections::HashMap; use std::path::Path; impl From<DType> for st::Dtype { fn from(value: DType) -> Self { match value { DType::U8 =...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/op.rs
#![allow(clippy::redundant_closure_call)] use crate::{CpuStorage, CudaStorage, Layout, MetalStorage, Result, Shape, Tensor}; use half::{bf16, f16}; use num_traits::float::Float; #[derive(Clone, Copy, PartialEq, Eq)] pub enum CmpOp { Eq, Ne, Le, Ge, Lt, Gt, } #[derive(Debug, Clone, Copy, Partia...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/metal_backend.rs
use crate::backend::{BackendDevice, BackendStorage}; use crate::conv::{ParamsConv1D, ParamsConv2D, ParamsConvTranspose1D, ParamsConvTranspose2D}; use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{CpuStorage, DType, Layout, Result, Shape}; use candle_metal_kernels; use candle_metal_kernels::Kernels; use...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/backend.rs
use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{CpuStorage, DType, Layout, Result, Shape}; pub trait BackendStorage: Sized { type Device: BackendDevice; fn try_clone(&self, _: &Layout) -> Result<Self>; fn dtype(&self) -> DType; fn device(&self) -> &Self::Device; // Maybe this...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/error.rs
use crate::{DType, DeviceLocation, Layout, MetalError, Shape}; #[derive(Debug, Clone)] pub struct MatMulUnexpectedStriding { pub lhs_l: Layout, pub rhs_l: Layout, pub bmnk: (usize, usize, usize, usize), pub msg: &'static str, } /// Main library error type. #[derive(thiserror::Error, Debug)] pub enum E...
0
hf_public_repos/candle/candle-core
hf_public_repos/candle/candle-core/src/test_utils.rs
use crate::{Result, Tensor}; #[macro_export] macro_rules! test_device { // TODO: Switch to generating the two last arguments automatically once concat_idents is // stable. https://github.com/rust-lang/rust/issues/29599 ($fn_name: ident, $test_cpu: ident, $test_cuda: ident, $test_metal: ident) => { ...
0