text stringlengths 5 424k | id stringlengths 13 178 | metadata dict | __index_level_0__ int64 0 672 |
|---|---|---|---|
# Introduction

Welcome to this first **Bonus Unit**, where you'll learn to **fine-tune a Large Language Model (LLM) for function calling**.
In terms of LLMs, function calling is quickly be... | agents-course/units/en/bonus-unit1/introduction.mdx/0 | {
"file_path": "agents-course/units/en/bonus-unit1/introduction.mdx",
"repo_id": "agents-course",
"token_count": 773
} | 0 |
# Introduction to Agentic Frameworks
<img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/thumbnail.jpg" alt="Thumbnail"/>
Welcome to this second unit, where **we'll explore different agentic frameworks** that can be used to build powerful agentic applications.
We will study:
... | agents-course/units/en/unit2/introduction.mdx/0 | {
"file_path": "agents-course/units/en/unit2/introduction.mdx",
"repo_id": "agents-course",
"token_count": 780
} | 1 |
# Using Tools in LlamaIndex
**Defining a clear set of Tools is crucial to performance.** As we discussed in [unit 1](../../unit1/tools), clear tool interfaces are easier for LLMs to use.
Much like a software API interface for human engineers, they can get more out of the tool if it's easy to understand how it works.
... | agents-course/units/en/unit2/llama-index/tools.mdx/0 | {
"file_path": "agents-course/units/en/unit2/llama-index/tools.mdx",
"repo_id": "agents-course",
"token_count": 2037
} | 2 |
# Agentic Retrieval Augmented Generation (RAG)
In this unit, we'll be taking a look at how we can use Agentic RAG to help Alfred prepare for the amazing gala.
<Tip>We know we've already discussed Retrieval Augmented Generation (RAG) and agentic RAG in the previous unit, so feel free to skip ahead if you're already fa... | agents-course/units/en/unit3/agentic-rag/agentic-rag.mdx/0 | {
"file_path": "agents-course/units/en/unit3/agentic-rag/agentic-rag.mdx",
"repo_id": "agents-course",
"token_count": 474
} | 3 |
# Observabilidad y Evaluación de Agentes de IA

¡Bienvenido a la **Unidad Extra 2**! En este capítulo, explorarás estrategias avanzadas para observar, evaluar y, en última instancia, mejorar ... | agents-course/units/es/bonus-unit2/introduction.mdx/0 | {
"file_path": "agents-course/units/es/bonus-unit2/introduction.mdx",
"repo_id": "agents-course",
"token_count": 729
} | 4 |
# Entendiendo los Agentes de IA a través del Ciclo Pensamiento-Acción-Observación
<img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-check-3.jpg" alt="Planificación de la Unidad 1"/>
En las secciones anteriores, aprendimos:
- **Cómo las herramientas se ponen a disp... | agents-course/units/es/unit1/agent-steps-and-structure.mdx/0 | {
"file_path": "agents-course/units/es/unit1/agent-steps-and-structure.mdx",
"repo_id": "agents-course",
"token_count": 2625
} | 5 |
# Conclusión
¡Felicidades por terminar el módulo de `LangGraph` de esta segunda Unidad! 🥳
Ahora has dominado los fundamentos para construir flujos de trabajo estructurados con LangGraph que podrás llevar a producción.
Este módulo es solo el comienzo de tu viaje con LangGraph. Para temas más avanzados, recomendamos:... | agents-course/units/es/unit2/langgraph/conclusion.mdx/0 | {
"file_path": "agents-course/units/es/unit2/langgraph/conclusion.mdx",
"repo_id": "agents-course",
"token_count": 420
} | 6 |
<CourseFloatingBanner chapter={2}
classNames="absolute z-10 right-0 top-0"
notebooks={[
{label: "Google Colab", value: "https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/code_agents.ipynb"},
]} />
# Construcción de Agentes que Usan Código
Los a... | agents-course/units/es/unit2/smolagents/code_agents.mdx/0 | {
"file_path": "agents-course/units/es/unit2/smolagents/code_agents.mdx",
"repo_id": "agents-course",
"token_count": 7738
} | 7 |
# Introducción al Caso de Uso para RAG Agéntico

En esta unidad, ayudaremos a Alfred, nuestro amigable agente que está organizando la gala, utilizando RAG Agéntico para crear una herra... | agents-course/units/es/unit3/agentic-rag/introduction.mdx/0 | {
"file_path": "agents-course/units/es/unit3/agentic-rag/introduction.mdx",
"repo_id": "agents-course",
"token_count": 1191
} | 8 |
<CourseFloatingBanner chapter={2}
classNames="absolute z-10 right-0 top-0"
notebooks={[
{label: "Google Colab", value: "https://colab.research.google.com/#fileId=https%3A//huggingface.co/agents-course/notebooks/blob/main/fr/bonus-unit2/monitoring-and-evaluating-agents.ipynb"},
]} />
# Observer et évaluer des a... | agents-course/units/fr/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx/0 | {
"file_path": "agents-course/units/fr/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx",
"repo_id": "agents-course",
"token_count": 7618
} | 9 |
# Conclusion [[conclusion]]
Félicitations pour avoir terminé cette première Unité 🥳
Vous **maîtrisez les fondamentaux** et avez créé votre premier agent !
Il est **normal que vous soyez encore un peu confus par certains éléments**. Les agents sont un sujet complexe et il est courant de mettre un certain temps à tou... | agents-course/units/fr/unit1/conclusion.mdx/0 | {
"file_path": "agents-course/units/fr/unit1/conclusion.mdx",
"repo_id": "agents-course",
"token_count": 513
} | 10 |
# Graphe d'analyse de documents
Alfred à votre service. En tant que majordome de confiance de M. Wayne, j'ai pris la liberté de documenter comment j'aide M. Wayne avec ses divers besoins documentaires. Pendant qu'il s'occupe de ses... activités nocturnes, je m'assure que tous ses papiers, programmes d'entraînement et ... | agents-course/units/fr/unit2/langgraph/document_analysis_agent.mdx/0 | {
"file_path": "agents-course/units/fr/unit2/langgraph/document_analysis_agent.mdx",
"repo_id": "agents-course",
"token_count": 4065
} | 11 |
# Conclusion
Félicitations d'avoir terminé le module `smolagents` de cette deuxième unité 🥳
Vous **maîtrisez les fondamentaux** de `smolagents` et vous avez construit votre propre agent ! A présent que vous avez des compétences sur `smolagents`, vous pouvez maintenant commencer à créer des agents qui résoudront des ... | agents-course/units/fr/unit2/smolagents/conclusion.mdx/0 | {
"file_path": "agents-course/units/fr/unit2/smolagents/conclusion.mdx",
"repo_id": "agents-course",
"token_count": 305
} | 12 |
# Création d'un RAG pour converser avec les invités
Alfred, votre agent de confiance, se prépare pour le gala le plus extravagant du siècle. Pour s'assurer que l'événement se déroule sans encombre, il a besoin d'un accès rapide à des informations à jour sur chaque invité. Aidons le en créant un outil RAG alimenté par ... | agents-course/units/fr/unit3/agentic-rag/invitees.mdx/0 | {
"file_path": "agents-course/units/fr/unit3/agentic-rag/invitees.mdx",
"repo_id": "agents-course",
"token_count": 7170
} | 13 |
# 결론 [[conclusion]]
축하합니다! 첫 번째 유닛을 완료하셨네요 🥳
이제 **에이전트의 기본 개념을 마스터**하고 첫 AI 에이전트를 만드셨습니다!
**아직 일부 요소가 혼란스럽게 느껴지는 것은 정상**입니다. 에이전트는 복잡한 주제이며, 모든 것을 이해하는 데 시간이 걸리는 것이 일반적입니다.
계속 진행하기 전에 **배운 내용을 제대로 이해하는 시간을 가지세요**. 재미있는 부분으로 넘어가기 전에 이러한 요소들을 숙달하고 탄탄한 기초를 다지는 것이 중요합니다.
퀴즈 테스트를 통과하셨다면, 인증서를 받는 것도 잊지 마세요 🎓 👉 [여기를 클... | agents-course/units/ko/unit1/conclusion.mdx/0 | {
"file_path": "agents-course/units/ko/unit1/conclusion.mdx",
"repo_id": "agents-course",
"token_count": 1208
} | 14 |
# Введение

Добро пожаловать в первый **Бонусный раздел**, в котором вы научитесь **дообучать Большую Языковую Модель (LLM) вызову функций**.
С точки зрения LLM, вызов функций быстро с... | agents-course/units/ru-RU/bonus-unit1/introduction.mdx/0 | {
"file_path": "agents-course/units/ru-RU/bonus-unit1/introduction.mdx",
"repo_id": "agents-course",
"token_count": 2961
} | 15 |
# Наблюдение: Интеграция Обратной Связи для Рефлексии и Адаптации
Наблюдения - это то, **как агент воспринимает последствия своих действий**.
Они предоставляют важную информацию, которая подпитывает мыслительный процесс агента и направляет его дальнейшие действия.
Это **сигналы из окружения** - будь то данные из API... | agents-course/units/ru-RU/unit1/observations.mdx/0 | {
"file_path": "agents-course/units/ru-RU/unit1/observations.mdx",
"repo_id": "agents-course",
"token_count": 2975
} | 16 |
# Chào mừng bạn đến với Khóa học AI Agents 🤗 [[introduction]]
<figure>
<img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/thumbnail.jpg" alt="Thumbnail khóa học AI Agents" width="100%"/>
<figcaption>Phông nền của hình ảnh được tạo bằng <a href="https://scenario.com/">Scenario.... | agents-course/units/vi/unit0/introduction.mdx/0 | {
"file_path": "agents-course/units/vi/unit0/introduction.mdx",
"repo_id": "agents-course",
"token_count": 6195
} | 17 |
# LLM là gì?
<img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-check-1.jpg" alt="Unit 1 planning"/>
Ở phần trước, ta đã biết mỗi Agent cần **một mô hình AI làm lõi**, và LLM là loại mô hình AI phổ biến nhất cho mục đích này.
Giờ ta sẽ tìm hiểu LLM là gì và cách ch... | agents-course/units/vi/unit1/what-are-llms.mdx/0 | {
"file_path": "agents-course/units/vi/unit1/what-are-llms.mdx",
"repo_id": "agents-course",
"token_count": 6989
} | 18 |
<CourseFloatingBanner chapter={2}
classNames="absolute z-10 right-0 top-0"
notebooks={[
{label: "Google Colab", value: "https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit2/monitoring-and-evaluating-agents.ipynb"},
]} />
# 附加单元 2:AI 智能体(AI Agent)的可观测性与评... | agents-course/units/zh-CN/bonus_unit2/monitoring-and-evaluating-agents-notebook.mdx/0 | {
"file_path": "agents-course/units/zh-CN/bonus_unit2/monitoring-and-evaluating-agents-notebook.mdx",
"repo_id": "agents-course",
"token_count": 9851
} | 19 |
# Observe: 整合反馈以反思和调整
Observations(观察)是**智能体感知其行动结果的方式**。
它们提供关键信息,为智能体的思考过程提供燃料并指导未来行动。
这些是**来自环境的信号**——无论是 API 返回的数据、错误信息还是系统日志——它们指导着下一轮的思考循环。
在观察阶段,智能体会:
- **收集反馈**:接收数据或确认其行动是否成功
- **附加结果**:将新信息整合到现有上下文中,有效更新记忆
- **调整策略**:使用更新后的上下文来优化后续思考和行动
例如,当天气 API 返回数据*"partly cloudy, 15°C, 60% humidity"*(局部多云,15°C,60% ... | agents-course/units/zh-CN/unit1/observations.mdx/0 | {
"file_path": "agents-course/units/zh-CN/unit1/observations.mdx",
"repo_id": "agents-course",
"token_count": 1851
} | 20 |
# 目录
此 LlamaIndex 框架大纲是课程第 2 单元的一部分。您可以在 hf.co/learn 上访问有关 LlamaIndex 的第 2 单元 👉 <a href="https://hf.co/learn/agents-course/unit2/llama-index/introduction">这里</a>
| 标题 | 描述 |
| -------------------------------- | ------... | agents-course/units/zh-CN/unit2/llama-index/README.md/0 | {
"file_path": "agents-course/units/zh-CN/unit2/llama-index/README.md",
"repo_id": "agents-course",
"token_count": 1137
} | 21 |
# 小测验(不计分)[[quiz2]]
现在该测试您对*代码智能体*、*工具调用智能体*和*工具*章节的理解了。本测验为可选且不计分。
---
### Q1: 使用 `@tool` 装饰器创建工具与创建 `Tool` 的子类之间的主要区别是什么?
以下哪个陈述最能描述这两种定义工具方法的区别?
<Question
choices={[
{
text: "使用 <code>@tool</code> 装饰器是检索类工具的强制要求,而 <code>Tool</code> 的子类仅用于文本生成任务",
explain: "两种方法都适用于任何类型的工具,包括检索类和文本生成类工具。",
},
{
... | agents-course/units/zh-CN/unit2/smolagents/quiz2.mdx/0 | {
"file_path": "agents-course/units/zh-CN/unit2/smolagents/quiz2.mdx",
"repo_id": "agents-course",
"token_count": 3839
} | 22 |
# 动手实践
现在你已经准备好更深入地创建你的最终智能体了,让我们看看如何提交它以供评审。
## 数据集
此排行榜使用的数据集包含从 GAIA **验证**集的一级问题中所提取的 20 个问题。
这些问题是根据回答问题所需的工具和步骤数量进行筛选的。
根据 GAIA 基准目前的状况,我们认为让你尝试在一级问题中达到 30% 的准确率是一个相对好的测试。
<img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/leaderboard%20GAIA%2024%3A04%3A2025.png" alt... | agents-course/units/zh-CN/unit4/hands-on.mdx/0 | {
"file_path": "agents-course/units/zh-CN/unit4/hands-on.mdx",
"repo_id": "agents-course",
"token_count": 2053
} | 23 |
[package]
name = "candle-book"
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 = { ... | candle/candle-book/Cargo.toml/0 | {
"file_path": "candle/candle-book/Cargo.toml",
"repo_id": "candle",
"token_count": 459
} | 24 |
# Installation
## 1. Create a new rust app or library
```bash
cargo new myapp
cd myapp
```
## 2. Add the correct candle version
### Standard
```bash
cargo add --git https://github.com/huggingface/candle.git candle-core
```
### CUDA
First, make sure that Cuda is correctly installed.
- `nvcc --version` should prin... | candle/candle-book/src/guide/installation.md/0 | {
"file_path": "candle/candle-book/src/guide/installation.md",
"repo_id": "candle",
"token_count": 464
} | 25 |
# 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... | candle/candle-book/src/training/simplified.md/0 | {
"file_path": "candle/candle-book/src/training/simplified.md",
"repo_id": "candle",
"token_count": 530
} | 26 |
#[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]]... | candle/candle-core/examples/basics.rs/0 | {
"file_path": "candle/candle-core/examples/basics.rs",
"repo_id": "candle",
"token_count": 308
} | 27 |
/// Helper functions to write CPU kernels.
use crate::backend::BackendStorage;
use crate::{Error, Layout, Result, WithDType};
type C = super::CpuStorage;
pub trait Map1 {
fn f<T: WithDType>(&self, vs: &[T], layout: &Layout) -> Result<Vec<T>>;
fn map(&self, vs: &C, layout: &Layout) -> Result<C> {
match... | candle/candle-core/src/cpu_backend/utils.rs/0 | {
"file_path": "candle/candle-core/src/cpu_backend/utils.rs",
"repo_id": "candle",
"token_count": 9870
} | 28 |
use crate::{DType, Result};
use candle_metal_kernels::{
metal::{
Buffer, BufferMap, CommandBuffer, Commands, ComputePipeline, Device, MTLResourceOptions,
},
Kernels,
};
use objc2_foundation::NSURL;
use objc2_metal::{MTLCaptureDescriptor, MTLCaptureDestination, MTLCaptureManager};
use std::path::Path... | candle/candle-core/src/metal_backend/device.rs/0 | {
"file_path": "candle/candle-core/src/metal_backend/device.rs",
"repo_id": "candle",
"token_count": 4213
} | 29 |
use super::k_quants::{BlockQ2K, BlockQ4K, BlockQ4_0, BlockQ6K, BlockQ8K, BlockQ8_0, QK8_0, QK_K};
use crate::Result;
use byteorder::{ByteOrder, LittleEndian};
use half::f16;
use core::arch::wasm32::*;
#[inline(always)]
pub(crate) fn vec_dot_q4_0_q8_0(n: usize, xs: &[BlockQ4_0], ys: &[BlockQ8_0]) -> Result<f32> {
... | candle/candle-core/src/quantized/simd128.rs/0 | {
"file_path": "candle/candle-core/src/quantized/simd128.rs",
"repo_id": "candle",
"token_count": 11617
} | 30 |
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... | candle/candle-core/tests/display_tests.rs/0 | {
"file_path": "candle/candle-core/tests/display_tests.rs",
"repo_id": "candle",
"token_count": 1395
} | 31 |
use candle::{DType, Device, Tensor};
use candle_nn::VarBuilder;
use candle_transformers::generation::LogitsProcessor;
use candle_transformers::models::codegeex4_9b::*;
use clap::Parser;
use hf_hub::{Repo, RepoType};
use tokenizers::Tokenizer;
struct TextGeneration {
model: Model,
device: Device,
tokenizer:... | candle/candle-examples/examples/codegeex4-9b/main.rs/0 | {
"file_path": "candle/candle-examples/examples/codegeex4-9b/main.rs",
"repo_id": "candle",
"token_count": 3865
} | 32 |
#[cfg(feature = "mkl")]
extern crate intel_mkl_src;
#[cfg(feature = "accelerate")]
extern crate accelerate_src;
use std::fmt::Display;
use std::path::PathBuf;
use anyhow::bail;
use anyhow::{Error as E, Result};
use candle::{Device, Tensor};
use candle_nn::ops::softmax;
use candle_nn::VarBuilder;
use candle_transform... | candle/candle-examples/examples/debertav2/main.rs/0 | {
"file_path": "candle/candle-examples/examples/debertav2/main.rs",
"repo_id": "candle",
"token_count": 6735
} | 33 |
# candle-endocec
[EnCodec](https://huggingface.co/facebook/encodec_24khz) is a high-quality audio
compression model using an encoder/decoder architecture with residual vector
quantization.
## Running one example
```bash
cargo run --example encodec --features encodec --release -- code-to-audio \
candle-examples/e... | candle/candle-examples/examples/encodec/README.md/0 | {
"file_path": "candle/candle-examples/examples/encodec/README.md",
"repo_id": "candle",
"token_count": 305
} | 34 |
## GLM4
GLM-4-9B-0414 is a new architecture in the GLM-4 series developed by Zhipu AI. This model is not compatible with previous versions of GLM-4, such as THUDM/glm-4-9b, due to differences in model architecture and internal implementation. Users must explicitly specify the correct model type when loading it, as usin... | candle/candle-examples/examples/glm4/README.md/0 | {
"file_path": "candle/candle-examples/examples/glm4/README.md",
"repo_id": "candle",
"token_count": 829
} | 35 |
// An implementation of LLaMA https://github.com/facebookresearch/llama
//
// This is based on nanoGPT in a similar way to:
// https://github.com/Lightning-AI/lit-llama/blob/main/lit_llama/model.py
//
// The tokenizer config can be retrieved from:
// https://huggingface.co/hf-internal-testing/llama-tokenizer/raw/main/t... | candle/candle-examples/examples/llama_multiprocess/main.rs/0 | {
"file_path": "candle/candle-examples/examples/llama_multiprocess/main.rs",
"repo_id": "candle",
"token_count": 3774
} | 36 |
# candle-metavoice
MetaVoice-1B is a text-to-speech model trained on 100K hours of speech, more
details on the [model
card](https://huggingface.co/metavoiceio/metavoice-1B-v0.1).
Note that the current candle implementation suffers from some limitations as of
2024-03-02:
- The speaker embeddings are hardcoded.
- The g... | candle/candle-examples/examples/metavoice/README.md/0 | {
"file_path": "candle/candle-examples/examples/metavoice/README.md",
"repo_id": "candle",
"token_count": 178
} | 37 |
#[cfg(feature = "mkl")]
extern crate intel_mkl_src;
#[cfg(feature = "accelerate")]
extern crate accelerate_src;
use clap::{Parser, ValueEnum};
use candle::{DType, IndexOp, D};
use candle_nn::{Module, VarBuilder};
use candle_transformers::models::mobileone;
#[derive(Clone, Copy, Debug, ValueEnum)]
enum Which {
S... | candle/candle-examples/examples/mobileone/main.rs/0 | {
"file_path": "candle/candle-examples/examples/mobileone/main.rs",
"repo_id": "candle",
"token_count": 1212
} | 38 |
use anyhow::Result;
use candle::{Device, Tensor};
use clap::{Parser, Subcommand};
#[derive(Subcommand, Debug, Clone)]
enum Command {
Print {
#[arg(long)]
file: String,
},
SimpleEval {
#[arg(long)]
file: String,
},
}
#[derive(Parser, Debug)]
#[command(author, version, a... | candle/candle-examples/examples/onnx_basics.rs/0 | {
"file_path": "candle/candle-examples/examples/onnx_basics.rs",
"repo_id": "candle",
"token_count": 2016
} | 39 |
# candle-quantized-qwen2-instruct
[Qwen2]((https://qwenlm.github.io/blog/qwen2/)) is an upgraded version of Qwen1.5, released by Alibaba Cloud.
## Running the example
```bash
cargo run --example quantized-qwen2-instruct --release -- --prompt "Write a function to count prime numbers up to N."
```
0.5b, 1.5b, 7b and ... | candle/candle-examples/examples/quantized-qwen2-instruct/README.md/0 | {
"file_path": "candle/candle-examples/examples/quantized-qwen2-instruct/README.md",
"repo_id": "candle",
"token_count": 179
} | 40 |
use std::collections::VecDeque;
use rand::{distr::Uniform, rng, Rng};
use candle::{DType, Device, Error, Module, Result, Tensor};
use candle_nn::loss::mse;
use candle_nn::{linear, seq, Activation, AdamW, Optimizer, VarBuilder, VarMap};
use crate::gym_env::GymEnv;
const DEVICE: Device = Device::Cpu;
const EPISODES: ... | candle/candle-examples/examples/reinforcement-learning/dqn.rs/0 | {
"file_path": "candle/candle-examples/examples/reinforcement-learning/dqn.rs",
"repo_id": "candle",
"token_count": 2036
} | 41 |
use candle::Device;
use candle::Module;
use candle_nn::VarBuilder;
use candle_transformers::models::segformer::{
Config, ImageClassificationModel, SemanticSegmentationModel,
};
use clap::{Args, Parser, Subcommand};
use imageproc::image::Rgb;
use imageproc::integral_image::ArrayData;
use std::collections::HashMap;
u... | candle/candle-examples/examples/segformer/main.rs/0 | {
"file_path": "candle/candle-examples/examples/segformer/main.rs",
"repo_id": "candle",
"token_count": 2240
} | 42 |
use anyhow::{Error as E, Ok, Result};
use candle::{DType, IndexOp, Module, Tensor, D};
use candle_transformers::models::{stable_diffusion, t5};
use std::path::PathBuf;
use tokenizers::tokenizer::Tokenizer;
struct ClipWithTokenizer {
clip: stable_diffusion::clip::ClipTextTransformer,
config: stable_diffusion::c... | candle/candle-examples/examples/stable-diffusion-3/clip.rs/0 | {
"file_path": "candle/candle-examples/examples/stable-diffusion-3/clip.rs",
"repo_id": "candle",
"token_count": 4060
} | 43 |
# candle-whisper: speech recognition
An implementation of [OpenAI Whisper](https://github.com/openai/whisper) using
candle. Whisper is a general purpose speech recognition model, it can be used to
convert audio files (in the `.wav` format) to text. Supported features include
language detection as well as multilingual ... | candle/candle-examples/examples/whisper/README.md/0 | {
"file_path": "candle/candle-examples/examples/whisper/README.md",
"repo_id": "candle",
"token_count": 627
} | 44 |
#[cfg(feature = "mkl")]
extern crate intel_mkl_src;
#[cfg(feature = "accelerate")]
extern crate accelerate_src;
use candle_transformers::object_detection::{non_maximum_suppression, Bbox};
mod darknet;
use anyhow::Result;
use candle::{DType, Device, Tensor};
use candle_nn::{Module, VarBuilder};
use clap::Parser;
use ... | candle/candle-examples/examples/yolo-v3/main.rs/0 | {
"file_path": "candle/candle-examples/examples/yolo-v3/main.rs",
"repo_id": "candle",
"token_count": 3179
} | 45 |
use std::io::prelude::*;
pub trait Sample {
fn to_i16(&self) -> i16;
}
impl Sample for f32 {
fn to_i16(&self) -> i16 {
(self.clamp(-1.0, 1.0) * 32767.0) as i16
}
}
impl Sample for f64 {
fn to_i16(&self) -> i16 {
(self.clamp(-1.0, 1.0) * 32767.0) as i16
}
}
impl Sample for i16 {
... | candle/candle-examples/src/wav.rs/0 | {
"file_path": "candle/candle-examples/src/wav.rs",
"repo_id": "candle",
"token_count": 729
} | 46 |
#ifndef _GPU_OPS_KERNELS_H_
#define _GPU_OPS_KERNELS_H_
#include <cuda_runtime_api.h>
#include <cstddef>
#include <cstdint>
#include<stdlib.h>
#include<stdint.h>
namespace gpu_ops {
struct MHAParams {
uint32_t q_batch_stride;
uint32_t k_batch_stride;
uint32_t v_batch_stride;
uint32_t o_batch_stride;
uin... | candle/candle-flash-attn/kernels/kernels.h/0 | {
"file_path": "candle/candle-flash-attn/kernels/kernels.h",
"repo_id": "candle",
"token_count": 557
} | 47 |
#include "cuda_utils.cuh"
#include<stdint.h>
template <typename S, typename T>
__device__ void cast_(
const size_t numel,
const size_t num_dims,
const size_t *info,
const S *inp,
T *out
) {
const size_t *dims = info;
const size_t *strides = info + num_dims;
if (info == nullptr || is_con... | candle/candle-kernels/src/cast.cu/0 | {
"file_path": "candle/candle-kernels/src/cast.cu",
"repo_id": "candle",
"token_count": 4130
} | 48 |
use crate::kernels::sdpa::SdpaDType;
#[derive(thiserror::Error, Debug)]
pub enum MetalKernelError {
#[error("Could not lock kernel map: {0}")]
LockError(String),
#[error("Error while loading library: {0}")]
LoadLibraryError(String),
#[error("Error while loading function: {0}")]
LoadFunctionErro... | candle/candle-metal-kernels/src/err.rs/0 | {
"file_path": "candle/candle-metal-kernels/src/err.rs",
"repo_id": "candle",
"token_count": 563
} | 49 |
use crate::linear_split;
use crate::utils::{BufferOffset, EncoderProvider};
use crate::{set_params, Buffer, ComputeCommandEncoder, Device, Kernels, MetalKernelError, Source};
use objc2_metal::MTLResourceUsage;
#[allow(clippy::too_many_arguments)]
pub fn call_where_cond_strided(
device: &Device,
ep: impl Encode... | candle/candle-metal-kernels/src/kernels/ternary.rs/0 | {
"file_path": "candle/candle-metal-kernels/src/kernels/ternary.rs",
"repo_id": "candle",
"token_count": 688
} | 50 |
#include <metal_stdlib>
using namespace metal;
template <typename T>
inline T max_value();
template <>
inline int64_t max_value<int64_t>() {
return 0x7FFFFFFFFFFFFFFF;
}
template <>
inline uint32_t max_value<uint32_t>() {
return 0xFFFFFFFFu;
}
template <>
inline uint8_t max_value<uint8_t>() {
return 0xF... | candle/candle-metal-kernels/src/metal_src/indexing.metal/0 | {
"file_path": "candle/candle-metal-kernels/src/metal_src/indexing.metal",
"repo_id": "candle",
"token_count": 5472
} | 51 |
mod benchmarks;
use criterion::criterion_main;
criterion_main!(
benchmarks::softmax::benches,
benchmarks::layer_norm::benches,
benchmarks::conv::benches
);
| candle/candle-nn/benches/bench_main.rs/0 | {
"file_path": "candle/candle-nn/benches/bench_main.rs",
"repo_id": "candle",
"token_count": 58
} | 52 |
//! Cache Implementations
//!
use candle::{DType, Device, Result, Tensor};
#[derive(Debug, Clone)]
pub struct Cache {
// all_data is an option on a Tensor, this makes it possible to only create the actual tensor
// on the first call where the batch size is easily known.
// Also this makes it safe to clone ... | candle/candle-nn/src/kv_cache.rs/0 | {
"file_path": "candle/candle-nn/src/kv_cache.rs",
"repo_id": "candle",
"token_count": 12511
} | 53 |
#[cfg(feature = "mkl")]
extern crate intel_mkl_src;
#[cfg(feature = "accelerate")]
extern crate accelerate_src;
use candle::{Device, Result, Tensor};
#[test]
fn kv_cache() -> Result<()> {
let mut cache = candle_nn::kv_cache::Cache::new(0, 16);
for _ in [0, 1] {
assert_eq!(cache.current_seq_len(), 0);... | candle/candle-nn/tests/kv_cache.rs/0 | {
"file_path": "candle/candle-nn/tests/kv_cache.rs",
"repo_id": "candle",
"token_count": 2618
} | 54 |
[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 = { ... | candle/candle-pyo3/Cargo.toml/0 | {
"file_path": "candle/candle-pyo3/Cargo.toml",
"repo_id": "candle",
"token_count": 325
} | 55 |
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 _... | candle/candle-pyo3/py_src/candle/nn/module.py/0 | {
"file_path": "candle/candle-pyo3/py_src/candle/nn/module.py",
"repo_id": "candle",
"token_count": 12028
} | 56 |
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... | candle/candle-pyo3/test.py/0 | {
"file_path": "candle/candle-pyo3/test.py",
"repo_id": "candle",
"token_count": 340
} | 57 |
//! BigCode implementation in Rust based on the GPT-BigCode model.
//!
//! [StarCoder/BigCode](https://huggingface.co/bigcode/starcoderbase-1b) is a LLM
//! model specialized to code generation. The initial model was trained on 80
//! programming languages. See "StarCoder: A State-of-the-Art LLM for Code", Mukherjee et... | candle/candle-transformers/src/models/bigcode.rs/0 | {
"file_path": "candle/candle-transformers/src/models/bigcode.rs",
"repo_id": "candle",
"token_count": 6581
} | 58 |
use std::collections::HashMap;
use candle::{bail, Context, DType, Device, Module, Result, Tensor, D};
use candle_nn::{
conv1d, embedding, layer_norm, Conv1d, Conv1dConfig, Embedding, LayerNorm, VarBuilder,
};
use serde::{Deserialize, Deserializer};
pub const DTYPE: DType = DType::F32;
// NOTE: HiddenAct and Hidd... | candle/candle-transformers/src/models/debertav2.rs/0 | {
"file_path": "candle/candle-transformers/src/models/debertav2.rs",
"repo_id": "candle",
"token_count": 24495
} | 59 |
use candle::{Device, Result, Tensor};
pub fn get_noise(
num_samples: usize,
height: usize,
width: usize,
device: &Device,
) -> Result<Tensor> {
let height = height.div_ceil(16) * 2;
let width = width.div_ceil(16) * 2;
Tensor::randn(0f32, 1., (num_samples, 16, height, width), device)
}
#[de... | candle/candle-transformers/src/models/flux/sampling.rs/0 | {
"file_path": "candle/candle-transformers/src/models/flux/sampling.rs",
"repo_id": "candle",
"token_count": 2069
} | 60 |
//! Mamba inference implementation.
//!
//! See ["Mamba: Linear-Time Sequence Modeling with Selective State Spaces"](https://arxiv.org/abs/2312.00752)
//!
//! Based on reference implementation from the AlbertMamba project
//! A fast implementation of mamba for inference only.
//! Based on Laurent Mazare's rust implemen... | candle/candle-transformers/src/models/mamba.rs/0 | {
"file_path": "candle/candle-transformers/src/models/mamba.rs",
"repo_id": "candle",
"token_count": 3925
} | 61 |
use candle::{Module, Result, Tensor};
use candle_nn as nn;
pub struct Qkv {
pub q: Tensor,
pub k: Tensor,
pub v: Tensor,
}
pub struct Mlp {
fc1: nn::Linear,
act: nn::Activation,
fc2: nn::Linear,
}
impl Mlp {
pub fn new(
in_features: usize,
hidden_features: usize,
v... | candle/candle-transformers/src/models/mmdit/projections.rs/0 | {
"file_path": "candle/candle-transformers/src/models/mmdit/projections.rs",
"repo_id": "candle",
"token_count": 1917
} | 62 |
//! Parler Model implementation for parler_tts text-to-speech synthesis
//!
//! Implements a transformer-based decoder architecture for generating audio tokens
//! from text using discrete tokens. The model converts text into audio segments
//! using multiple codebooks of quantized audio tokens.
//!
//! The model archi... | candle/candle-transformers/src/models/parler_tts.rs/0 | {
"file_path": "candle/candle-transformers/src/models/parler_tts.rs",
"repo_id": "candle",
"token_count": 8563
} | 63 |
//! # ResNet Implementation
//!
//! Implementation of ResNet architectures as described in the paper:
//!
//! ## Reference
//!
//! [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385)
//! He et al. (2015)
//!
//! This paper introduced ResNet, a deep neural network architecture that utilizes
... | candle/candle-transformers/src/models/resnet.rs/0 | {
"file_path": "candle/candle-transformers/src/models/resnet.rs",
"repo_id": "candle",
"token_count": 4023
} | 64 |
use super::schedulers::{betas_for_alpha_bar, BetaSchedule, PredictionType};
use candle::{Result, Tensor};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DDPMVarianceType {
FixedSmall,
FixedSmallLog,
FixedLarge,
FixedLargeLog,
Learned,
}
impl Default for DDPMVarianceType {
fn default() -> Self... | candle/candle-transformers/src/models/stable_diffusion/ddpm.rs/0 | {
"file_path": "candle/candle-transformers/src/models/stable_diffusion/ddpm.rs",
"repo_id": "candle",
"token_count": 3666
} | 65 |
//! VGG-16 model implementation.
//!
//! VGG-16 is a convolutional neural network architecture. It consists of 13
//! convolutional layers followed by 3 fully connected layers.
//!
//! Key characteristics:
//! - Conv layers with 3x3 filters
//! - Max pooling after every 2-3 conv layers
//! - Three fully connected layer... | candle/candle-transformers/src/models/vgg.rs/0 | {
"file_path": "candle/candle-transformers/src/models/vgg.rs",
"repo_id": "candle",
"token_count": 4390
} | 66 |
use super::common::LayerNormNoWeights;
use candle::{Module, Result, Tensor};
use candle_nn::VarBuilder;
#[derive(Debug)]
pub struct MixingResidualBlock {
norm1: LayerNormNoWeights,
depthwise_conv: candle_nn::Conv2d,
norm2: LayerNormNoWeights,
channelwise_lin1: candle_nn::Linear,
channelwise_lin2: c... | candle/candle-transformers/src/models/wuerstchen/paella_vq.rs/0 | {
"file_path": "candle/candle-transformers/src/models/wuerstchen/paella_vq.rs",
"repo_id": "candle",
"token_count": 4078
} | 67 |
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<title>Candle Bert</title>
</head>
<body></body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
@import u... | candle/candle-wasm-examples/bert/lib-example.html/0 | {
"file_path": "candle/candle-wasm-examples/bert/lib-example.html",
"repo_id": "candle",
"token_count": 6066
} | 68 |
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<title>Candle Llama.c Rust/WASM</title>
</head>
<body></body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
... | candle/candle-wasm-examples/llama2-c/lib-example.html/0 | {
"file_path": "candle/candle-wasm-examples/llama2-c/lib-example.html",
"repo_id": "candle",
"token_count": 6089
} | 69 |
// Audio processing code, adapted from whisper.cpp
// https://github.com/ggerganov/whisper.cpp
use super::worker;
pub trait Float: num_traits::Float + num_traits::FloatConst + num_traits::NumAssign {}
impl Float for f32 {}
impl Float for f64 {}
// https://github.com/ggerganov/whisper.cpp/blob/4774d2feb01a772a15de81f... | candle/candle-wasm-examples/whisper/src/audio.rs/0 | {
"file_path": "candle/candle-wasm-examples/whisper/src/audio.rs",
"repo_id": "candle",
"token_count": 3162
} | 70 |
use yew_agent::PublicWorker;
fn main() {
console_error_panic_hook::set_once();
candle_wasm_example_yolo::Worker::register();
}
| candle/candle-wasm-examples/yolo/src/bin/worker.rs/0 | {
"file_path": "candle/candle-wasm-examples/yolo/src/bin/worker.rs",
"repo_id": "candle",
"token_count": 53
} | 71 |
# Use .env.local to change these variables
# DO NOT EDIT THIS FILE WITH SENSITIVE DATA
### Models ###
# Models are sourced exclusively from an OpenAI-compatible base URL.
# Example: https://router.huggingface.co/v1
OPENAI_BASE_URL=
# Canonical auth token for any OpenAI-compatible provider
OPENAI_API_KEY=#your provide... | chat-ui/.env/0 | {
"file_path": "chat-ui/.env",
"repo_id": "chat-ui",
"token_count": 2064
} | 72 |
{
"version": "0.2.0",
"configurations": [
{
"command": "npm run dev",
"name": "Run development server",
"request": "launch",
"type": "node-terminal"
}
]
}
| chat-ui/.vscode/launch.json/0 | {
"file_path": "chat-ui/.vscode/launch.json",
"repo_id": "chat-ui",
"token_count": 82
} | 73 |
{{- if $.Values.networkPolicy.enabled }}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: {{ include "name" . }}
namespace: {{ .Release.Namespace }}
spec:
egress:
- ports:
- port: 53
protocol: UDP
to:
- namespaceSelector:
matchLabels:
... | chat-ui/chart/templates/network-policy.yaml/0 | {
"file_path": "chat-ui/chart/templates/network-policy.yaml",
"repo_id": "chat-ui",
"token_count": 494
} | 74 |
declare module "*.ttf" {
const value: ArrayBuffer;
export default value;
}
// Legacy helpers removed: web search support is deprecated, so we intentionally
// avoid leaking those shapes into the global ambient types.
| chat-ui/src/ambient.d.ts/0 | {
"file_path": "chat-ui/src/ambient.d.ts",
"repo_id": "chat-ui",
"token_count": 54
} | 75 |
<script lang="ts">
import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";
interface Props {
classNames?: string;
onClick?: () => void;
showBorder?: boolean;
}
let { classNames = "", onClick, showBorder = false }: Props = $props();
</script>
<button
type="button"
onclick={onClick}
class={`btn s... | chat-ui/src/lib/components/StopGeneratingBtn.svelte/0 | {
"file_path": "chat-ui/src/lib/components/StopGeneratingBtn.svelte",
"repo_id": "chat-ui",
"token_count": 613
} | 76 |
<script lang="ts">
import MarkdownRenderer from "./MarkdownRenderer.svelte";
import CarbonCaretDown from "~icons/carbon/caret-down";
interface Props {
summary: string;
content: string;
loading?: boolean;
}
let { summary, content, loading = false }: Props = $props();
let isOpen = $state(loading);
$effect... | chat-ui/src/lib/components/chat/OpenReasoningResults.svelte/0 | {
"file_path": "chat-ui/src/lib/components/chat/OpenReasoningResults.svelte",
"repo_id": "chat-ui",
"token_count": 1919
} | 77 |
export const PUBLIC_SEP_TOKEN = "</s>";
| chat-ui/src/lib/constants/publicSepToken.ts/0 | {
"file_path": "chat-ui/src/lib/constants/publicSepToken.ts",
"repo_id": "chat-ui",
"token_count": 16
} | 78 |
import type { ObjectId } from "mongodb";
import updateSearchAssistant from "./01-update-search-assistants";
import updateAssistantsModels from "./02-update-assistants-models";
import type { Database } from "$lib/server/database";
import updateMessageUpdates from "./04-update-message-updates";
import updateMessageFiles... | chat-ui/src/lib/migrations/routines/index.ts/0 | {
"file_path": "chat-ui/src/lib/migrations/routines/index.ts",
"repo_id": "chat-ui",
"token_count": 355
} | 79 |
import { z } from "zod";
import { openAICompletionToTextGenerationStream } from "./openAICompletionToTextGenerationStream";
import {
openAIChatToTextGenerationSingle,
openAIChatToTextGenerationStream,
} from "./openAIChatToTextGenerationStream";
import type { CompletionCreateParamsStreaming } from "openai/resources/c... | chat-ui/src/lib/server/endpoints/openai/endpointOai.ts/0 | {
"file_path": "chat-ui/src/lib/server/endpoints/openai/endpointOai.ts",
"repo_id": "chat-ui",
"token_count": 2986
} | 80 |
import { z } from "zod";
import { config } from "$lib/server/config";
import JSON5 from "json5";
const sanitizeJSONEnv = (val: string, fallback: string) => {
const raw = (val ?? "").trim();
const unquoted = raw.startsWith("`") && raw.endsWith("`") ? raw.slice(1, -1) : raw;
return unquoted || fallback;
};
// RATE_L... | chat-ui/src/lib/server/usageLimits.ts/0 | {
"file_path": "chat-ui/src/lib/server/usageLimits.ts",
"repo_id": "chat-ui",
"token_count": 365
} | 81 |
import type { MessageUpdate } from "./MessageUpdate";
import type { Timestamps } from "./Timestamps";
import type { v4 } from "uuid";
export type Message = Partial<Timestamps> & {
from: "user" | "assistant" | "system";
id: ReturnType<typeof v4>;
content: string;
updates?: MessageUpdate[];
reasoning?: string;
sc... | chat-ui/src/lib/types/Message.ts/0 | {
"file_path": "chat-ui/src/lib/types/Message.ts",
"repo_id": "chat-ui",
"token_count": 277
} | 82 |
import type { env as publicEnv } from "$env/dynamic/public";
import { page } from "$app/state";
import { base } from "$app/paths";
import type { Transporter } from "@sveltejs/kit";
import { getContext } from "svelte";
type PublicConfigKey = keyof typeof publicEnv;
class PublicConfigManager {
#configStore = $state<R... | chat-ui/src/lib/utils/PublicConfig.svelte.ts/0 | {
"file_path": "chat-ui/src/lib/utils/PublicConfig.svelte.ts",
"repo_id": "chat-ui",
"token_count": 691
} | 83 |
import type { MessageFile } from "$lib/types/Message";
import {
type MessageUpdate,
type MessageStreamUpdate,
MessageUpdateType,
} from "$lib/types/MessageUpdate";
import { page } from "$app/state";
type MessageUpdateRequestOptions = {
base: string;
inputs?: string;
messageId?: string;
isRetry: boolean;
isCon... | chat-ui/src/lib/utils/messageUpdates.ts/0 | {
"file_path": "chat-ui/src/lib/utils/messageUpdates.ts",
"repo_id": "chat-ui",
"token_count": 2436
} | 84 |
import type { Tree, TreeId, TreeNode } from "./tree";
export function buildSubtree<T>(conv: Tree<T>, id: TreeId): TreeNode<T>[] {
if (!conv.rootMessageId) {
if (conv.messages.length === 0) return [];
// legacy conversation slice up to id
const index = conv.messages.findIndex((m) => m.id === id);
if (index ===... | chat-ui/src/lib/utils/tree/buildSubtree.ts/0 | {
"file_path": "chat-ui/src/lib/utils/tree/buildSubtree.ts",
"repo_id": "chat-ui",
"token_count": 302
} | 85 |
import { collections } from "$lib/server/database";
import { authCondition } from "$lib/server/auth";
import { z } from "zod";
import { ObjectId } from "mongodb";
export async function GET({ locals, params }) {
const id = z.string().parse(params.id);
const convId = new ObjectId(id);
if (locals.user?._id || locals.... | chat-ui/src/routes/api/conversation/[id]/+server.ts/0 | {
"file_path": "chat-ui/src/routes/api/conversation/[id]/+server.ts",
"repo_id": "chat-ui",
"token_count": 432
} | 86 |
import { getOIDCAuthorizationUrl } from "$lib/server/auth";
import { base } from "$app/paths";
import { config } from "$lib/server/config";
export async function GET({ request, url, locals }) {
const referer = request.headers.get("referer");
let redirectURI = `${(referer ? new URL(referer) : url).origin}${base}/logi... | chat-ui/src/routes/login/+server.ts/0 | {
"file_path": "chat-ui/src/routes/login/+server.ts",
"repo_id": "chat-ui",
"token_count": 270
} | 87 |
<script lang="ts">
import { page } from "$app/state";
import { base } from "$app/paths";
import type { BackendModel } from "$lib/server/models";
import IconOmni from "$lib/components/icons/IconOmni.svelte";
import { useSettingsStore } from "$lib/stores/settings";
import CopyToClipBoardBtn from "$lib/components/C... | chat-ui/src/routes/settings/(nav)/[...model]/+page.svelte/0 | {
"file_path": "chat-ui/src/routes/settings/(nav)/[...model]/+page.svelte",
"repo_id": "chat-ui",
"token_count": 3966
} | 88 |
{
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {
"values": "<DVC_METRIC_DATA>"
},
"title": "<DVC_METRIC_TITLE>",
"mark": {
"type": "line"
},
"encoding": {
"x": {
"field": "<DVC_METRIC_X>",
"type": "quantitative",
... | datasets/.dvc/plots/smooth.json/0 | {
"file_path": "datasets/.dvc/plots/smooth.json",
"repo_id": "datasets",
"token_count": 569
} | 89 |
import timeit
import numpy as np
import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD
def get_duration(func):
def wrapper(*args, **kwargs):
starttime = timeit.default_timer()
_ = func(*args, **kwargs)
delta = timeit.default_timer()... | datasets/benchmarks/utils.py/0 | {
"file_path": "datasets/benchmarks/utils.py",
"repo_id": "datasets",
"token_count": 927
} | 90 |
# Command Line Interface (CLI)
🤗 Datasets provides a command line interface (CLI) with useful shell commands to interact with your dataset.
You can check the available commands:
```bash
>>> datasets-cli --help
usage: datasets-cli <command> [<args>]
positional arguments:
{env,test,delete_from_hub}
... | datasets/docs/source/cli.mdx/0 | {
"file_path": "datasets/docs/source/cli.mdx",
"repo_id": "datasets",
"token_count": 516
} | 91 |
# Installation
Before you start, you'll need to setup your environment and install the appropriate packages. 🤗 Datasets is tested on **Python 3.9+**.
> [!TIP]
> If you want to use 🤗 Datasets with TensorFlow or PyTorch, you'll need to install them separately. Refer to the [TensorFlow installation page](https://www.t... | datasets/docs/source/installation.md/0 | {
"file_path": "datasets/docs/source/installation.md",
"repo_id": "datasets",
"token_count": 1061
} | 92 |
# Stream
Dataset streaming lets you work with a dataset without downloading it.
The data is streamed as you iterate over the dataset.
This is especially helpful when:
- You don't want to wait for an extremely large dataset to download.
- The dataset size exceeds the amount of available disk space on your computer.
- ... | datasets/docs/source/stream.mdx/0 | {
"file_path": "datasets/docs/source/stream.mdx",
"repo_id": "datasets",
"token_count": 7919
} | 93 |
<!---
Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or ... | datasets/notebooks/README.md/0 | {
"file_path": "datasets/notebooks/README.md",
"repo_id": "datasets",
"token_count": 534
} | 94 |
import contextlib
import copy
import fnmatch
import itertools
import json
import math
import posixpath
import random
import re
import time
from collections.abc import Sequence
from functools import partial
from pathlib import Path
from typing import Callable, Optional, Union
import fsspec
import numpy as np
from fsspe... | datasets/src/datasets/dataset_dict.py/0 | {
"file_path": "datasets/src/datasets/dataset_dict.py",
"repo_id": "datasets",
"token_count": 62611
} | 95 |
import os
from functools import partial
from typing import Optional
import fsspec
from fsspec.archive import AbstractArchiveFileSystem
class BaseCompressedFileFileSystem(AbstractArchiveFileSystem):
"""Read contents of compressed file as a filesystem with one file inside."""
root_marker = ""
protocol: st... | datasets/src/datasets/filesystems/compression.py/0 | {
"file_path": "datasets/src/datasets/filesystems/compression.py",
"repo_id": "datasets",
"token_count": 1827
} | 96 |
import multiprocessing
import os
from typing import BinaryIO, Optional, Union
import fsspec
from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import tqdm as hf_tqdm
from ..utils.typing import NestedDataStructureLike, Pa... | datasets/src/datasets/io/json.py/0 | {
"file_path": "datasets/src/datasets/io/json.py",
"repo_id": "datasets",
"token_count": 3162
} | 97 |
import contextlib
from multiprocessing import Pool, RLock
from tqdm.auto import tqdm
from ..utils import experimental, logging
logger = logging.get_logger(__name__)
class ParallelBackendConfig:
backend_name = None
@experimental
def parallel_map(function, iterable, num_proc, batched, batch_size, types, disab... | datasets/src/datasets/parallel/parallel.py/0 | {
"file_path": "datasets/src/datasets/parallel/parallel.py",
"repo_id": "datasets",
"token_count": 1783
} | 98 |
import enum
import os
from typing import Optional
from huggingface_hub.utils import insecure_hashlib
from .. import config
from ..exceptions import (
ExpectedMoreDownloadedFilesError,
ExpectedMoreSplitsError,
NonMatchingChecksumError,
NonMatchingSplitsSizesError,
UnexpectedDownloadedFileError,
... | datasets/src/datasets/utils/info_utils.py/0 | {
"file_path": "datasets/src/datasets/utils/info_utils.py",
"repo_id": "datasets",
"token_count": 1731
} | 99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.