text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
# 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 generated audio file quality is weaker than the Python implementation, probably because of some implementation discrepancies. ## Run an example ```bash cargo run --example metavoice --release -- \ --prompt "This is a demo of text to speech by MetaVoice-1B, an open-source foundational audio model." ```
candle/candle-examples/examples/metavoice/README.md/0
{ "file_path": "candle/candle-examples/examples/metavoice/README.md", "repo_id": "candle", "token_count": 178 }
37
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, about, long_about = None)] pub struct Args { #[command(subcommand)] command: Command, } pub fn main() -> Result<()> { let args = Args::parse(); match args.command { Command::Print { file } => { let model = candle_onnx::read_file(file)?; println!("{model:?}"); let graph = model.graph.unwrap(); for node in graph.node.iter() { println!("{node:?}"); } } Command::SimpleEval { file } => { let model = candle_onnx::read_file(file)?; let graph = model.graph.as_ref().unwrap(); let constants: std::collections::HashSet<_> = graph.initializer.iter().map(|i| i.name.as_str()).collect(); let mut inputs = std::collections::HashMap::new(); for input in graph.input.iter() { use candle_onnx::onnx::tensor_proto::DataType; if constants.contains(input.name.as_str()) { continue; } let type_ = input.r#type.as_ref().expect("no type for input"); let type_ = type_.value.as_ref().expect("no type.value for input"); let value = match type_ { candle_onnx::onnx::type_proto::Value::TensorType(tt) => { let dt = match DataType::try_from(tt.elem_type) { Ok(dt) => match candle_onnx::dtype(dt) { Some(dt) => dt, None => { anyhow::bail!( "unsupported 'value' data-type {dt:?} for {}", input.name ) } }, type_ => anyhow::bail!("unsupported input type {type_:?}"), }; let shape = tt.shape.as_ref().expect("no tensortype.shape for input"); let dims = shape .dim .iter() .map(|dim| match dim.value.as_ref().expect("no dim value") { candle_onnx::onnx::tensor_shape_proto::dimension::Value::DimValue(v) => Ok(*v as usize), candle_onnx::onnx::tensor_shape_proto::dimension::Value::DimParam(_) => Ok(42), }) .collect::<Result<Vec<usize>>>()?; Tensor::zeros(dims, dt, &Device::Cpu)? } type_ => anyhow::bail!("unsupported input type {type_:?}"), }; println!("input {}: {value:?}", input.name); inputs.insert(input.name.clone(), value); } let outputs = candle_onnx::simple_eval(&model, inputs)?; for (name, value) in outputs.iter() { println!("output {name}: {value:?}") } } } Ok(()) }
candle/candle-examples/examples/onnx_basics.rs/0
{ "file_path": "candle/candle-examples/examples/onnx_basics.rs", "repo_id": "candle", "token_count": 2016 }
38
# 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 72b models are available via `--which` argument. ```bash cargo run --release --example quantized-qwen2-instruct -- --which 0.5b --prompt "Write a function to count prime numbers up to N." ```
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 }
39
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: usize = 200; const BATCH_SIZE: usize = 64; const GAMMA: f64 = 0.99; const LEARNING_RATE: f64 = 0.01; pub fn run() -> Result<()> { let env = GymEnv::new("CartPole-v1")?; // Build the model that predicts the estimated rewards given a specific state. let var_map = VarMap::new(); let vb = VarBuilder::from_varmap(&var_map, DType::F32, &DEVICE); let observation_space = *env.observation_space().first().unwrap(); let model = seq() .add(linear(observation_space, 64, vb.pp("linear_in"))?) .add(Activation::Relu) .add(linear(64, env.action_space(), vb.pp("linear_out"))?); let mut optimizer = AdamW::new_lr(var_map.all_vars(), LEARNING_RATE)?; // Initialize the model's memory. let mut memory = VecDeque::with_capacity(10000); // Start the training loop. let mut state = env.reset(0)?; let mut episode = 0; let mut accumulate_rewards = 0.0; while episode < EPISODES { // Given the current state, predict the estimated rewards, and take the // action that is expected to return the most rewards. let estimated_rewards = model.forward(&state.unsqueeze(0)?)?; let action: u32 = estimated_rewards.squeeze(0)?.argmax(0)?.to_scalar()?; // Take that action in the environment, and memorize the outcome: // - the state for which the action was taken // - the action taken // - the new state resulting of taking that action // - the actual rewards of taking that action // - whether the environment reached a terminal state or not (e.g. game over) let step = env.step(action)?; accumulate_rewards += step.reward; memory.push_back(( state, action, step.state.clone(), step.reward, step.terminated || step.truncated, )); state = step.state; // If there's enough entries in the memory, perform a learning step, where // BATCH_SIZE transitions will be sampled from the memory and will be // fed to the model so that it performs a backward pass. if memory.len() > BATCH_SIZE { // Sample randomly from the memory. let batch = rng() .sample_iter(Uniform::try_from(0..memory.len()).map_err(Error::wrap)?) .take(BATCH_SIZE) .map(|i| memory.get(i).unwrap().clone()) .collect::<Vec<_>>(); // Group all the samples together into tensors with the appropriate shape. let states: Vec<_> = batch.iter().map(|e| e.0.clone()).collect(); let states = Tensor::stack(&states, 0)?; let actions = batch.iter().map(|e| e.1); let actions = Tensor::from_iter(actions, &DEVICE)?.unsqueeze(1)?; let next_states: Vec<_> = batch.iter().map(|e| e.2.clone()).collect(); let next_states = Tensor::stack(&next_states, 0)?; let rewards = batch.iter().map(|e| e.3 as f32); let rewards = Tensor::from_iter(rewards, &DEVICE)?.unsqueeze(1)?; let non_final_mask = batch.iter().map(|e| !e.4 as u8 as f32); let non_final_mask = Tensor::from_iter(non_final_mask, &DEVICE)?.unsqueeze(1)?; // Get the estimated rewards for the actions that where taken at each step. let estimated_rewards = model.forward(&states)?; let x = estimated_rewards.gather(&actions, 1)?; // Get the maximum expected rewards for the next state, apply them a discount rate // GAMMA and add them to the rewards that were actually gathered on the current state. // If the next state is a terminal state, just omit maximum estimated // rewards for that state. let expected_rewards = model.forward(&next_states)?.detach(); let y = expected_rewards.max_keepdim(1)?; let y = (y * GAMMA * non_final_mask + rewards)?; // Compare the estimated rewards with the maximum expected rewards and // perform the backward step. let loss = mse(&x, &y)?; optimizer.backward_step(&loss)?; } // If we are on a terminal state, reset the environment and log how it went. if step.terminated || step.truncated { episode += 1; println!("Episode {episode} | Rewards {}", accumulate_rewards as i64); state = env.reset(0)?; accumulate_rewards = 0.0; } } Ok(()) }
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 }
40
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; use std::path::PathBuf; #[derive(Parser)] #[clap(about, version, long_about = None)] struct CliArgs { #[arg(long, help = "use cpu")] cpu: bool, #[command(subcommand)] command: Commands, } #[derive(Args, Debug)] struct SegmentationArgs { #[arg( long, help = "name of the huggingface hub model", default_value = "nvidia/segformer-b0-finetuned-ade-512-512" )] model_name: String, #[arg( long, help = "path to the label file in json format", default_value = "candle-examples/examples/segformer/assets/labels.json" )] label_path: PathBuf, #[arg(long, help = "path to for the output mask image")] output_path: PathBuf, #[arg(help = "path to image as input")] image: PathBuf, } #[derive(Args, Debug)] struct ClassificationArgs { #[arg( long, help = "name of the huggingface hub model", default_value = "paolinox/segformer-finetuned-food101" )] model_name: String, #[arg(help = "path to image as input")] image: PathBuf, } #[derive(Subcommand, Debug)] enum Commands { Segment(SegmentationArgs), Classify(ClassificationArgs), } fn get_vb_and_config( model_name: String, device: &Device, ) -> anyhow::Result<(VarBuilder<'_>, Config)> { println!("loading model {model_name} via huggingface hub"); let api = hf_hub::api::sync::Api::new()?; let api = api.model(model_name.clone()); let model_file = api.get("model.safetensors")?; println!("model {model_name} downloaded and loaded"); let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model_file], candle::DType::F32, device)? }; let config = std::fs::read_to_string(api.get("config.json")?)?; let config: Config = serde_json::from_str(&config)?; println!("{config:?}"); Ok((vb, config)) } #[derive(Debug, serde::Deserialize)] struct LabelItem { index: u32, color: String, } fn segmentation_task(args: SegmentationArgs, device: &Device) -> anyhow::Result<()> { let label_file = std::fs::read_to_string(&args.label_path)?; let label_items: Vec<LabelItem> = serde_json::from_str(&label_file)?; let label_colors: HashMap<u32, Rgb<u8>> = label_items .iter() .map(|x| { (x.index - 1, { let color = x.color.trim_start_matches('#'); let r = u8::from_str_radix(&color[0..2], 16).unwrap(); let g = u8::from_str_radix(&color[2..4], 16).unwrap(); let b = u8::from_str_radix(&color[4..6], 16).unwrap(); Rgb([r, g, b]) }) }) .collect(); let image = candle_examples::imagenet::load_image224(args.image)? .unsqueeze(0)? .to_device(device)?; let (vb, config) = get_vb_and_config(args.model_name, device)?; let num_labels = label_items.len(); let model = SemanticSegmentationModel::new(&config, num_labels, vb)?; let segmentations = model.forward(&image)?; // generate a mask image let mask = &segmentations.squeeze(0)?.argmax(0)?; let (h, w) = mask.dims2()?; let mask = mask.flatten_all()?.to_vec1::<u32>()?; let mask = mask .iter() .flat_map(|x| label_colors[x].data()) .collect::<Vec<u8>>(); let mask: image::ImageBuffer<image::Rgb<u8>, Vec<u8>> = image::ImageBuffer::from_raw(w as u32, h as u32, mask).unwrap(); // resize let mask = image::DynamicImage::from(mask); let mask = mask.resize_to_fill( w as u32 * 4, h as u32 * 4, image::imageops::FilterType::CatmullRom, ); mask.save(args.output_path.clone())?; println!("mask image saved to {:?}", args.output_path); Ok(()) } fn classification_task(args: ClassificationArgs, device: &Device) -> anyhow::Result<()> { let image = candle_examples::imagenet::load_image224(args.image)? .unsqueeze(0)? .to_device(device)?; let (vb, config) = get_vb_and_config(args.model_name, device)?; let num_labels = 7; let model = ImageClassificationModel::new(&config, num_labels, vb)?; let classification = model.forward(&image)?; let classification = candle_nn::ops::softmax_last_dim(&classification)?; let classification = classification.squeeze(0)?; println!( "classification logits {:?}", classification.to_vec1::<f32>()? ); let label_id = classification.argmax(0)?.to_scalar::<u32>()?; let label_id = format!("{label_id}"); println!("label: {}", config.id2label[&label_id]); Ok(()) } pub fn main() -> anyhow::Result<()> { let args = CliArgs::parse(); let device = candle_examples::device(args.cpu)?; if let Commands::Segment(args) = args.command { segmentation_task(args, &device)? } else if let Commands::Classify(args) = args.command { classification_task(args, &device)? } Ok(()) }
candle/candle-examples/examples/segformer/main.rs/0
{ "file_path": "candle/candle-examples/examples/segformer/main.rs", "repo_id": "candle", "token_count": 2240 }
41
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::clip::Config, tokenizer: Tokenizer, max_position_embeddings: usize, } impl ClipWithTokenizer { fn new( vb: candle_nn::VarBuilder, config: stable_diffusion::clip::Config, tokenizer_path: &str, max_position_embeddings: usize, ) -> Result<Self> { let clip = stable_diffusion::clip::ClipTextTransformer::new(vb, &config)?; let path_buf = hf_hub::api::sync::Api::new()? .model(tokenizer_path.to_string()) .get("tokenizer.json")?; let tokenizer = Tokenizer::from_file(path_buf.to_str().ok_or(E::msg( "Failed to serialize huggingface PathBuf of CLIP tokenizer", ))?) .map_err(E::msg)?; Ok(Self { clip, config, tokenizer, max_position_embeddings, }) } fn encode_text_to_embedding( &self, prompt: &str, device: &candle::Device, ) -> Result<(Tensor, Tensor)> { let pad_id = match &self.config.pad_with { Some(padding) => *self .tokenizer .get_vocab(true) .get(padding.as_str()) .ok_or(E::msg("Failed to tokenize CLIP padding."))?, None => *self .tokenizer .get_vocab(true) .get("<|endoftext|>") .ok_or(E::msg("Failed to tokenize CLIP end-of-text."))?, }; let mut tokens = self .tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); let eos_position = tokens.len() - 1; while tokens.len() < self.max_position_embeddings { tokens.push(pad_id) } let tokens = Tensor::new(tokens.as_slice(), device)?.unsqueeze(0)?; let (text_embeddings, text_embeddings_penultimate) = self .clip .forward_until_encoder_layer(&tokens, usize::MAX, -2)?; let text_embeddings_pooled = text_embeddings.i((0, eos_position, ..))?; Ok((text_embeddings_penultimate, text_embeddings_pooled)) } } struct T5WithTokenizer { t5: t5::T5EncoderModel, tokenizer: Tokenizer, max_position_embeddings: usize, } impl T5WithTokenizer { fn new(vb: candle_nn::VarBuilder, max_position_embeddings: usize) -> Result<Self> { let api = hf_hub::api::sync::Api::new()?; let repo = api.repo(hf_hub::Repo::with_revision( "google/t5-v1_1-xxl".to_string(), hf_hub::RepoType::Model, "refs/pr/2".to_string(), )); let config_filename = repo.get("config.json")?; let config = std::fs::read_to_string(config_filename)?; let config: t5::Config = serde_json::from_str(&config)?; let model = t5::T5EncoderModel::load(vb, &config)?; let tokenizer_filename = api .model("lmz/mt5-tokenizers".to_string()) .get("t5-v1_1-xxl.tokenizer.json")?; let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; Ok(Self { t5: model, tokenizer, max_position_embeddings, }) } fn encode_text_to_embedding( &mut self, prompt: &str, device: &candle::Device, ) -> Result<Tensor> { let mut tokens = self .tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); tokens.resize(self.max_position_embeddings, 0); let input_token_ids = Tensor::new(&tokens[..], device)?.unsqueeze(0)?; let embeddings = self.t5.forward_dt(&input_token_ids, Some(DType::F32))?; Ok(embeddings) } } pub struct StableDiffusion3TripleClipWithTokenizer { clip_l: ClipWithTokenizer, clip_g: ClipWithTokenizer, clip_g_text_projection: candle_nn::Linear, t5: T5WithTokenizer, } impl StableDiffusion3TripleClipWithTokenizer { pub fn new_split( clip_g_file: &PathBuf, clip_l_file: &PathBuf, t5xxl_file: &PathBuf, device: &candle::Device, ) -> Result<Self> { let vb_clip_g = unsafe { candle_nn::VarBuilder::from_mmaped_safetensors(&[clip_g_file], DType::F16, device)? }; let vb_clip_l = unsafe { candle_nn::VarBuilder::from_mmaped_safetensors(&[clip_l_file], DType::F16, device)? }; let vb_t5 = unsafe { candle_nn::VarBuilder::from_mmaped_safetensors(&[t5xxl_file], DType::F16, device)? }; let max_position_embeddings = 77usize; let clip_l = ClipWithTokenizer::new( vb_clip_l, stable_diffusion::clip::Config::sdxl(), "openai/clip-vit-large-patch14", max_position_embeddings, )?; let text_projection = candle_nn::linear_no_bias(1280, 1280, vb_clip_g.pp("text_projection"))?; let clip_g = ClipWithTokenizer::new( vb_clip_g, stable_diffusion::clip::Config::sdxl2(), "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", max_position_embeddings, )?; let t5 = T5WithTokenizer::new(vb_t5, max_position_embeddings)?; Ok(Self { clip_l, clip_g, clip_g_text_projection: text_projection, t5, }) } pub fn new(vb: candle_nn::VarBuilder) -> Result<Self> { let max_position_embeddings = 77usize; let clip_l = ClipWithTokenizer::new( vb.pp("clip_l.transformer"), stable_diffusion::clip::Config::sdxl(), "openai/clip-vit-large-patch14", max_position_embeddings, )?; let clip_g = ClipWithTokenizer::new( vb.pp("clip_g.transformer"), stable_diffusion::clip::Config::sdxl2(), "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", max_position_embeddings, )?; let text_projection = candle_nn::linear_no_bias(1280, 1280, vb.pp("clip_g.transformer.text_projection"))?; let t5 = T5WithTokenizer::new(vb.pp("t5xxl.transformer"), max_position_embeddings)?; Ok(Self { clip_l, clip_g, clip_g_text_projection: text_projection, t5, }) } pub fn encode_text_to_embedding( &mut self, prompt: &str, device: &candle::Device, ) -> Result<(Tensor, Tensor)> { let (clip_l_embeddings, clip_l_embeddings_pooled) = self.clip_l.encode_text_to_embedding(prompt, device)?; let (clip_g_embeddings, clip_g_embeddings_pooled) = self.clip_g.encode_text_to_embedding(prompt, device)?; let clip_g_embeddings_pooled = self .clip_g_text_projection .forward(&clip_g_embeddings_pooled.unsqueeze(0)?)? .squeeze(0)?; let y = Tensor::cat(&[&clip_l_embeddings_pooled, &clip_g_embeddings_pooled], 0)? .unsqueeze(0)?; let clip_embeddings_concat = Tensor::cat( &[&clip_l_embeddings, &clip_g_embeddings], D::Minus1, )? .pad_with_zeros(D::Minus1, 0, 2048)?; let t5_embeddings = self .t5 .encode_text_to_embedding(prompt, device)? .to_dtype(DType::F16)?; let context = Tensor::cat(&[&clip_embeddings_concat, &t5_embeddings], D::Minus2)?; Ok((context, y)) } }
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 }
42
# 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 speech recognition. ## Running some example If no audio file is passed as input, a [sample file](https://huggingface.co/datasets/Narsil/candle-examples/resolve/main/samples_jfk.wav) is automatically downloaded from the hub. ```bash cargo run --example whisper --release --features="symphonia" > No audio file submitted: Downloading https://huggingface.co/datasets/Narsil/candle_demo/blob/main/samples_jfk.wav > loaded wav data: Header { audio_format: 1, channel_count: 1, sampling_rate: 16000, bytes_per_second: 32000, bytes_per_sample: 2, bits_per_sample: 16 } > pcm data loaded 176000 > loaded mel: [1, 80, 3000] > 0.0s -- 30.0s: And so my fellow Americans ask not what your country can do for you ask what you can do for your country ``` In order to use the multilingual mode, specify a multilingual model via the `--model` flag, see the details below. ## Command line flags - `--input`: the audio file to be converted to text, in wav format. - `--language`: force the language to some specific value rather than being detected, e.g. `en`. - `--task`: the task to be performed, can be `transcribe` (return the text data in the original language) or `translate` (translate the text to English). - `--timestamps`: enable the timestamp mode where some timestamps are reported for each recognized audio extracts. - `--model`: the model to be used. Models that do not end with `-en` are multilingual models, other ones are English only models. The supported OpenAI Whisper models are `tiny`, `tiny.en`, `base`, `base.en`, `small`, `small.en`, `medium`, `medium.en`, `large`, `large-v2` and `large-v3`. The supported Distil-Whisper models are `distil-medium.en`, `distil-large-v2` and `distil-large-v3`.
candle/candle-examples/examples/whisper/README.md/0
{ "file_path": "candle/candle-examples/examples/whisper/README.md", "repo_id": "candle", "token_count": 627 }
43
#[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 image::{DynamicImage, ImageBuffer}; // Assumes x1 <= x2 and y1 <= y2 pub fn draw_rect( img: &mut ImageBuffer<image::Rgb<u8>, Vec<u8>>, x1: u32, x2: u32, y1: u32, y2: u32, ) { for x in x1..=x2 { let pixel = img.get_pixel_mut(x, y1); *pixel = image::Rgb([255, 0, 0]); let pixel = img.get_pixel_mut(x, y2); *pixel = image::Rgb([255, 0, 0]); } for y in y1..=y2 { let pixel = img.get_pixel_mut(x1, y); *pixel = image::Rgb([255, 0, 0]); let pixel = img.get_pixel_mut(x2, y); *pixel = image::Rgb([255, 0, 0]); } } pub fn report( pred: &Tensor, img: DynamicImage, w: usize, h: usize, confidence_threshold: f32, nms_threshold: f32, ) -> Result<DynamicImage> { let pred = pred.to_device(&Device::Cpu)?; let (npreds, pred_size) = pred.dims2()?; let nclasses = pred_size - 5; // The bounding boxes grouped by (maximum) class index. let mut bboxes: Vec<Vec<Bbox<()>>> = (0..nclasses).map(|_| vec![]).collect(); // Extract the bounding boxes for which confidence is above the threshold. for index in 0..npreds { let pred = Vec::<f32>::try_from(pred.get(index)?)?; let confidence = pred[4]; if confidence > confidence_threshold { let mut class_index = 0; for i in 0..nclasses { if pred[5 + i] > pred[5 + class_index] { class_index = i } } if pred[class_index + 5] > 0. { let bbox = Bbox { xmin: pred[0] - pred[2] / 2., ymin: pred[1] - pred[3] / 2., xmax: pred[0] + pred[2] / 2., ymax: pred[1] + pred[3] / 2., confidence, data: (), }; bboxes[class_index].push(bbox) } } } non_maximum_suppression(&mut bboxes, nms_threshold); // Annotate the original image and print boxes information. let (initial_h, initial_w) = (img.height(), img.width()); let w_ratio = initial_w as f32 / w as f32; let h_ratio = initial_h as f32 / h as f32; let mut img = img.to_rgb8(); for (class_index, bboxes_for_class) in bboxes.iter().enumerate() { for b in bboxes_for_class.iter() { println!( "{}: {:?}", candle_examples::coco_classes::NAMES[class_index], b ); let xmin = ((b.xmin * w_ratio) as u32).clamp(0, initial_w - 1); let ymin = ((b.ymin * h_ratio) as u32).clamp(0, initial_h - 1); let xmax = ((b.xmax * w_ratio) as u32).clamp(0, initial_w - 1); let ymax = ((b.ymax * h_ratio) as u32).clamp(0, initial_h - 1); draw_rect(&mut img, xmin, xmax, ymin, ymax); } } Ok(DynamicImage::ImageRgb8(img)) } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Model weights, in safetensors format. #[arg(long)] model: Option<String>, #[arg(long)] config: Option<String>, images: Vec<String>, /// Threshold for the model confidence level. #[arg(long, default_value_t = 0.5)] confidence_threshold: f32, /// Threshold for non-maximum suppression. #[arg(long, default_value_t = 0.4)] nms_threshold: f32, } impl Args { fn config(&self) -> anyhow::Result<std::path::PathBuf> { let path = match &self.config { Some(config) => std::path::PathBuf::from(config), None => { let api = hf_hub::api::sync::Api::new()?; let api = api.model("lmz/candle-yolo-v3".to_string()); api.get("yolo-v3.cfg")? } }; Ok(path) } fn model(&self) -> anyhow::Result<std::path::PathBuf> { let path = match &self.model { Some(model) => std::path::PathBuf::from(model), None => { let api = hf_hub::api::sync::Api::new()?; let api = api.model("lmz/candle-yolo-v3".to_string()); api.get("yolo-v3.safetensors")? } }; Ok(path) } } pub fn main() -> Result<()> { let args = Args::parse(); // Create the model and load the weights from the file. let model = args.model()?; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model], DType::F32, &Device::Cpu)? }; let config = args.config()?; let darknet = darknet::parse_config(config)?; let model = darknet.build_model(vb)?; for image_name in args.images.iter() { println!("processing {image_name}"); let mut image_name = std::path::PathBuf::from(image_name); // Load the image file and resize it. let net_width = darknet.width()?; let net_height = darknet.height()?; let original_image = image::ImageReader::open(&image_name)? .decode() .map_err(candle::Error::wrap)?; let image = { let data = original_image .resize_exact( net_width as u32, net_height as u32, image::imageops::FilterType::Triangle, ) .to_rgb8() .into_raw(); Tensor::from_vec(data, (net_width, net_height, 3), &Device::Cpu)?.permute((2, 0, 1))? }; let image = (image.unsqueeze(0)?.to_dtype(DType::F32)? * (1. / 255.))?; let predictions = model.forward(&image)?.squeeze(0)?; println!("generated predictions {predictions:?}"); let image = report( &predictions, original_image, net_width, net_height, args.confidence_threshold, args.nms_threshold, )?; image_name.set_extension("pp.jpg"); println!("writing {image_name:?}"); image.save(image_name)? } Ok(()) }
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 }
44
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 { fn to_i16(&self) -> i16 { *self } } pub fn write_pcm_as_wav<W: Write, S: Sample>( w: &mut W, samples: &[S], sample_rate: u32, ) -> std::io::Result<()> { let len = 12u32; // header let len = len + 24u32; // fmt let len = len + samples.len() as u32 * 2 + 8; // data let n_channels = 1u16; let bytes_per_second = sample_rate * 2 * n_channels as u32; w.write_all(b"RIFF")?; w.write_all(&(len - 8).to_le_bytes())?; // total length minus 8 bytes w.write_all(b"WAVE")?; // Format block w.write_all(b"fmt ")?; w.write_all(&16u32.to_le_bytes())?; // block len minus 8 bytes w.write_all(&1u16.to_le_bytes())?; // PCM w.write_all(&n_channels.to_le_bytes())?; // one channel w.write_all(&sample_rate.to_le_bytes())?; w.write_all(&bytes_per_second.to_le_bytes())?; w.write_all(&2u16.to_le_bytes())?; // 2 bytes of data per sample w.write_all(&16u16.to_le_bytes())?; // bits per sample // Data block w.write_all(b"data")?; w.write_all(&(samples.len() as u32 * 2).to_le_bytes())?; for sample in samples.iter() { w.write_all(&sample.to_i16().to_le_bytes())? } Ok(()) }
candle/candle-examples/src/wav.rs/0
{ "file_path": "candle/candle-examples/src/wav.rs", "repo_id": "candle", "token_count": 729 }
45
#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; uint32_t q_row_stride; uint32_t k_row_stride; uint32_t v_row_stride; uint32_t o_row_stride; uint32_t q_head_stride; uint32_t k_head_stride; uint32_t v_head_stride; uint32_t o_head_stride; uint32_t b; uint32_t h; uint32_t h_k; uint32_t d; uint32_t d_rounded; float softmax_scale; float softcap; uint32_t seqlen_q; uint32_t seqlen_k; uint32_t seqlen_q_rounded; uint32_t seqlen_k_rounded; int window_size_left; int window_size_right; int is_causal; int is_bf16; }; void run_mha_fwd_j(cudaStream_t stream, void **buffers, const char *opaque, std::size_t opaque_len); void run_mha_bwd_j(cudaStream_t stream, void **buffers, const char *opaque, std::size_t opaque_len); } #endif
candle/candle-flash-attn/kernels/kernels.h/0
{ "file_path": "candle/candle-flash-attn/kernels/kernels.h", "repo_id": "candle", "token_count": 557 }
46
#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_contiguous(num_dims, dims, strides)) { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { out[i] = inp[i]; } } else { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { unsigned strided_i = get_strided_index(i, num_dims, dims, strides); out[i] = inp[strided_i]; } } } #define F8E4M3_TO_FLOAT(x) __half2float(__nv_cvt_fp8_to_halfraw(x.__x, __NV_E4M3)) template <typename T> __device__ void cast_fp8_( const size_t numel, const size_t num_dims, const size_t *info, const __nv_fp8_e4m3 *inp, T *out ) { const size_t *dims = info; const size_t *strides = info + num_dims; if (info == nullptr || is_contiguous(num_dims, dims, strides)) { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { out[i] = F8E4M3_TO_FLOAT(inp[i]); } } else { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { unsigned strided_i = get_strided_index(i, num_dims, dims, strides); out[i] = F8E4M3_TO_FLOAT(inp[strided_i]); } } } template <typename S> __device__ void cast_fp8_into_( const size_t numel, const size_t num_dims, const size_t *info, const S *inp, __nv_fp8_e4m3 *out ) { const size_t *dims = info; const size_t *strides = info + num_dims; if (info == nullptr || is_contiguous(num_dims, dims, strides)) { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { out[i] = __nv_fp8_e4m3((float)inp[i]); } } else { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { unsigned strided_i = get_strided_index(i, num_dims, dims, strides); out[i] = __nv_fp8_e4m3((float)inp[strided_i]); } } } template <typename S, typename T, typename I> __device__ void cast_through( 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_contiguous(num_dims, dims, strides)) { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { out[i] = static_cast<T>(static_cast<I>(inp[i])); } } else { for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { unsigned strided_i = get_strided_index(i, num_dims, dims, strides); out[i] = static_cast<T>(static_cast<I>(inp[strided_i])); } } } #define CAST_OP(SRC_TYPENAME, DST_TYPENAME, FN_NAME) \ extern "C" __global__ void FN_NAME( \ const size_t numel, \ const size_t num_dims, \ const size_t *info, \ const SRC_TYPENAME *inp, \ DST_TYPENAME *out \ ) { \ cast_<SRC_TYPENAME, DST_TYPENAME>(numel, num_dims, info, inp, out); \ } \ #define CAST_OP_FP8(SRC_TYPENAME, DST_TYPENAME, FN_NAME) \ extern "C" __global__ void FN_NAME( \ const size_t numel, \ const size_t num_dims, \ const size_t *info, \ const SRC_TYPENAME *inp, \ DST_TYPENAME *out \ ) { \ cast_fp8_<DST_TYPENAME>(numel, num_dims, info, inp, out); \ } \ #define CAST_OP_FP8_INTO(SRC_TYPENAME, DST_TYPENAME, FN_NAME) \ extern "C" __global__ void FN_NAME( \ const size_t numel, \ const size_t num_dims, \ const size_t *info, \ const SRC_TYPENAME *inp, \ DST_TYPENAME *out \ ) { \ cast_fp8_into_<SRC_TYPENAME>(numel, num_dims, info, inp, out); \ } \ #define CAST_THROUGH_OP(SRC_TYPENAME, DST_TYPENAME, INT_TYPENAME, FN_NAME) \ extern "C" __global__ void FN_NAME( \ const size_t numel, \ const size_t num_dims, \ const size_t *info, \ const SRC_TYPENAME *inp, \ DST_TYPENAME *out \ ) { \ cast_through<SRC_TYPENAME, DST_TYPENAME, INT_TYPENAME>(numel, num_dims, info, inp, out); \ } \ #if __CUDA_ARCH__ >= 800 CAST_OP(__nv_bfloat16, __nv_bfloat16, cast_bf16_bf16) CAST_OP(__nv_fp8_e4m3, __nv_fp8_e4m3, cast_f8_e4m3_f8_e4m3) CAST_OP(__nv_bfloat16, uint32_t, cast_bf16_u32) CAST_OP(__nv_bfloat16, float, cast_bf16_f32) CAST_OP(__nv_bfloat16, double, cast_bf16_f64) CAST_OP(uint8_t, __nv_bfloat16, cast_u8_bf16) CAST_OP(uint32_t, __nv_bfloat16, cast_u32_bf16) CAST_OP(float, __nv_bfloat16, cast_f32_bf16) CAST_OP(double, __nv_bfloat16, cast_f64_bf16) CAST_THROUGH_OP(__nv_bfloat16, uint8_t, float, cast_bf16_u8) CAST_THROUGH_OP(__nv_bfloat16, __half, float, cast_bf16_f16) CAST_THROUGH_OP(__half, __nv_bfloat16, float, cast_f16_bf16) CAST_OP_FP8(__nv_fp8_e4m3, float, cast_f8_e4m3_f32) CAST_OP_FP8_INTO(float, __nv_fp8_e4m3, cast_f32_f8_e4m3) CAST_OP_FP8(__nv_fp8_e4m3, uint8_t, cast_f8_e4m3_u8) CAST_OP_FP8(__nv_fp8_e4m3, __half, cast_f8_e4m3_f16) CAST_OP_FP8(__nv_fp8_e4m3, double, cast_f8_e4m3_f64) CAST_OP_FP8_INTO(__half, __nv_fp8_e4m3, cast_f16_f8_e4m3) CAST_OP_FP8_INTO(double, __nv_fp8_e4m3, cast_f64_f8_e4m3) CAST_OP_FP8_INTO(uint8_t, __nv_fp8_e4m3, cast_u8_f8_e4m3) CAST_OP_FP8_INTO(int32_t, __nv_fp8_e4m3, cast_i32_f8_e4m3) CAST_OP_FP8(__nv_fp8_e4m3, int32_t, cast_f8_e4m3_i32) CAST_OP_FP8(__nv_fp8_e4m3, __nv_bfloat16, cast_f8_e4m3_bf16) CAST_OP_FP8_INTO(__nv_bfloat16, __nv_fp8_e4m3, cast_bf16_f8_e4m3) #else #include <cuda.h> #if CUDA_VERSION >= 11000 CAST_OP(__nv_bfloat16, float, cast_bf16_f32) CAST_OP(float, __nv_bfloat16, cast_f32_bf16) CAST_THROUGH_OP(__nv_bfloat16, uint8_t, float, cast_bf16_u8) CAST_THROUGH_OP(__nv_bfloat16, __half, float, cast_bf16_f16) CAST_THROUGH_OP(__nv_bfloat16, double, float, cast_bf16_f64) CAST_THROUGH_OP(__half, __nv_bfloat16, float, cast_f16_bf16) CAST_THROUGH_OP(double, __nv_bfloat16, float, cast_f64_bf16) CAST_THROUGH_OP(uint8_t, __nv_bfloat16, float, cast_u8_bf16) CAST_THROUGH_OP(__nv_bfloat16, __nv_fp8_e4m3, float, cast_bf16_f8_e4m3) #endif #endif #if __CUDA_ARCH__ >= 530 CAST_OP(__half, __half, cast_f16_f16) CAST_THROUGH_OP(__half, uint8_t, float, cast_f16_u8) CAST_OP(__half, uint32_t, cast_f16_u32) CAST_OP(__half, float, cast_f16_f32) CAST_OP(__half, double, cast_f16_f64) CAST_OP(uint8_t, __half, cast_u8_f16 ) CAST_OP(uint32_t, __half, cast_u32_f16) CAST_OP(float, __half, cast_f32_f16) CAST_OP(double, __half, cast_f64_f16) #endif CAST_OP(uint32_t, uint32_t, cast_u32_u32) CAST_OP(uint32_t, uint8_t, cast_u32_u8 ) CAST_OP(uint32_t, int64_t, cast_u32_i64 ) CAST_OP(uint32_t, float, cast_u32_f32) CAST_OP(uint32_t, double, cast_u32_f64) CAST_OP(uint8_t, uint32_t, cast_u8_u32) CAST_OP(uint8_t, uint8_t, cast_u8_u8 ) CAST_OP(uint8_t, int64_t, cast_u8_i64 ) CAST_OP(uint8_t, float, cast_u8_f32) CAST_OP(uint8_t, double, cast_u8_f64) CAST_OP(int64_t, uint32_t, cast_i64_u32) CAST_OP(int64_t, uint8_t, cast_i64_u8 ) CAST_OP(int64_t, int64_t, cast_i64_i64 ) CAST_OP(int64_t, float, cast_i64_f32) CAST_OP(int64_t, double, cast_i64_f64) CAST_OP(float, uint8_t, cast_f32_u8 ) CAST_OP(float, uint32_t, cast_f32_u32) CAST_OP(float, int64_t, cast_f32_i64 ) CAST_OP(float, float, cast_f32_f32) CAST_OP(float, double, cast_f32_f64) CAST_OP(double, uint8_t, cast_f64_u8 ) CAST_OP(double, uint32_t, cast_f64_u32) CAST_OP(double, int64_t, cast_f64_i64 ) CAST_OP(double, float, cast_f64_f32) CAST_OP(double, double, cast_f64_f64)
candle/candle-kernels/src/cast.cu/0
{ "file_path": "candle/candle-kernels/src/cast.cu", "repo_id": "candle", "token_count": 4130 }
47
#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]) * strides[dim_idx]; idx /= dims[dim_idx]; } return strided_i; } using namespace metal; #define AFFINE(FN_NAME, T) \ kernel void FN_NAME( \ constant size_t &dim, \ constant float &mul, \ constant float &add, \ device const T *input, \ device T *output, \ uint id [[ thread_position_in_grid ]] \ ) { \ if (id >= dim) { \ return; \ } \ output[id] = T(fma(float(input[id]), mul, add)); \ } \ kernel void FN_NAME##_strided( \ constant size_t &dim, \ constant size_t &num_dims, \ constant size_t *dims, \ constant size_t *strides, \ constant float &mul, \ constant float &add, \ device const T *input, \ device T *output, \ uint id [[ thread_position_in_grid ]] \ ) { \ if (id >= dim) { \ return; \ } \ output[id] = T(fma(float(input[get_strided_index(id, num_dims, dims, strides)]), mul, add)); \ } #define POWF(FN_NAME, TYPENAME) \ kernel void FN_NAME( \ constant size_t &dim, \ constant float &mul, \ device const TYPENAME *input, \ device TYPENAME *output, \ uint id [[ thread_position_in_grid ]] \ ) { \ if (id >= dim) { \ return; \ } \ output[id] = TYPENAME(pow(input[id], TYPENAME(mul))); \ } \ kernel void FN_NAME##_strided( \ constant size_t &dim, \ constant size_t &num_dims, \ constant size_t *dims, \ constant size_t *strides, \ constant float &mul, \ device const TYPENAME *input, \ device TYPENAME *output, \ uint id [[ thread_position_in_grid ]] \ ) { \ if (id >= dim) { \ return; \ } \ output[id] = TYPENAME(pow(input[get_strided_index(id, num_dims, dims, strides)], TYPENAME(mul))); \ } #define ELU(FN_NAME, TYPENAME) \ kernel void FN_NAME( \ constant size_t &dim, \ constant float &mul, \ device const TYPENAME *input, \ device TYPENAME *output, \ uint id [[ thread_position_in_grid ]] \ ) { \ if (id >= dim) { \ return; \ } \ const TYPENAME x = input[id]; \ output[id] = TYPENAME((x > 0)?x: mul * (exp(x) - 1)); \ } \ kernel void FN_NAME##_strided( \ constant size_t &dim, \ constant size_t &num_dims, \ constant size_t *dims, \ constant size_t *strides, \ constant float &mul, \ device const TYPENAME *input, \ device TYPENAME *output, \ uint id [[ thread_position_in_grid ]] \ ) { \ if (id >= dim) { \ return; \ } \ const TYPENAME x = input[get_strided_index(id, num_dims, dims, strides)]; \ output[id] = TYPENAME((x > 0)?x: mul * (exp(x) - 1)); \ } \ AFFINE(affine_u8, uint8_t) AFFINE(affine_u32, uint32_t) AFFINE(affine_f32, float) AFFINE(affine_f16, half) POWF(powf_f32, float) POWF(powf_f16, half) ELU(elu_f32, float) ELU(elu_f16, half) #if defined(__HAVE_BFLOAT__) AFFINE(affine_bf16, bfloat); POWF(powf_bf16, bfloat); ELU(elu_bf16, bfloat); #endif
candle/candle-metal-kernels/src/affine.metal/0
{ "file_path": "candle/candle-metal-kernels/src/affine.metal", "repo_id": "candle", "token_count": 1498 }
48
#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 % dims[dim_idx]) * strides[dim_idx]; idx /= dims[dim_idx]; } return strided_i; } template<typename T, typename ID> METAL_FUNC void where_cond( constant size_t &numel, constant size_t &num_dims, constant size_t *dims, constant size_t *strides, constant size_t *strides_t, constant size_t *strides_f, device const ID *ids, device const T *t, device const T *f, device T *out, uint i [[ thread_position_in_grid ]] ) { if (i >= numel){ return; } uint strided_i = get_strided_index(i, num_dims, dims, strides); uint strided_i_t = get_strided_index(i, num_dims, dims, strides_t); uint strided_i_f = get_strided_index(i, num_dims, dims, strides_f); out[i] = ids[strided_i] ? t[strided_i_t] : f[strided_i_f]; } #define WHERE_OP(T, ID, FN_NAME) \ kernel void FN_NAME( \ constant size_t &numel, \ constant size_t &num_dims, \ constant size_t *dims, \ constant size_t *strides, \ constant size_t *strides_t, \ constant size_t *strides_f, \ device const ID *ids, \ device const T *t, \ device const T *f, \ device T *out, \ uint i [[ thread_position_in_grid ]] \ ) { \ where_cond<T, ID>(numel, num_dims, dims, strides, strides_t, strides_f, ids, t, f, out, i); \ } \ WHERE_OP(half, uint32_t, where_u32_f16) WHERE_OP(float, uint32_t, where_u32_f32) WHERE_OP(uint8_t, uint32_t, where_u32_u8) WHERE_OP(uint32_t, uint32_t, where_u32_u32) WHERE_OP(half, uint8_t, where_u8_f16) WHERE_OP(float, uint8_t, where_u8_f32) WHERE_OP(uint8_t, uint8_t, where_u8_u8) WHERE_OP(uint32_t, uint8_t, where_u8_u32) #if __METAL_VERSION__ >= 220 WHERE_OP(int64_t, uint8_t, where_u8_i64) WHERE_OP(int64_t, uint32_t, where_u32_i64) WHERE_OP(half, int64_t, where_i64_f16) WHERE_OP(float, int64_t, where_i64_f32) WHERE_OP(uint8_t, int64_t, where_i64_u8) WHERE_OP(uint32_t, int64_t, where_i64_u32) WHERE_OP(int64_t, int64_t, where_i64_i64) #if defined(__HAVE_BFLOAT__) WHERE_OP(bfloat, int64_t, where_i64_bf16) #endif #endif #if defined(__HAVE_BFLOAT__) WHERE_OP(bfloat, uint8_t, where_u8_bf16) WHERE_OP(bfloat, uint32_t, where_u32_bf16) #endif
candle/candle-metal-kernels/src/ternary.metal/0
{ "file_path": "candle/candle-metal-kernels/src/ternary.metal", "repo_id": "candle", "token_count": 2256 }
49
#[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 sample linear data. let w_gen = Tensor::new(&[[3f32, 1.]], &Device::Cpu)?; let b_gen = Tensor::new(-2f32, &Device::Cpu)?; let gen = Linear::new(w_gen, Some(b_gen)); let sample_xs = Tensor::new(&[[2f32, 1.], [7., 4.], [-4., 12.], [5., 8.]], &Device::Cpu)?; let sample_ys = gen.forward(&sample_xs)?; Ok((sample_xs, sample_ys)) } fn main() -> Result<()> { let (sample_xs, sample_ys) = gen_data()?; // Use backprop to run a linear regression between samples and get the coefficients back. let varmap = VarMap::new(); let vb = VarBuilder::from_varmap(&varmap, DType::F32, &Device::Cpu); let model = linear(2, 1, vb.pp("linear"))?; let params = ParamsAdamW { lr: 0.1, ..Default::default() }; let mut opt = AdamW::new(varmap.all_vars(), params)?; for step in 0..10000 { let ys = model.forward(&sample_xs)?; let loss = ys.sub(&sample_ys)?.sqr()?.sum_all()?; opt.backward_step(&loss)?; println!("{step} {}", loss.to_vec0::<f32>()?); } Ok(()) }
candle/candle-nn/examples/basic_optimizer.rs/0
{ "file_path": "candle/candle-nn/examples/basic_optimizer.rs", "repo_id": "candle", "token_count": 595 }
50
//! 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<()>; fn learning_rate(&self) -> f64; fn set_learning_rate(&mut self, lr: f64); fn empty(config: Self::Config) -> Result<Self> { Self::new(vec![], config) } fn backward_step(&mut self, loss: &Tensor) -> Result<()> { let grads = loss.backward()?; self.step(&grads) } fn from_slice(vars: &[&Var], config: Self::Config) -> Result<Self> { let vars: Vec<_> = vars.iter().map(|&v| v.clone()).collect(); Self::new(vars, config) } } /// Optimizer for Stochastic Gradient Descent. /// /// Contrary to the PyTorch implementation of SGD, this version does not support momentum. #[derive(Debug)] pub struct SGD { vars: Vec<Var>, learning_rate: f64, } impl Optimizer for SGD { type Config = f64; fn new(vars: Vec<Var>, learning_rate: f64) -> Result<Self> { let vars = vars .into_iter() .filter(|var| var.dtype().is_float()) .collect(); Ok(Self { vars, learning_rate, }) } fn learning_rate(&self) -> f64 { self.learning_rate } fn step(&mut self, grads: &candle::backprop::GradStore) -> Result<()> { for var in self.vars.iter() { if let Some(grad) = grads.get(var) { var.set(&var.sub(&(grad * self.learning_rate)?)?)?; } } Ok(()) } fn set_learning_rate(&mut self, lr: f64) { self.learning_rate = lr } } impl SGD { pub fn into_inner(self) -> Vec<Var> { self.vars } pub fn push(&mut self, var: &Var) { self.vars.push(var.clone()) } } #[derive(Clone, Debug)] pub struct ParamsAdamW { pub lr: f64, pub beta1: f64, pub beta2: f64, pub eps: f64, pub weight_decay: f64, } impl Default for ParamsAdamW { fn default() -> Self { Self { lr: 0.001, beta1: 0.9, beta2: 0.999, eps: 1e-8, weight_decay: 0.01, } } } #[derive(Debug)] struct VarAdamW { var: Var, first_moment: Var, second_moment: Var, } #[derive(Debug)] pub struct AdamW { vars: Vec<VarAdamW>, step_t: usize, params: ParamsAdamW, } impl Optimizer for AdamW { type Config = ParamsAdamW; fn new(vars: Vec<Var>, params: ParamsAdamW) -> Result<Self> { let vars = vars .into_iter() .filter(|var| var.dtype().is_float()) .map(|var| { let dtype = var.dtype(); let shape = var.shape(); let device = var.device(); let first_moment = Var::zeros(shape, dtype, device)?; let second_moment = Var::zeros(shape, dtype, device)?; Ok(VarAdamW { var, first_moment, second_moment, }) }) .collect::<Result<Vec<_>>>()?; Ok(Self { vars, params, step_t: 0, }) } fn learning_rate(&self) -> f64 { self.params.lr } fn set_learning_rate(&mut self, lr: f64) { self.params.lr = lr } fn step(&mut self, grads: &candle::backprop::GradStore) -> Result<()> { self.step_t += 1; let lr = self.params.lr; let lambda = self.params.weight_decay; let lr_lambda = lr * lambda; let beta1 = self.params.beta1; let beta2 = self.params.beta2; let scale_m = 1f64 / (1f64 - beta1.powi(self.step_t as i32)); let scale_v = 1f64 / (1f64 - beta2.powi(self.step_t as i32)); for var in self.vars.iter() { let theta = &var.var; let m = &var.first_moment; let v = &var.second_moment; if let Some(g) = grads.get(theta) { // This involves locking 3 RWLocks per params, if the parameters are large this // should not be an issue but this may be problematic with models with lots of // small parameters. let next_m = ((m.as_tensor() * beta1)? + (g * (1.0 - beta1))?)?; let next_v = ((v.as_tensor() * beta2)? + (g.sqr()? * (1.0 - beta2))?)?; let m_hat = (&next_m * scale_m)?; let v_hat = (&next_v * scale_v)?; let next_theta = (theta.as_tensor() * (1f64 - lr_lambda))?; let adjusted_grad = (m_hat / (v_hat.sqrt()? + self.params.eps)?)?; let next_theta = (next_theta - (adjusted_grad * lr)?)?; m.set(&next_m)?; v.set(&next_v)?; theta.set(&next_theta)?; } } Ok(()) } } impl AdamW { pub fn new_lr(vars: Vec<Var>, learning_rate: f64) -> Result<Self> { let params = ParamsAdamW { lr: learning_rate, ..ParamsAdamW::default() }; Self::new(vars, params) } pub fn params(&self) -> &ParamsAdamW { &self.params } pub fn set_params(&mut self, params: ParamsAdamW) { self.params = params; } }
candle/candle-nn/src/optim.rs/0
{ "file_path": "candle/candle-nn/src/optim.rs", "repo_id": "candle", "token_count": 2798 }
51
#[cfg(feature = "metal")] mod metal_sdpa_tests { use candle::{DType, Device, Result, Shape, Tensor}; use rand::SeedableRng; use rand_distr::Distribution; use std::ops::{Div, Mul}; fn randn<S: Into<Shape>>( rng: &mut rand::rngs::StdRng, shape: S, dev: &Device, ) -> Result<Tensor> { let shape = shape.into(); let elem_count = shape.elem_count(); let normal = rand_distr::Normal::new(0.0, 1.0).unwrap(); let vs: Vec<f32> = (0..elem_count).map(|_| normal.sample(rng)).collect(); Tensor::from_vec(vs, &shape, dev) } #[test] fn sdpa_full() -> Result<()> { // Force seqlen = 100 const BS: usize = 4; const R: usize = 4; const L: usize = 4; const DK: usize = 64; const H: usize = 3; let scale: f64 = f64::from(DK as u32).sqrt().recip(); let device = Device::new_metal(0)?; let mut rng = rand::rngs::StdRng::seed_from_u64(42); let q = randn(&mut rng, (BS, H, R, DK), &device)?; let k = randn(&mut rng, (BS, H, L, DK), &device)?; let v = randn(&mut rng, (BS, H, L, DK), &device)?; let ground_truth = { let att = (q.clone() * scale)?.matmul(&k.clone().t()?)?; let att = candle_nn::ops::softmax_last_dim(&att.to_dtype(DType::F32)?)? .to_dtype(q.dtype())?; att.matmul(&v.clone())? }; let sdpa_output = candle_nn::ops::sdpa(&q, &k, &v, scale as f32, 1.)?; assert_eq!(ground_truth.shape(), sdpa_output.shape()); let error: f32 = ((&ground_truth - &sdpa_output)?.abs()? / &ground_truth.abs()?)? .sum_all()? .to_scalar()?; assert!(error <= 0.0004, "{}", error); Ok(()) } #[test] fn sdpa_vector() -> Result<()> { // Allow vectorized, seqlen = 1 const BS: usize = 4; const R: usize = 1; const L: usize = 1; const DK: usize = 64; const H: usize = 3; let scale: f64 = f64::from(DK as u32).sqrt().recip(); let device = Device::new_metal(0)?; let mut rng = rand::rngs::StdRng::seed_from_u64(4242); let q = randn(&mut rng, (BS, H, R, DK), &device)?; let k = randn(&mut rng, (BS, H, L, DK), &device)?; let v = randn(&mut rng, (BS, H, L, DK), &device)?; let ground_truth = { let att = (q.clone() * scale)?.matmul(&k.clone().t()?)?; let att = candle_nn::ops::softmax_last_dim(&att.to_dtype(DType::F32)?)? .to_dtype(q.dtype())?; att.matmul(&v.clone())? }; let sdpa_output = candle_nn::ops::sdpa(&q, &k, &v, scale as f32, 1.)?; assert_eq!(ground_truth.shape(), sdpa_output.shape()); let error: f32 = ((&ground_truth - &sdpa_output)?.abs()? / &ground_truth.abs()?)? .sum_all()? .to_scalar()?; assert!(error <= 0.000, "{}", error); Ok(()) } #[test] fn sdpa_full_softcapping() -> Result<()> { // Allow vectorized, seqlen = 1 const BS: usize = 4; const R: usize = 4; const L: usize = 4; const DK: usize = 64; const H: usize = 3; const SOFTCAP: f64 = 50.; let scale: f64 = f64::from(DK as u32).sqrt().recip(); let device = Device::new_metal(0)?; let mut rng = rand::rngs::StdRng::seed_from_u64(424242); let q = randn(&mut rng, (BS, H, R, DK), &device)?; let k = randn(&mut rng, (BS, H, L, DK), &device)?; let v = randn(&mut rng, (BS, H, L, DK), &device)?; let ground_truth = { let att = (q.clone() * scale)?.matmul(&k.clone().t()?)?; let att = candle_nn::ops::softmax_last_dim( &att.to_dtype(DType::F32)? .div(SOFTCAP)? .tanh()? .mul(SOFTCAP)?, )? .to_dtype(q.dtype())?; att.matmul(&v.clone())? }; let sdpa_output = candle_nn::ops::sdpa(&q, &k, &v, scale as f32, SOFTCAP as f32)?; assert_eq!(ground_truth.shape(), sdpa_output.shape()); let error: f32 = ((&ground_truth - &sdpa_output)?.abs()? / &ground_truth.abs()?)? .sum_all()? .to_scalar()?; assert!(error <= 0.0005, "{}", error); Ok(()) } #[test] fn sdpa_vector_softcapping() -> Result<()> { // Allow vectorized, seqlen = 1 const BS: usize = 4; const R: usize = 1; const L: usize = 1; const DK: usize = 64; const H: usize = 3; const SOFTCAP: f64 = 50.; let scale: f64 = f64::from(DK as u32).sqrt().recip(); let device = Device::new_metal(0)?; let mut rng = rand::rngs::StdRng::seed_from_u64(42424242); let q = randn(&mut rng, (BS, H, R, DK), &device)?; let k = randn(&mut rng, (BS, H, L, DK), &device)?; let v = randn(&mut rng, (BS, H, L, DK), &device)?; let ground_truth = { let att = (q.clone() * scale)?.matmul(&k.clone().t()?)?; let att = candle_nn::ops::softmax_last_dim( &att.to_dtype(DType::F32)? .div(SOFTCAP)? .tanh()? .mul(SOFTCAP)?, )? .to_dtype(q.dtype())?; att.matmul(&v.clone())? }; let sdpa_output = candle_nn::ops::sdpa(&q, &k, &v, scale as f32, SOFTCAP as f32)?; assert_eq!(ground_truth.shape(), sdpa_output.shape()); let error: f32 = ((&ground_truth - &sdpa_output)?.abs()? / &ground_truth.abs()?)? .sum_all()? .to_scalar()?; assert!(error <= 0.0001, "{}", error); Ok(()) } #[test] fn sdpa_vector_cross() -> Result<()> { // Allow vectorized, seqlen = 1. Simulat cross attention case where R != L, R = 1 const BS: usize = 4; const R: usize = 1; const L: usize = 24; const DK: usize = 64; const H: usize = 3; let scale: f64 = f64::from(DK as u32).sqrt().recip(); let device = Device::new_metal(0)?; let mut rng = rand::rngs::StdRng::seed_from_u64(4242424242); let q = randn(&mut rng, (BS, H, R, DK), &device)?; let k = randn(&mut rng, (BS, H, L, DK), &device)?; let v = randn(&mut rng, (BS, H, L, DK), &device)?; let ground_truth = { let att = (q.clone() * scale)?.matmul(&k.clone().t()?)?; let att = candle_nn::ops::softmax_last_dim(&att.to_dtype(DType::F32)?)? .to_dtype(q.dtype())?; att.matmul(&v.clone())? }; let sdpa_output = candle_nn::ops::sdpa(&q, &k, &v, scale as f32, 1.)?; assert_eq!(ground_truth.shape(), sdpa_output.shape()); let error: f32 = ((&ground_truth - &sdpa_output)?.abs()? / &ground_truth.abs()?)? .sum_all()? .to_scalar()?; assert!(error <= 0.0013, "{}", error); Ok(()) } }
candle/candle-nn/tests/sdpa.rs/0
{ "file_path": "candle/candle-nn/tests/sdpa.rs", "repo_id": "candle", "token_count": 3762 }
52
# 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: """ Concatenate the tensors across one axis. """ pass class f16(DType): pass class f32(DType): pass class f64(DType): pass class i64(DType): pass @staticmethod def ones(*shape: Shape, dtype: Optional[DType] = None, device: Optional[Device] = None) -> Tensor: """ Creates a new tensor filled with ones. """ pass @staticmethod def rand(*shape: Shape, device: Optional[Device] = None) -> Tensor: """ Creates a new tensor with random values. """ pass @staticmethod def randn(*shape: Shape, device: Optional[Device] = None) -> Tensor: """ Creates a new tensor with random values from a normal distribution. """ pass @staticmethod def stack(tensors: List[Tensor], dim: int) -> Tensor: """ Stack the tensors along a new axis. """ pass @staticmethod def tensor(data: _ArrayLike) -> Tensor: """ Creates a new tensor from a Python value. The value can be a scalar or array-like object. """ pass class u32(DType): pass class u8(DType): pass @staticmethod def zeros(*shape: Shape, dtype: Optional[DType] = None, device: Optional[Device] = None) -> Tensor: """ Creates a new tensor filled with zeros. """ pass class DType: """ A `candle` dtype. """ class QTensor: """ A quantized tensor. """ def dequantize(self) -> Tensor: """ Dequantizes the tensor. """ pass @property def ggml_dtype(self) -> str: """ Gets the tensors quantized dtype. """ pass def matmul_t(self, lhs: Tensor) -> Tensor: """ Performs a quantized matrix multiplication, with the quantized tensor as the right hand side. """ pass @property def rank(self) -> int: """ Gets the rank of the tensor. """ pass @property def shape(self) -> Tuple[int]: """ Gets the shape of the tensor. """ pass class Tensor: """ A `candle` tensor. """ def __init__(self, data: _ArrayLike): pass def __add__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Add a scalar to a tensor or two tensors together. """ pass def __eq__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __ge__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __getitem__(self, index: Union[Index, Tensor, Sequence[Index]]) -> "Tensor": """ Return a slice of a tensor. """ pass def __gt__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __le__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __lt__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __mul__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Multiply a tensor by a scalar or one tensor by another. """ pass def __ne__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __radd__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Add a scalar to a tensor or two tensors together. """ pass def __richcmp__(self, rhs: Union[Tensor, Scalar], op) -> "Tensor": """ Compare a tensor with a scalar or one tensor with another. """ pass def __rmul__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Multiply a tensor by a scalar or one tensor by another. """ pass def __sub__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Subtract a scalar from a tensor or one tensor from another. """ pass def __truediv__(self, rhs: Union[Tensor, Scalar]) -> "Tensor": """ Divide a tensor by a scalar or one tensor by another. """ pass def abs(self) -> Tensor: """ Performs the `abs` operation on the tensor. """ pass def argmax_keepdim(self, dim: int) -> Tensor: """ Returns the indices of the maximum value(s) across the selected dimension. """ pass def argmin_keepdim(self, dim: int) -> Tensor: """ Returns the indices of the minimum value(s) across the selected dimension. """ pass def broadcast_add(self, rhs: Tensor) -> Tensor: """ Adds the two tensors, while broadcasting the right-hand-side tensor to match the shape of the left-hand-side tensor. """ pass def broadcast_as(self, *shape: Shape) -> Tensor: """ Broadcasts the tensor to the given shape. """ pass def broadcast_div(self, rhs: Tensor) -> Tensor: """ Divides the two tensors, while broadcasting the right-hand-side tensor to match the shape of the left-hand-side tensor. """ pass def broadcast_left(self, *shape: Shape) -> Tensor: """ Broadcasts the tensor to the given shape, adding new dimensions on the left. """ pass def broadcast_mul(self, rhs: Tensor) -> Tensor: """ Multiplies the two tensors, while broadcasting the right-hand-side tensor to match the shape of the left-hand-side tensor. """ pass def broadcast_sub(self, rhs: Tensor) -> Tensor: """ Subtracts the two tensors, while broadcasting the right-hand-side tensor to match the shape of the left-hand-side tensor. """ pass def contiguous(self) -> Tensor: """ Makes the tensor contiguous in memory. """ pass def copy(self) -> Tensor: """ Returns a copy of the tensor. """ pass def cos(self) -> Tensor: """ Performs the `cos` operation on the tensor. """ pass def detach(self) -> Tensor: """ Detach the tensor from the computation graph. """ pass @property def device(self) -> Device: """ Gets the tensor's device. """ pass @property def dtype(self) -> DType: """ Gets the tensor's dtype. """ pass def exp(self) -> Tensor: """ Performs the `exp` operation on the tensor. """ pass def flatten_all(self) -> Tensor: """ Flattens the tensor into a 1D tensor. """ pass def flatten_from(self, dim: int) -> Tensor: """ Flattens the tensor on the dimension indexes from `dim` (inclusive) to the last dimension. """ pass def flatten_to(self, dim: int) -> Tensor: """ Flattens the tensor on the dimension indexes from `0` to `dim` (inclusive). """ pass def gather(self, index, dim): """ Gathers values along an axis specified by dim. """ pass def get(self, index: int) -> Tensor: """ Gets the value at the specified index. """ pass def index_select(self, rhs: Tensor, dim: int) -> Tensor: """ Select values for the input tensor at the target indexes across the specified dimension. The `indexes` is argument is an int tensor with a single dimension. The output has the same number of dimension as the `self` input. The target dimension of the output has length the length of `indexes` and the values are taken from `self` using the index from `indexes`. Other dimensions have the same number of elements as the input tensor. """ pass def is_contiguous(self) -> bool: """ Returns true if the tensor is contiguous in C order. """ pass def is_fortran_contiguous(self) -> bool: """ Returns true if the tensor is contiguous in Fortran order. """ pass def log(self) -> Tensor: """ Performs the `log` operation on the tensor. """ pass def matmul(self, rhs: Tensor) -> Tensor: """ Performs a matrix multiplication between the two tensors. """ pass def max_keepdim(self, dim: int) -> Tensor: """ Gathers the maximum value across the selected dimension. """ pass def mean_all(self) -> Tensor: """ Returns the mean of the tensor. """ pass def min_keepdim(self, dim: int) -> Tensor: """ Gathers the minimum value across the selected dimension. """ pass def narrow(self, dim: int, start: int, len: int) -> Tensor: """ Returns a new tensor that is a narrowed version of the input, the dimension `dim` ranges from `start` to `start + len`. """ pass @property def nelement(self) -> int: """ Gets the tensor's element count. """ pass def powf(self, p: float) -> Tensor: """ Performs the `pow` operation on the tensor with the given exponent. """ pass def quantize(self, quantized_dtype: str) -> QTensor: """ Quantize the tensor. """ pass @property def rank(self) -> int: """ Gets the tensor's rank. """ pass def recip(self) -> Tensor: """ Get the `recip` of the tensor. """ pass def reshape(self, *shape: Shape) -> Tensor: """ Reshapes the tensor to the given shape. """ pass @property def shape(self) -> Tuple[int]: """ Gets the tensor's shape. """ pass def sin(self) -> Tensor: """ Performs the `sin` operation on the tensor. """ pass def sqr(self) -> Tensor: """ Squares the tensor. """ pass def sqrt(self) -> Tensor: """ Calculates the square root of the tensor. """ pass def squeeze(self, dim: int) -> Tensor: """ Creates a new tensor with the specified dimension removed if its size was one. """ pass @property def stride(self) -> Tuple[int]: """ Gets the tensor's strides. """ pass def sum_all(self) -> Tensor: """ Returns the sum of the tensor. """ pass def sum_keepdim(self, dim: Union[int, List[int]]) -> Tensor: """ Returns the sum of all elements in the input tensor. The sum is performed over all the input dimensions. """ pass def t(self) -> Tensor: """ Transposes the tensor. """ pass def to(self, *args, **kwargs) -> Tensor: """ Performs Tensor dtype and/or device conversion. """ pass def to_device(self, device: Union[str, Device]) -> Tensor: """ Move the tensor to a new device. """ pass def to_dtype(self, dtype: Union[str, DType]) -> Tensor: """ Convert the tensor to a new dtype. """ pass def to_torch(self) -> torch.Tensor: """ Converts candle's tensor to pytorch's tensor """ pass def transpose(self, dim1: int, dim2: int) -> Tensor: """ Returns a tensor that is a transposed version of the input, the given dimensions are swapped. """ pass def unsqueeze(self, dim: int) -> Tensor: """ Creates a new tensor with a dimension of size one inserted at the specified position. """ pass def values(self) -> _ArrayLike: """ Gets the tensor's data as a Python scalar or array-like object. """ pass def where_cond(self, on_true: Tensor, on_false: Tensor) -> Tensor: """ Returns a tensor with the same shape as the input tensor, the values are taken from `on_true` if the input tensor value is not zero, and `on_false` at the positions where the input tensor is equal to zero. """ pass
candle/candle-pyo3/py_src/candle/__init__.pyi/0
{ "file_path": "candle/candle-pyo3/py_src/candle/__init__.pyi", "repo_id": "candle", "token_count": 5844 }
53
# 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_gguf save_safetensors = utils.save_safetensors
candle/candle-pyo3/py_src/candle/utils/__init__.py/0
{ "file_path": "candle/candle-pyo3/py_src/candle/utils/__init__.py", "repo_id": "candle", "token_count": 150 }
54
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]) assert t.values() == [3.0, 1, 4, 1, 5, 9, 2, 6] def test_tensor_can_be_constructed_from_list_of_lists(): t = Tensor([[3.0, 1, 4, 1], [5, 9, 2, 6]]) assert t.values() == [[3.0, 1, 4, 1], [5, 9, 2, 6]] def test_tensor_can_be_quantized(): t = candle.randn((16, 256)) for format in [ "q4_0", "q4_1", "q5_0", "q5_1", "q8_0", "q2k", "q3k", "q4k", "q5k", "q8k", ]: for formatted_format in [format.upper(), format.lower()]: quant_t = t.quantize(formatted_format) assert quant_t.ggml_dtype.lower() == format.lower() assert quant_t.shape == t.shape def test_tensor_can_be_indexed(): t = Tensor([[3.0, 1, 4, 1], [5, 9, 2, 6]]) assert t[0].values() == [3.0, 1.0, 4.0, 1.0] assert t[1].values() == [5.0, 9.0, 2.0, 6.0] assert t[-1].values() == [5.0, 9.0, 2.0, 6.0] assert t[-2].values() == [3.0, 1.0, 4.0, 1.0] def test_tensor_can_be_sliced(): t = Tensor([3.0, 1, 4, 10, 5, 9, 2, 6]) assert t[0:4].values() == [3.0, 1.0, 4.0, 10.0] assert t[4:8].values() == [5.0, 9.0, 2.0, 6.0] assert t[-4:].values() == [5.0, 9.0, 2.0, 6.0] assert t[:-4].values() == [3.0, 1.0, 4.0, 10.0] assert t[-4:-2].values() == [5.0, 9.0] assert t[...].values() == t.values() def test_tensor_can_be_sliced_2d(): t = Tensor([[3.0, 1, 4, 1], [5, 9, 2, 6]]) assert t[:, 0].values() == [3.0, 5] assert t[:, 1].values() == [1.0, 9.0] assert t[0, 0].values() == 3.0 assert t[:, -1].values() == [1.0, 6.0] assert t[:, -4].values() == [3.0, 5] assert t[..., 0].values() == [3.0, 5] def test_tensor_can_be_scliced_3d(): t = Tensor([[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]) assert t[:, :, 0].values() == [[1, 5], [9, 13]] assert t[:, :, 0:2].values() == [[[1, 2], [5, 6]], [[9, 10], [13, 14]]] assert t[:, 0, 0].values() == [1, 9] assert t[..., 0].values() == [[1, 5], [9, 13]] assert t[..., 0:2].values() == [[[1, 2], [5, 6]], [[9, 10], [13, 14]]] def assert_bool(t: Tensor, expected: bool): assert t.shape == () assert str(t.dtype) == str(candle.u8) assert bool(t.values()) == expected def test_tensor_supports_equality_operations_with_scalars(): t = Tensor(42.0) assert_bool(t == 42.0, True) assert_bool(t == 43.0, False) assert_bool(t != 42.0, False) assert_bool(t != 43.0, True) assert_bool(t > 41.0, True) assert_bool(t > 42.0, False) assert_bool(t >= 41.0, True) assert_bool(t >= 42.0, True) assert_bool(t < 43.0, True) assert_bool(t < 42.0, False) assert_bool(t <= 43.0, True) assert_bool(t <= 42.0, True) def test_tensor_supports_equality_operations_with_tensors(): t = Tensor(42.0) same = Tensor(42.0) other = Tensor(43.0) assert_bool(t == same, True) assert_bool(t == other, False) assert_bool(t != same, False) assert_bool(t != other, True) assert_bool(t > same, False) assert_bool(t > other, False) assert_bool(t >= same, True) assert_bool(t >= other, False) assert_bool(t < same, False) assert_bool(t < other, True) assert_bool(t <= same, True) assert_bool(t <= other, True) def test_tensor_equality_operations_can_broadcast(): # Create a decoder attention mask as a test case # e.g. # [[1,0,0] # [1,1,0] # [1,1,1]] mask_cond = candle.Tensor([0, 1, 2]) mask = mask_cond < (mask_cond + 1).reshape((3, 1)) assert mask.shape == (3, 3) assert_equal(mask, Tensor([[1, 0, 0], [1, 1, 0], [1, 1, 1]]).to_dtype(candle.u8)) def test_tensor_can_be_hashed(): t = Tensor(42.0) other = Tensor(42.0) # Hash should represent a unique tensor assert hash(t) != hash(other) assert hash(t) == hash(t) def test_tensor_can_be_expanded_with_none(): t = candle.rand((12, 12)) b = t[None] assert b.shape == (1, 12, 12) c = t[:, None, None, :] assert c.shape == (12, 1, 1, 12) d = t[None, :, None, :] assert d.shape == (1, 12, 1, 12) e = t[None, None, :, :] assert e.shape == (1, 1, 12, 12) f = t[:, :, None] assert f.shape == (12, 12, 1) def test_tensor_can_be_index_via_tensor(): t = candle.Tensor([[1, 2, 1, 2], [3, 4, 3, 4], [5, 6, 5, 6]]) indexed = t[candle.Tensor([0, 2])] assert indexed.shape == (2, 4) assert indexed.values() == [[1, 2, 1, 2], [5, 6, 5, 6]] indexed = t[:, candle.Tensor([0, 2])] assert indexed.shape == (3, 2) assert indexed.values() == [[1, 1], [3, 3], [5, 5]] def test_tensor_can_be_index_via_list(): t = candle.Tensor([[1, 2, 1, 2], [3, 4, 3, 4], [5, 6, 5, 6]]) indexed = t[[0, 2]] assert indexed.shape == (2, 4) assert indexed.values() == [[1, 2, 1, 2], [5, 6, 5, 6]] indexed = t[:, [0, 2]] assert indexed.shape == (3, 2) assert indexed.values() == [[1, 1], [3, 3], [5, 5]] def test_tensor_can_be_cast_via_to(): t = Tensor(42.0) assert str(t.dtype) == str(candle.f32) t_new_args = t.to(candle.f64) assert str(t_new_args.dtype) == str(candle.f64) t_new_kwargs = t.to(dtype=candle.f64) assert str(t_new_kwargs.dtype) == str(candle.f64) pytest.raises(TypeError, lambda: t.to("not a dtype")) pytest.raises(TypeError, lambda: t.to(dtype="not a dtype")) pytest.raises(TypeError, lambda: t.to(candle.f64, "not a dtype")) pytest.raises(TypeError, lambda: t.to()) pytest.raises(ValueError, lambda: t.to(candle.f16, dtype=candle.f64)) pytest.raises(ValueError, lambda: t.to(candle.f16, candle.f16)) other = Tensor(42.0).to(candle.f64) t_new_other_args = t.to(other) assert str(t_new_other_args.dtype) == str(candle.f64) t_new_other_kwargs = t.to(other=other) assert str(t_new_other_kwargs.dtype) == str(candle.f64) @pytest.mark.skipif(not cuda_is_available(), reason="CUDA is not available") def test_tensor_can_be_moved_via_to(): t = Tensor(42.0) assert t.device == "cpu" t_new_args = t.to("cuda") assert t_new_args.device == "cuda" t_new_kwargs = t.to(device="cuda") assert t_new_kwargs.device == "cuda" pytest.raises(TypeError, lambda: t.to("not a device")) pytest.raises(TypeError, lambda: t.to(device="not a device")) pytest.raises(TypeError, lambda: t.to("cuda", "not a device")) pytest.raises(TypeError, lambda: t.to()) pytest.raises(ValueError, lambda: t.to("cuda", device="cpu")) pytest.raises(ValueError, lambda: t.to("cuda", "cuda")) other = Tensor(42.0).to("cuda") t_new_other_args = t.to(other) assert t_new_other_args.device == "cuda" t_new_other_kwargs = t.to(other=other) assert t_new_other_kwargs.device == "cuda" @pytest.mark.skipif(not cuda_is_available(), reason="CUDA is not available") def test_tensor_can_be_moved_and_cast_via_to(): t = Tensor(42.0) assert t.device == "cpu" assert str(t.dtype) == str(candle.f32) t_new_args = t.to("cuda", candle.f64) assert t_new_args.device == "cuda" assert str(t_new_args.dtype) == str(candle.f64) t_new_kwargs = t.to(device="cuda", dtype=candle.f64) assert t_new_kwargs.device == "cuda" assert str(t_new_kwargs.dtype) == str(candle.f64) other = Tensor(42.0).to("cuda").to(candle.f64) t_new_other_args = t.to(other) assert t_new_other_args.device == "cuda" assert str(t_new_other_args.dtype) == str(candle.f64) t_new_other_kwargs = t.to(other=other) assert t_new_other_kwargs.device == "cuda" assert str(t_new_other_kwargs.dtype) == str(candle.f64) def test_tensor_can_be_added(): t = Tensor(42.0) result = t + t assert result.values() == 84.0 result = t + 2.0 assert result.values() == 44.0 a = candle.rand((3, 1, 4)) b = candle.rand((2, 1)) c_native = a.broadcast_add(b) c = a + b assert c.shape == (3, 2, 4) assert c.values() == c_native.values() with pytest.raises(ValueError): d = candle.rand((3, 4, 5)) e = candle.rand((4, 6)) f = d + e def test_tensor_can_be_subtracted(): t = Tensor(42.0) result = t - t assert result.values() == 0 result = t - 2.0 assert result.values() == 40.0 a = candle.rand((3, 1, 4)) b = candle.rand((2, 1)) c_native = a.broadcast_sub(b) c = a - b assert c.shape == (3, 2, 4) assert c.values() == c_native.values() with pytest.raises(ValueError): d = candle.rand((3, 4, 5)) e = candle.rand((4, 6)) f = d - e def test_tensor_can_be_multiplied(): t = Tensor(42.0) result = t * t assert result.values() == 1764.0 result = t * 2.0 assert result.values() == 84.0 a = candle.rand((3, 1, 4)) b = candle.rand((2, 1)) c_native = a.broadcast_mul(b) c = a * b assert c.shape == (3, 2, 4) assert c.values() == c_native.values() with pytest.raises(ValueError): d = candle.rand((3, 4, 5)) e = candle.rand((4, 6)) f = d * e def test_tensor_can_be_divided(): t = Tensor(42.0) result = t / t assert result.values() == 1.0 result = t / 2.0 assert result.values() == 21.0 a = candle.rand((3, 1, 4)) b = candle.rand((2, 1)) c_native = a.broadcast_div(b) c = a / b assert c.shape == (3, 2, 4) assert c.values() == c_native.values() with pytest.raises(ValueError): d = candle.rand((3, 4, 5)) e = candle.rand((4, 6)) f = d / e
candle/candle-pyo3/tests/native/test_tensor.py/0
{ "file_path": "candle/candle-pyo3/tests/native/test_tensor.py", "repo_id": "candle", "token_count": 4688 }
55
//! Contrastive Language-Image Pre-Training //! //! Contrastive Language-Image Pre-Training (CLIP) is an architecture trained on //! pairs of images with related texts. //! //! - 💻 [GH Link](https://github.com/openai/CLIP) //! - 💻 Transformers Python [reference implementation](https://github.com/huggingface/transformers/tree/f6fa0f0bf0796ac66f201f23bdb8585de1609add/src/transformers/models/clip) //! - 🤗 [HF Model](https://huggingface.co/openai/clip-vit-large-patch14-336) //! use self::{ text_model::{Activation, ClipTextTransformer}, vision_model::ClipVisionTransformer, }; use candle::{Result, Tensor, D}; pub mod text_model; pub mod vision_model; #[derive(Clone, Debug)] pub struct ClipModel { text_model: ClipTextTransformer, vision_model: ClipVisionTransformer, visual_projection: candle_nn::Linear, text_projection: candle_nn::Linear, logit_scale: Tensor, } #[derive(Clone, Debug)] pub enum EncoderConfig { Text(text_model::ClipTextConfig), Vision(vision_model::ClipVisionConfig), } impl EncoderConfig { pub fn embed_dim(&self) -> usize { match self { Self::Text(c) => c.embed_dim, Self::Vision(c) => c.embed_dim, } } pub fn num_attention_heads(&self) -> usize { match self { Self::Text(c) => c.num_attention_heads, Self::Vision(c) => c.num_attention_heads, } } pub fn intermediate_size(&self) -> usize { match self { Self::Text(c) => c.intermediate_size, Self::Vision(c) => c.intermediate_size, } } pub fn num_hidden_layers(&self) -> usize { match self { Self::Text(c) => c.num_hidden_layers, Self::Vision(c) => c.num_hidden_layers, } } pub fn activation(&self) -> Activation { match self { Self::Text(_c) => Activation::QuickGelu, Self::Vision(c) => c.activation, } } } #[derive(Clone, Debug)] pub struct ClipConfig { pub text_config: text_model::ClipTextConfig, pub vision_config: vision_model::ClipVisionConfig, pub logit_scale_init_value: f32, pub image_size: usize, } impl ClipConfig { // base image size is 224, model size is 600Mb pub fn vit_base_patch32() -> Self { let text_config = text_model::ClipTextConfig::vit_base_patch32(); let vision_config = vision_model::ClipVisionConfig::vit_base_patch32(); Self { text_config, vision_config, logit_scale_init_value: 2.6592, image_size: 224, } } } impl ClipModel { pub fn new(vs: candle_nn::VarBuilder, c: &ClipConfig) -> Result<Self> { let text_model = ClipTextTransformer::new(vs.pp("text_model"), &c.text_config)?; let vision_model = ClipVisionTransformer::new(vs.pp("vision_model"), &c.vision_config)?; let visual_projection = candle_nn::linear_no_bias( c.vision_config.embed_dim, c.vision_config.projection_dim, vs.pp("visual_projection"), )?; let text_projection = candle_nn::linear_no_bias( c.text_config.embed_dim, c.text_config.projection_dim, vs.pp("text_projection"), )?; // originally nn.Parameter let logit_scale = if vs.contains_tensor("logit_scale") { vs.get(&[], "logit_scale")? } else { Tensor::new(&[c.logit_scale_init_value], vs.device())? }; Ok(Self { text_model, vision_model, visual_projection, text_projection, logit_scale, }) } pub fn get_text_features(&self, input_ids: &Tensor) -> Result<Tensor> { input_ids .apply(&self.text_model)? .apply(&self.text_projection) } pub fn get_image_features(&self, pixel_values: &Tensor) -> Result<Tensor> { pixel_values .apply(&self.vision_model)? .apply(&self.visual_projection) } pub fn forward(&self, pixel_values: &Tensor, input_ids: &Tensor) -> Result<(Tensor, Tensor)> { let image_features = self.get_image_features(pixel_values)?; let text_features = self.get_text_features(input_ids)?; let image_features_normalized = div_l2_norm(&image_features)?; let text_features_normalized = div_l2_norm(&text_features)?; let logits_per_text = text_features_normalized.matmul(&image_features_normalized.t()?)?; let logit_scale = self.logit_scale.exp()?; let logits_per_text = logits_per_text.broadcast_mul(&logit_scale)?; let logits_per_image = logits_per_text.t()?; Ok((logits_per_text, logits_per_image)) } } pub fn div_l2_norm(v: &Tensor) -> Result<Tensor> { let l2_norm = v.sqr()?.sum_keepdim(D::Minus1)?.sqrt()?; v.broadcast_div(&l2_norm) }
candle/candle-transformers/src/models/clip/mod.rs/0
{ "file_path": "candle/candle-transformers/src/models/clip/mod.rs", "repo_id": "candle", "token_count": 2243 }
56
//! EfficientViT (MSRA) inference implementation based on timm. //! //! This crate provides an implementation of the EfficientViT model from Microsoft Research Asia //! for efficient image classification. The model uses cascaded group attention modules //! to achieve strong performance while maintaining low memory usage. //! //! The model was originally described in the paper: //! ["EfficientViT: Memory Efficient Vision Transformer with Cascaded Group Attention"](https://arxiv.org/abs/2305.07027) //! //! This implementation is based on the reference implementation from //! [pytorch-image-models](https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/efficientvit_msra.py). //! //! # Example Usage //! //! This candle implementation uses a pre-trained EfficientViT (from Microsoft Research Asia) network for inference. //! The classification head has been trained on the ImageNet dataset and returns the probabilities for the top-5 classes. //! //! //! ```bash //! cargo run //! --example efficientvit \ //! --release -- \ //! --image candle-examples/examples/yolo-v8/assets/bike.jpg --which m1 //! //! > loaded image Tensor[dims 3, 224, 224; f32] //! > model built //! > mountain bike, all-terrain bike, off-roader: 69.80% //! > unicycle, monocycle : 13.03% //! > bicycle-built-for-two, tandem bicycle, tandem: 9.28% //! > crash helmet : 2.25% //! > alp : 0.46% //! ``` //! //! <div align=center> //! <img src="https://github.com/huggingface/candle/raw/main/candle-examples/examples/yolo-v8/assets/bike.jpg" alt="" width=640> //! </div> //! use candle::{Result, Tensor, D}; use candle_nn::{ batch_norm, conv2d, conv2d_no_bias, linear, ops::sigmoid, ops::softmax, Conv2dConfig, Func, VarBuilder, }; #[derive(Clone)] pub struct Config { channels: [usize; 3], blocks: [usize; 3], heads: [usize; 3], kernels: [usize; 4], } impl Config { pub fn m0() -> Self { Self { channels: [64, 128, 192], blocks: [1, 2, 3], heads: [4, 4, 4], kernels: [5, 5, 5, 5], } } pub fn m1() -> Self { Self { channels: [128, 144, 192], blocks: [1, 2, 3], heads: [2, 3, 3], kernels: [7, 5, 3, 3], } } pub fn m2() -> Self { Self { channels: [128, 192, 224], blocks: [1, 2, 3], heads: [4, 3, 2], kernels: [7, 5, 3, 3], } } pub fn m3() -> Self { Self { channels: [128, 240, 320], blocks: [1, 2, 3], heads: [4, 3, 4], kernels: [5, 5, 5, 5], } } pub fn m4() -> Self { Self { channels: [128, 256, 384], blocks: [1, 2, 3], heads: [4, 4, 4], kernels: [7, 5, 3, 3], } } pub fn m5() -> Self { Self { channels: [192, 288, 384], blocks: [1, 3, 4], heads: [3, 3, 4], kernels: [7, 5, 3, 3], } } } fn efficientvit_stemblock( in_channels: usize, out_channels: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { stride: 2, padding: 1, ..Default::default() }; let bn = batch_norm(out_channels, 1e-5, vb.pp("bn"))?; let conv = conv2d_no_bias(in_channels, out_channels, 3, conv2d_cfg, vb.pp("conv"))?; Ok(Func::new(move |xs| { let xs = xs.apply(&conv)?.apply_t(&bn, false)?; Ok(xs) })) } fn efficientvit_stem(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let conv1 = efficientvit_stemblock(3, dim / 8, vb.pp("conv1"))?; let conv2 = efficientvit_stemblock(dim / 8, dim / 4, vb.pp("conv2"))?; let conv3 = efficientvit_stemblock(dim / 4, dim / 2, vb.pp("conv3"))?; let conv4 = efficientvit_stemblock(dim / 2, dim, vb.pp("conv4"))?; Ok(Func::new(move |xs| { let xs = xs .apply(&conv1)? .relu()? .apply(&conv2)? .relu()? .apply(&conv3)? .relu()? .apply(&conv4)?; Ok(xs) })) } fn depthwise_conv( channels: usize, kernel: usize, stride: usize, padding: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { stride, padding, groups: channels, ..Default::default() }; let bn = batch_norm(channels, 1e-5, vb.pp("bn"))?; let conv = conv2d_no_bias(channels, channels, kernel, conv2d_cfg, vb.pp("conv"))?; Ok(Func::new(move |xs| xs.apply(&conv)?.apply_t(&bn, false))) } fn pointwise_conv( in_channels: usize, out_channels: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { ..Default::default() }; let bn = batch_norm(out_channels, 1e-5, vb.pp("bn"))?; let conv = conv2d_no_bias(in_channels, out_channels, 1, conv2d_cfg, vb.pp("conv"))?; Ok(Func::new(move |xs| xs.apply(&conv)?.apply_t(&bn, false))) } fn conv_mlp(in_channels: usize, out_channels: usize, vb: VarBuilder) -> Result<Func<'static>> { let pw1 = pointwise_conv(in_channels, out_channels, vb.pp("pw1"))?; let pw2 = pointwise_conv(out_channels, in_channels, vb.pp("pw2"))?; Ok(Func::new(move |xs| { let xs = xs.apply(&pw1)?.relu()?.apply(&pw2)?; Ok(xs) })) } // Fixed per-stage resolutions const RESOLUTIONS: [usize; 3] = [14, 7, 4]; // Attention block fn efficientvit_attn( cfg: &Config, stage: usize, in_channels: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let cga = cascaded_group_attn(cfg, stage, in_channels, vb)?; Ok(Func::new(move |xs| { let mut xs = xs.clone(); let (b, c, h, w) = xs.dims4()?; let win_res = 7; // Fixed window resolution let pad_b = (win_res - h % win_res) % win_res; let pad_r = (win_res - w % win_res) % win_res; let ph = h + pad_b; let pw = w + pad_r; let nh = ph / win_res; let nw = pw / win_res; if RESOLUTIONS[stage] > win_res { xs = xs.permute((0, 2, 3, 1))?; xs = xs.pad_with_zeros(D::Minus1, 0, pad_r)?; xs = xs.pad_with_zeros(D::Minus2, 0, pad_b)?; xs = xs .reshape((b, nh, win_res, nw, win_res, c))? .transpose(2, 3)?; xs = xs .reshape((b * nh * nw, win_res, win_res, c))? .permute((0, 3, 1, 2))?; } xs = xs.apply(&cga)?; if RESOLUTIONS[stage] > win_res { xs = xs .permute((0, 2, 3, 1))? .reshape((b, nh, nw, win_res, win_res, c))?; xs = xs.transpose(2, 3)?.reshape((b, ph, pw, c))?; xs = xs.permute((0, 3, 1, 2))?; } Ok(xs) })) } // Cascaded group attention fn cascaded_group_attn( cfg: &Config, stage: usize, in_channels: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let heads = cfg.heads[stage]; let key_dim = 16; let val_dim = in_channels / heads; let scale = (key_dim as f64).powf(-0.5); let mut dws = Vec::with_capacity(heads); let mut qkvs = Vec::with_capacity(heads); for i in 0..heads { dws.push(depthwise_conv( key_dim, cfg.kernels[i], 1, cfg.kernels[i] / 2, vb.pp(format!("dws.{i}")), )?); qkvs.push(pointwise_conv( in_channels / heads, in_channels / heads + 2 * key_dim, vb.pp(format!("qkvs.{i}")), )?); } let proj = pointwise_conv(in_channels, in_channels, vb.pp("proj.1"))?; Ok(Func::new(move |xs| { let (b, _, h, w) = xs.dims4()?; let feats_in = xs.chunk(heads, 1)?; let mut feats_out = Vec::with_capacity(heads); let mut feat = feats_in[0].clone(); for i in 0..heads { if i > 0 { feat = (&feat + &feats_in[i])?; } feat = feat.apply(&qkvs[i])?; let res = feat.reshape((b, (), h, w))?; let q = res.narrow(1, 0, key_dim)?; let k = res.narrow(1, key_dim, key_dim)?; let v = res.narrow(1, 2 * key_dim, val_dim)?; let q = q.apply(&dws[i])?; let q = q.flatten_from(2)?; let k = k.flatten_from(2)?; let v = v.flatten_from(2)?; let q = (q * scale)?; let att = q.transpose(D::Minus2, D::Minus1)?.matmul(&k)?; let att = softmax(&att, D::Minus1)?; feat = v.matmul(&att.transpose(D::Minus2, D::Minus1)?)?; feat = feat.reshape((b, val_dim, h, w))?; feats_out.push(feat.clone()); } let xs = Tensor::cat(&feats_out, 1)?; let xs = xs.relu()?.apply(&proj)?; Ok(xs) })) } // Used by the downsampling layer fn squeeze_and_excitation( in_channels: usize, squeeze_channels: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { ..Default::default() }; let fc1 = conv2d(in_channels, squeeze_channels, 1, conv2d_cfg, vb.pp("fc1"))?; let fc2 = conv2d(squeeze_channels, in_channels, 1, conv2d_cfg, vb.pp("fc2"))?; Ok(Func::new(move |xs| { let residual = xs; let xs = xs.mean_keepdim(D::Minus2)?.mean_keepdim(D::Minus1)?; let xs = sigmoid(&xs.apply(&fc1)?.relu()?.apply(&fc2)?)?; residual.broadcast_mul(&xs) })) } // Used by the downsampling layer fn patchmerge(in_channels: usize, out_channels: usize, vb: VarBuilder) -> Result<Func<'static>> { let dim = in_channels; let hid_dim = in_channels * 4; let conv1 = pointwise_conv(dim, hid_dim, vb.pp("conv1"))?; let conv2 = depthwise_conv(hid_dim, 3, 2, 1, vb.pp("conv2"))?; let conv3 = pointwise_conv(hid_dim, out_channels, vb.pp("conv3"))?; let se = squeeze_and_excitation(hid_dim, hid_dim / 4, vb.pp("se"))?; Ok(Func::new(move |xs| { let xs = xs .apply(&conv1)? .relu()? .apply(&conv2)? .relu()? .apply(&se)? .apply(&conv3)?; Ok(xs) })) } // Used by the downsampling layer fn res(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let dw = depthwise_conv(dim, 3, 1, 1, vb.pp("0.m"))?; let mlp = conv_mlp(dim, dim * 2, vb.pp("1.m"))?; Ok(Func::new(move |xs| { let mut xs = xs.clone(); xs = (&xs + &xs.apply(&dw)?)?; xs = (&xs + &xs.apply(&mlp)?)?; Ok(xs) })) } // Downsampling fn efficientvit_downsample( in_channels: usize, out_channels: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let res1 = res(in_channels, vb.pp("res1"))?; let res2 = res(out_channels, vb.pp("res2"))?; let patchmerge = patchmerge(in_channels, out_channels, vb.pp("patchmerge"))?; Ok(Func::new(move |xs| { let xs = xs.apply(&res1)?.apply(&patchmerge)?.apply(&res2)?; Ok(xs) })) } fn efficientvit_block( cfg: &Config, stage: usize, dim: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let dw0 = depthwise_conv(dim, 3, 1, 1, vb.pp("dw0.m"))?; let dw1 = depthwise_conv(dim, 3, 1, 1, vb.pp("dw1.m"))?; let ffn0 = conv_mlp(dim, dim * 2, vb.pp("ffn0.m"))?; let ffn1 = conv_mlp(dim, dim * 2, vb.pp("ffn1.m"))?; let attn = efficientvit_attn(cfg, stage, dim, vb.pp("mixer.m.attn"))?; Ok(Func::new(move |xs| { let mut xs = xs.clone(); xs = (&xs + &xs.apply(&dw0)?)?; xs = (&xs + &xs.apply(&ffn0)?)?; xs = (&xs + &xs.apply(&attn)?)?; xs = (&xs + &xs.apply(&dw1)?)?; xs = (&xs + &xs.apply(&ffn1)?)?; Ok(xs) })) } // Each stage is made of blocks. There is a downsampling layer between stages. fn efficientvit_stage(cfg: &Config, stage: usize, vb: VarBuilder) -> Result<Func<'static>> { let nblocks = cfg.blocks[stage]; let mut blocks = Vec::with_capacity(nblocks + 1); let in_channels = if stage > 0 { cfg.channels[stage - 1] } else { cfg.channels[0] }; let out_channels = cfg.channels[stage]; if stage > 0 { blocks.push(efficientvit_downsample( in_channels, out_channels, vb.pp("downsample"), )?); } for i in 0..nblocks { blocks.push(efficientvit_block( cfg, stage, out_channels, vb.pp(format!("blocks.{i}")), )?); } Ok(Func::new(move |xs| { let mut xs = xs.clone(); for block in blocks.iter() { xs = xs.apply(block)? } Ok(xs) })) } // Classification head. fn efficientvit_head(outputs: usize, nclasses: usize, vb: VarBuilder) -> Result<Func<'static>> { let norm = batch_norm(outputs, 1e-6, vb.pp("bn"))?; let linear = linear(outputs, nclasses, vb.pp("linear"))?; Ok(Func::new(move |xs| { xs.apply_t(&norm, false)?.apply(&linear) })) } // Build a efficientvit model for a given configuration. fn efficientvit_model( config: &Config, nclasses: Option<usize>, vb: VarBuilder, ) -> Result<Func<'static>> { let cls = match nclasses { None => None, Some(nclasses) => { let outputs = config.channels[2]; let head = efficientvit_head(outputs, nclasses, vb.pp("head"))?; Some(head) } }; let stem_dim = config.channels[0]; let stem = efficientvit_stem(stem_dim, vb.pp("patch_embed"))?; let vb = vb.pp("stages"); let stage1 = efficientvit_stage(config, 0, vb.pp(0))?; let stage2 = efficientvit_stage(config, 1, vb.pp(1))?; let stage3 = efficientvit_stage(config, 2, vb.pp(2))?; Ok(Func::new(move |xs| { let xs = xs .apply(&stem)? .apply(&stage1)? .apply(&stage2)? .apply(&stage3)? .mean(D::Minus2)? .mean(D::Minus1)?; match &cls { None => Ok(xs), Some(cls) => xs.apply(cls), } })) } pub fn efficientvit(cfg: &Config, nclasses: usize, vb: VarBuilder) -> Result<Func<'static>> { efficientvit_model(cfg, Some(nclasses), vb) } pub fn efficientvit_no_final_layer(cfg: &Config, vb: VarBuilder) -> Result<Func<'static>> { efficientvit_model(cfg, None, vb) }
candle/candle-transformers/src/models/efficientvit.rs/0
{ "file_path": "candle/candle-transformers/src/models/efficientvit.rs", "repo_id": "candle", "token_count": 7414 }
57
//! Helium inference implementation. //! //! See the model card on Hugging Face's [hub](https://huggingface.co/kmhf/helium-2b). use super::with_tracing::{linear_b as linear, Linear, RmsNorm}; use candle::{DType, Device, Result, Tensor, D}; use candle_nn::{Module, VarBuilder}; use std::sync::Arc; fn default_use_flash_attn() -> bool { false } #[derive(Debug, Clone, serde::Deserialize)] pub struct Config { pub attention_bias: bool, pub bos_token_id: u32, pub eos_token_id: u32, pub head_dim: usize, pub hidden_act: candle_nn::Activation, pub hidden_size: usize, pub intermediate_size: usize, pub max_position_embeddings: usize, pub mlp_bias: bool, pub num_attention_heads: usize, pub num_hidden_layers: usize, pub num_key_value_heads: usize, pub rms_norm_eps: f64, pub rope_theta: f64, pub tie_word_embeddings: bool, pub vocab_size: usize, #[serde(default = "default_use_flash_attn")] pub use_flash_attn: bool, } impl Config { pub fn config_2b(use_flash_attn: bool) -> Self { Self { attention_bias: false, bos_token_id: 1, eos_token_id: 2, head_dim: 128, hidden_act: candle_nn::Activation::Silu, hidden_size: 2560, intermediate_size: 7040, max_position_embeddings: 4096, mlp_bias: false, num_attention_heads: 20, num_hidden_layers: 24, num_key_value_heads: 20, rms_norm_eps: 1e-08, rope_theta: 100000.0, tie_word_embeddings: false, vocab_size: 48000, use_flash_attn, } } } #[derive(Debug, Clone)] struct RotaryEmbedding { sin: Tensor, cos: Tensor, } impl RotaryEmbedding { fn new(dtype: DType, cfg: &Config, dev: &Device) -> Result<Self> { let rope_theta = cfg.rope_theta as f32; let dim = cfg.head_dim; let max_seq_len = cfg.max_position_embeddings; let inv_freq: Vec<_> = (0..dim) .step_by(2) .map(|i| 1f32 / rope_theta.powf(i as f32 / dim as f32)) .collect(); let inv_freq_len = inv_freq.len(); let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(DType::F32)?; let t = Tensor::arange(0u32, max_seq_len as u32, dev)? .to_dtype(DType::F32)? .reshape((max_seq_len, 1))?; let freqs = t.matmul(&inv_freq)?; Ok(Self { sin: freqs.sin()?.to_dtype(dtype)?, cos: freqs.cos()?.to_dtype(dtype)?, }) } fn apply_rotary_emb_qkv( &self, q: &Tensor, k: &Tensor, seqlen_offset: usize, ) -> Result<(Tensor, Tensor)> { let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?; let cos = self.cos.narrow(0, seqlen_offset, seq_len)?; let sin = self.sin.narrow(0, seqlen_offset, seq_len)?; let q_embed = candle_nn::rotary_emb::rope_i(q, &cos, &sin)?; let k_embed = candle_nn::rotary_emb::rope_i(k, &cos, &sin)?; Ok((q_embed, k_embed)) } } #[derive(Debug, Clone)] #[allow(clippy::upper_case_acronyms)] struct MLP { gate_proj: Linear, up_proj: Linear, down_proj: Linear, act_fn: candle_nn::Activation, } impl MLP { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let hidden_sz = cfg.hidden_size; let intermediate_sz = cfg.intermediate_size; let bias = cfg.mlp_bias; let gate_proj = linear(hidden_sz, intermediate_sz, bias, vb.pp("gate_proj"))?; let up_proj = linear(hidden_sz, intermediate_sz, bias, vb.pp("up_proj"))?; let down_proj = linear(intermediate_sz, hidden_sz, bias, vb.pp("down_proj"))?; Ok(Self { gate_proj, up_proj, down_proj, act_fn: cfg.hidden_act, }) } } impl Module for MLP { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let lhs = xs.apply(&self.gate_proj)?.apply(&self.act_fn)?; let rhs = xs.apply(&self.up_proj)?; (lhs * rhs)?.apply(&self.down_proj) } } #[cfg(feature = "flash-attn")] fn flash_attn( q: &Tensor, k: &Tensor, v: &Tensor, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { candle_flash_attn::flash_attn(q, k, v, softmax_scale, causal) } #[cfg(not(feature = "flash-attn"))] fn flash_attn(_: &Tensor, _: &Tensor, _: &Tensor, _: f32, _: bool) -> Result<Tensor> { unimplemented!("compile with '--features flash-attn'") } #[derive(Debug, Clone)] struct Attention { q_proj: Linear, k_proj: Linear, v_proj: Linear, o_proj: Linear, num_heads: usize, num_kv_heads: usize, num_kv_groups: usize, head_dim: usize, rotary_emb: Arc<RotaryEmbedding>, kv_cache: Option<(Tensor, Tensor)>, use_flash_attn: bool, } impl Attention { fn new(rotary_emb: Arc<RotaryEmbedding>, cfg: &Config, vb: VarBuilder) -> Result<Self> { let hidden_sz = cfg.hidden_size; let num_heads = cfg.num_attention_heads; let num_kv_heads = cfg.num_key_value_heads; let num_kv_groups = num_heads / num_kv_heads; let head_dim = cfg.head_dim; let bias = cfg.attention_bias; let q_proj = linear(hidden_sz, num_heads * head_dim, bias, vb.pp("q_proj"))?; let k_proj = linear(hidden_sz, num_kv_heads * head_dim, bias, vb.pp("k_proj"))?; let v_proj = linear(hidden_sz, num_kv_heads * head_dim, bias, vb.pp("v_proj"))?; let o_proj = linear(num_heads * head_dim, hidden_sz, bias, vb.pp("o_proj"))?; Ok(Self { q_proj, k_proj, v_proj, o_proj, num_heads, num_kv_heads, num_kv_groups, head_dim, rotary_emb, kv_cache: None, use_flash_attn: cfg.use_flash_attn, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let (b_sz, q_len, _) = xs.dims3()?; let query_states = self.q_proj.forward(xs)?; let key_states = self.k_proj.forward(xs)?; let value_states = self.v_proj.forward(xs)?; let query_states = query_states .reshape((b_sz, q_len, self.num_heads, self.head_dim))? .transpose(1, 2)? .contiguous()?; let key_states = key_states .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))? .transpose(1, 2)? .contiguous()?; let value_states = value_states .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))? .transpose(1, 2)? .contiguous()?; let (query_states, key_states) = self.rotary_emb .apply_rotary_emb_qkv(&query_states, &key_states, seqlen_offset)?; let (key_states, value_states) = match &self.kv_cache { None => (key_states, value_states), Some((prev_k, prev_v)) => { let key_states = Tensor::cat(&[prev_k, &key_states], 2)?; let value_states = Tensor::cat(&[prev_v, &value_states], 2)?; (key_states, value_states) } }; self.kv_cache = Some((key_states.clone(), value_states.clone())); let key_states = crate::utils::repeat_kv(key_states, self.num_kv_groups)?; let value_states = crate::utils::repeat_kv(value_states, self.num_kv_groups)?; let attn_output = if self.use_flash_attn { // flash-attn expects (b_sz, seq_len, nheads, head_dim) let q = query_states.transpose(1, 2)?; let k = key_states.transpose(1, 2)?; let v = value_states.transpose(1, 2)?; let softmax_scale = 1f32 / (self.head_dim as f32).sqrt(); flash_attn(&q, &k, &v, softmax_scale, q_len > 1)?.transpose(1, 2)? } else { let scale = 1f64 / f64::sqrt(self.head_dim as f64); let attn_weights = (query_states.matmul(&key_states.transpose(2, 3)?)? * scale)?; let attn_weights = match attention_mask { None => attn_weights, Some(mask) => attn_weights.broadcast_add(mask)?, }; let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?; attn_weights.matmul(&value_states)? }; attn_output .transpose(1, 2)? .reshape((b_sz, q_len, self.num_heads * self.head_dim))? .apply(&self.o_proj) } fn clear_kv_cache(&mut self) { self.kv_cache = None } } #[derive(Debug, Clone)] struct DecoderLayer { self_attn: Attention, mlp: MLP, input_layernorm: RmsNorm, post_attention_layernorm: RmsNorm, } impl DecoderLayer { fn new(rotary_emb: Arc<RotaryEmbedding>, cfg: &Config, vb: VarBuilder) -> Result<Self> { let self_attn = Attention::new(rotary_emb, cfg, vb.pp("self_attn"))?; let mlp = MLP::new(cfg, vb.pp("mlp"))?; let input_layernorm = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("input_layernorm"))?; let post_attention_layernorm = RmsNorm::new( cfg.hidden_size, cfg.rms_norm_eps, vb.pp("post_attention_layernorm"), )?; Ok(Self { self_attn, mlp, input_layernorm, post_attention_layernorm, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let residual = xs; let xs = self.input_layernorm.forward(xs)?; let xs = self.self_attn.forward(&xs, attention_mask, seqlen_offset)?; let xs = (xs + residual)?; let residual = &xs; let xs = xs.apply(&self.post_attention_layernorm)?.apply(&self.mlp)?; residual + xs } fn clear_kv_cache(&mut self) { self.self_attn.clear_kv_cache() } } #[derive(Debug, Clone)] pub struct Model { embed_tokens: candle_nn::Embedding, layers: Vec<DecoderLayer>, norm: RmsNorm, lm_head: Linear, device: Device, dtype: DType, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vb_m = vb.pp("model"); let embed_tokens = candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?; let rotary_emb = Arc::new(RotaryEmbedding::new(vb.dtype(), cfg, vb_m.device())?); let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb_l = vb_m.pp("layers"); for layer_idx in 0..cfg.num_hidden_layers { let layer = DecoderLayer::new(rotary_emb.clone(), cfg, vb_l.pp(layer_idx))?; layers.push(layer) } let norm = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb_m.pp("norm"))?; let lm_head = if cfg.tie_word_embeddings { Linear::from_weights(embed_tokens.embeddings().clone(), None) } else { linear(cfg.hidden_size, cfg.vocab_size, false, vb.pp("lm_head"))? }; Ok(Self { embed_tokens, layers, norm, lm_head, device: vb.device().clone(), dtype: vb.dtype(), }) } fn prepare_decoder_attention_mask( &self, tgt_len: usize, seqlen_offset: usize, ) -> Result<Tensor> { let mask: Vec<_> = (0..tgt_len) .flat_map(|i| (0..tgt_len).map(move |j| if i < j { f32::NEG_INFINITY } else { 0. })) .collect(); let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?; let mask = if seqlen_offset > 0 { let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?; Tensor::cat(&[&mask0, &mask], D::Minus1)? } else { mask }; mask.expand((1, 1, tgt_len, tgt_len + seqlen_offset))? .to_dtype(self.dtype) } pub fn embed_tokens(&self) -> &candle_nn::Embedding { &self.embed_tokens } pub fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> { let (_b_size, seq_len) = input_ids.dims2()?; let attention_mask = if seq_len <= 1 { None } else { let mask = self.prepare_decoder_attention_mask(seq_len, seqlen_offset)?; Some(mask) }; let mut xs = self.embed_tokens.forward(input_ids)?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)? } xs.narrow(1, seq_len - 1, 1)? .apply(&self.norm)? .apply(&self.lm_head) } pub fn clear_kv_cache(&mut self) { for layer in self.layers.iter_mut() { layer.clear_kv_cache() } } }
candle/candle-transformers/src/models/helium.rs/0
{ "file_path": "candle/candle-transformers/src/models/helium.rs", "repo_id": "candle", "token_count": 6786 }
58
// Copyright (c) Kyutai, all rights reserved. // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. use candle::{streaming, Module, Result, StreamTensor, StreamingModule, Tensor}; use candle_nn::VarBuilder; use super::conv::{StreamableConv1d, StreamableConvTranspose1d}; #[derive(Debug, Clone)] pub struct Config { pub dimension: usize, pub channels: usize, pub causal: bool, pub n_filters: usize, pub n_residual_layers: usize, pub ratios: Vec<usize>, pub activation: candle_nn::Activation, pub norm: super::conv::Norm, pub kernel_size: usize, pub residual_kernel_size: usize, pub last_kernel_size: usize, pub dilation_base: usize, pub pad_mode: super::conv::PadMode, pub true_skip: bool, pub compress: usize, pub lstm: usize, pub disable_norm_outer_blocks: usize, pub final_activation: Option<candle_nn::Activation>, } #[derive(Debug, Clone)] pub struct SeaNetResnetBlock { block: Vec<StreamableConv1d>, shortcut: Option<StreamableConv1d>, activation: candle_nn::Activation, skip_op: candle::StreamingBinOp, span: tracing::Span, } impl SeaNetResnetBlock { #[allow(clippy::too_many_arguments)] pub fn new( dim: usize, k_sizes_and_dilations: &[(usize, usize)], activation: candle_nn::Activation, norm: Option<super::conv::Norm>, causal: bool, pad_mode: super::conv::PadMode, compress: usize, true_skip: bool, vb: VarBuilder, ) -> Result<Self> { let mut block = Vec::with_capacity(k_sizes_and_dilations.len()); let hidden = dim / compress; let vb_b = vb.pp("block"); for (i, (k_size, dilation)) in k_sizes_and_dilations.iter().enumerate() { let in_c = if i == 0 { dim } else { hidden }; let out_c = if i == k_sizes_and_dilations.len() - 1 { dim } else { hidden }; let c = StreamableConv1d::new( in_c, out_c, /* k_size */ *k_size, /* stride */ 1, /* dilation */ *dilation, /* groups */ 1, /* bias */ true, /* causal */ causal, /* norm */ norm, /* pad_mode */ pad_mode, vb_b.pp(2 * i + 1), )?; block.push(c) } let shortcut = if true_skip { None } else { let c = StreamableConv1d::new( dim, dim, /* k_size */ 1, /* stride */ 1, /* dilation */ 1, /* groups */ 1, /* bias */ true, /* causal */ causal, /* norm */ norm, /* pad_mode */ pad_mode, vb.pp("shortcut"), )?; Some(c) }; Ok(Self { block, shortcut, activation, skip_op: streaming::StreamingBinOp::new(streaming::BinOp::Add, candle::D::Minus1), span: tracing::span!(tracing::Level::TRACE, "sea-resnet"), }) } } impl Module for SeaNetResnetBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let mut ys = xs.clone(); for block in self.block.iter() { ys = ys.apply(&self.activation)?.apply(block)?; } match self.shortcut.as_ref() { None => ys + xs, Some(shortcut) => ys + xs.apply(shortcut), } } } impl StreamingModule for SeaNetResnetBlock { fn reset_state(&mut self) { for block in self.block.iter_mut() { block.reset_state() } if let Some(shortcut) = self.shortcut.as_mut() { shortcut.reset_state() } } fn step(&mut self, xs: &StreamTensor) -> Result<StreamTensor> { let _enter = self.span.enter(); let mut ys = xs.clone(); for block in self.block.iter_mut() { ys = block.step(&ys.apply(&self.activation)?)?; } match self.shortcut.as_ref() { None => self.skip_op.step(&ys, xs), Some(shortcut) => self.skip_op.step(&ys, &xs.apply(shortcut)?), } } } #[derive(Debug, Clone)] struct EncoderLayer { residuals: Vec<SeaNetResnetBlock>, downsample: StreamableConv1d, } #[derive(Debug, Clone)] pub struct SeaNetEncoder { init_conv1d: StreamableConv1d, activation: candle_nn::Activation, layers: Vec<EncoderLayer>, final_conv1d: StreamableConv1d, span: tracing::Span, } impl SeaNetEncoder { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { if cfg.lstm > 0 { candle::bail!("seanet lstm is not supported") } let n_blocks = 2 + cfg.ratios.len(); let mut mult = 1usize; let init_norm = if cfg.disable_norm_outer_blocks >= 1 { None } else { Some(cfg.norm) }; let mut layer_idx = 0; let vb = vb.pp("layers"); let init_conv1d = StreamableConv1d::new( cfg.channels, mult * cfg.n_filters, cfg.kernel_size, /* stride */ 1, /* dilation */ 1, /* groups */ 1, /* bias */ true, /* causal */ cfg.causal, /* norm */ init_norm, /* pad_mode */ cfg.pad_mode, vb.pp(layer_idx), )?; layer_idx += 1; let mut layers = Vec::with_capacity(cfg.ratios.len()); for (i, &ratio) in cfg.ratios.iter().rev().enumerate() { let norm = if cfg.disable_norm_outer_blocks >= i + 2 { None } else { Some(cfg.norm) }; let mut residuals = Vec::with_capacity(cfg.n_residual_layers); for j in 0..cfg.n_residual_layers { let resnet_block = SeaNetResnetBlock::new( mult * cfg.n_filters, &[ (cfg.residual_kernel_size, cfg.dilation_base.pow(j as u32)), (1, 1), ], cfg.activation, norm, cfg.causal, cfg.pad_mode, cfg.compress, cfg.true_skip, vb.pp(layer_idx), )?; residuals.push(resnet_block); layer_idx += 1; } let downsample = StreamableConv1d::new( mult * cfg.n_filters, mult * cfg.n_filters * 2, /* k_size */ ratio * 2, /* stride */ ratio, /* dilation */ 1, /* groups */ 1, /* bias */ true, /* causal */ true, /* norm */ norm, /* pad_mode */ cfg.pad_mode, vb.pp(layer_idx + 1), )?; layer_idx += 2; let layer = EncoderLayer { downsample, residuals, }; layers.push(layer); mult *= 2 } let final_norm = if cfg.disable_norm_outer_blocks >= n_blocks { None } else { Some(cfg.norm) }; let final_conv1d = StreamableConv1d::new( mult * cfg.n_filters, cfg.dimension, cfg.last_kernel_size, /* stride */ 1, /* dilation */ 1, /* groups */ 1, /* bias */ true, /* causal */ cfg.causal, /* norm */ final_norm, /* pad_mode */ cfg.pad_mode, vb.pp(layer_idx + 1), )?; Ok(Self { init_conv1d, activation: cfg.activation, layers, final_conv1d, span: tracing::span!(tracing::Level::TRACE, "sea-encoder"), }) } } impl Module for SeaNetEncoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = xs.apply(&self.init_conv1d)?; for layer in self.layers.iter() { for residual in layer.residuals.iter() { xs = xs.apply(residual)? } xs = xs.apply(&self.activation)?.apply(&layer.downsample)?; } xs.apply(&self.activation)?.apply(&self.final_conv1d) } } impl StreamingModule for SeaNetEncoder { fn reset_state(&mut self) { self.init_conv1d.reset_state(); self.layers.iter_mut().for_each(|v| { v.residuals.iter_mut().for_each(|v| v.reset_state()); v.downsample.reset_state() }); self.final_conv1d.reset_state(); } fn step(&mut self, xs: &StreamTensor) -> Result<StreamTensor> { let _enter = self.span.enter(); let mut xs = self.init_conv1d.step(xs)?; for layer in self.layers.iter_mut() { for residual in layer.residuals.iter_mut() { xs = residual.step(&xs)?; } xs = layer.downsample.step(&xs.apply(&self.activation)?)?; } self.final_conv1d.step(&xs.apply(&self.activation)?) } } #[derive(Debug, Clone)] struct DecoderLayer { upsample: StreamableConvTranspose1d, residuals: Vec<SeaNetResnetBlock>, } #[derive(Debug, Clone)] pub struct SeaNetDecoder { init_conv1d: StreamableConv1d, activation: candle_nn::Activation, layers: Vec<DecoderLayer>, final_conv1d: StreamableConv1d, final_activation: Option<candle_nn::Activation>, span: tracing::Span, } impl SeaNetDecoder { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { if cfg.lstm > 0 { candle::bail!("seanet lstm is not supported") } let n_blocks = 2 + cfg.ratios.len(); let mut mult = 1 << cfg.ratios.len(); let init_norm = if cfg.disable_norm_outer_blocks == n_blocks { None } else { Some(cfg.norm) }; let mut layer_idx = 0; let vb = vb.pp("layers"); let init_conv1d = StreamableConv1d::new( cfg.dimension, mult * cfg.n_filters, cfg.kernel_size, /* stride */ 1, /* dilation */ 1, /* groups */ 1, /* bias */ true, /* causal */ cfg.causal, /* norm */ init_norm, /* pad_mode */ cfg.pad_mode, vb.pp(layer_idx), )?; layer_idx += 1; let mut layers = Vec::with_capacity(cfg.ratios.len()); for (i, &ratio) in cfg.ratios.iter().enumerate() { let norm = if cfg.disable_norm_outer_blocks + i + 1 >= n_blocks { None } else { Some(cfg.norm) }; let upsample = StreamableConvTranspose1d::new( mult * cfg.n_filters, mult * cfg.n_filters / 2, /* k_size */ ratio * 2, /* stride */ ratio, /* groups */ 1, /* bias */ true, /* causal */ true, /* norm */ norm, vb.pp(layer_idx + 1), )?; layer_idx += 2; let mut residuals = Vec::with_capacity(cfg.n_residual_layers); for j in 0..cfg.n_residual_layers { let resnet_block = SeaNetResnetBlock::new( mult * cfg.n_filters / 2, &[ (cfg.residual_kernel_size, cfg.dilation_base.pow(j as u32)), (1, 1), ], cfg.activation, norm, cfg.causal, cfg.pad_mode, cfg.compress, cfg.true_skip, vb.pp(layer_idx), )?; residuals.push(resnet_block); layer_idx += 1; } let layer = DecoderLayer { upsample, residuals, }; layers.push(layer); mult /= 2 } let final_norm = if cfg.disable_norm_outer_blocks >= 1 { None } else { Some(cfg.norm) }; let final_conv1d = StreamableConv1d::new( cfg.n_filters, cfg.channels, cfg.last_kernel_size, /* stride */ 1, /* dilation */ 1, /* groups */ 1, /* bias */ true, /* causal */ cfg.causal, /* norm */ final_norm, /* pad_mode */ cfg.pad_mode, vb.pp(layer_idx + 1), )?; Ok(Self { init_conv1d, activation: cfg.activation, layers, final_conv1d, final_activation: cfg.final_activation, span: tracing::span!(tracing::Level::TRACE, "sea-decoder"), }) } } impl Module for SeaNetDecoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = xs.apply(&self.init_conv1d)?; for layer in self.layers.iter() { xs = xs.apply(&self.activation)?.apply(&layer.upsample)?; for residual in layer.residuals.iter() { xs = xs.apply(residual)? } } let xs = xs.apply(&self.activation)?.apply(&self.final_conv1d)?; let xs = match self.final_activation.as_ref() { None => xs, Some(act) => xs.apply(act)?, }; Ok(xs) } } impl StreamingModule for SeaNetDecoder { fn reset_state(&mut self) { self.init_conv1d.reset_state(); self.layers.iter_mut().for_each(|v| { v.residuals.iter_mut().for_each(|v| v.reset_state()); v.upsample.reset_state() }); self.final_conv1d.reset_state(); } fn step(&mut self, xs: &StreamTensor) -> Result<StreamTensor> { let _enter = self.span.enter(); let mut xs = self.init_conv1d.step(xs)?; for layer in self.layers.iter_mut() { xs = layer.upsample.step(&xs.apply(&self.activation)?)?; for residual in layer.residuals.iter_mut() { xs = residual.step(&xs)?; } } let xs = self.final_conv1d.step(&xs.apply(&self.activation)?)?; let xs = match self.final_activation.as_ref() { None => xs, Some(act) => xs.apply(act)?, }; Ok(xs) } }
candle/candle-transformers/src/models/mimi/seanet.rs/0
{ "file_path": "candle/candle-transformers/src/models/mimi/seanet.rs", "repo_id": "candle", "token_count": 8092 }
59
//! Module implementing the MPT (Multi-Purpose Transformer) model //! //! References: //! - [MPT Model used by replit-code-v1_5-3b](https://huggingface.co/replit/replit-code-v1_5-3b/blob/main/modeling_mpt.py) //! - [Configuration](https://huggingface.co/replit/replit-code-v1_5-3b/blob/main/configuration_mpt.py) //! //! The model uses grouped query attention and alibi positional embeddings. use crate::models::with_tracing::{linear_no_bias, Embedding, Linear}; /// MPT model used by replit-code-v1_5-3b /// https://huggingface.co/replit/replit-code-v1_5-3b/blob/main/modeling_mpt.py use candle::{DType, Device, IndexOp, Module, Result, Tensor, D}; use candle_nn::{layer_norm, LayerNorm, VarBuilder}; // https://huggingface.co/replit/replit-code-v1_5-3b/blob/main/configuration_mpt.py #[derive(Debug, Clone, PartialEq)] pub struct Config { pub(crate) d_model: usize, pub(crate) n_heads: usize, pub(crate) n_layers: usize, pub(crate) expansion_ratio: usize, pub(crate) max_seq_len: usize, pub(crate) vocab_size: usize, pub(crate) kv_n_heads: usize, pub(crate) attn_prefix_lm: bool, pub(crate) attn_alibi: bool, pub(crate) attn_alibi_bias_max: usize, } impl Config { pub fn replit_code_v1_5_3b() -> Self { Self { d_model: 3072, n_heads: 24, n_layers: 32, expansion_ratio: 4, max_seq_len: 4096, vocab_size: 32768, kv_n_heads: 8, attn_prefix_lm: false, attn_alibi: true, attn_alibi_bias_max: 8, } } pub fn is_causal(&self) -> bool { !self.attn_prefix_lm } } #[derive(Debug, Clone)] struct GroupedQueryAttention { wqkv: Linear, out_proj: Linear, kv_cache: Option<(Tensor, Tensor)>, softmax_scale: f64, head_dim: usize, d_model: usize, n_heads: usize, kv_n_heads: usize, attn_bias: Tensor, span: tracing::Span, } impl GroupedQueryAttention { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let head_dim = cfg.d_model / cfg.n_heads; let wqkv_size = cfg.d_model + 2 * cfg.kv_n_heads * head_dim; let wqkv = linear_no_bias(cfg.d_model, wqkv_size, vb.pp("Wqkv"))?; let softmax_scale = 1f64 / (head_dim as f64).sqrt(); let out_proj = linear_no_bias(cfg.d_model, cfg.d_model, vb.pp("out_proj"))?; let attn_bias = build_alibi_bias(cfg)?.to_device(vb.device())?; Ok(Self { wqkv, out_proj, kv_cache: None, softmax_scale, head_dim, d_model: cfg.d_model, n_heads: cfg.n_heads, kv_n_heads: cfg.kv_n_heads, attn_bias, span: tracing::span!(tracing::Level::TRACE, "gqa"), }) } fn forward(&mut self, xs: &Tensor, mask: Option<&Tensor>) -> Result<Tensor> { let _enter = self.span.enter(); let (b_size, seq_len, _n_embd) = xs.dims3()?; let qkv = self.wqkv.forward(xs)?; let query = qkv.narrow(2, 0, self.d_model)?; let kv_size = self.kv_n_heads * self.head_dim; let key = qkv.narrow(2, self.d_model, kv_size)?; let value = qkv.narrow(2, self.d_model + kv_size, kv_size)?; // scaled_multihead_dot_product_attention let query = query .reshape((b_size, seq_len, self.n_heads, ()))? .transpose(1, 2)?; // b,h,s,d let key = key .reshape((b_size, seq_len, self.kv_n_heads, ()))? .permute((0, 2, 3, 1))?; // b,h,d,s let value = value .reshape((b_size, seq_len, self.kv_n_heads, ()))? .transpose(1, 2)?; // b,h,s,d let (key, value) = match &self.kv_cache { None => (key, value), Some((prev_k, prev_v)) => { let k = Tensor::cat(&[prev_k, &key], 3)?; let v = Tensor::cat(&[prev_v, &value], 2)?; (k, v) } }; self.kv_cache = Some((key.clone(), value.clone())); let query = query.contiguous()?; let key = crate::utils::repeat_kv(key, self.n_heads / self.kv_n_heads)?.contiguous()?; let value = crate::utils::repeat_kv(value, self.n_heads / self.kv_n_heads)?.contiguous()?; let attn_weights = (query.matmul(&key)? * self.softmax_scale)?; let attn_bias = { let s_q = query.dim(D::Minus2)?; let s_k = key.dim(D::Minus1)?; let (_, _, a_q, a_k) = self.attn_bias.dims4()?; let start_q = a_q.saturating_sub(s_q); let start_k = a_k.saturating_sub(s_k); self.attn_bias.i((.., .., start_q.., start_k..))? }; let attn_weights = attn_weights.broadcast_add(&attn_bias)?; let attn_weights = match mask { None => attn_weights, Some(mask) => masked_fill( &attn_weights, &mask.broadcast_as(attn_weights.shape())?, f32::NEG_INFINITY, )?, }; let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?; let attn_output = attn_weights .matmul(&value)? .transpose(1, 2)? .flatten_from(D::Minus2)?; let out = attn_output.apply(&self.out_proj)?; Ok(out) } } #[derive(Debug, Clone)] struct Ffn { up_proj: Linear, down_proj: Linear, } impl Ffn { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let hidden = cfg.d_model * cfg.expansion_ratio; let up_proj = linear_no_bias(cfg.d_model, hidden, vb.pp("up_proj"))?; let down_proj = linear_no_bias(hidden, cfg.d_model, vb.pp("down_proj"))?; Ok(Self { up_proj, down_proj }) } } impl Module for Ffn { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.up_proj)?.gelu_erf()?.apply(&self.down_proj) } } #[derive(Debug, Clone)] struct MPTBlock { norm1: LayerNorm, // Do we need the low-precision variant? attn: GroupedQueryAttention, norm2: LayerNorm, ffn: Ffn, } impl MPTBlock { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let ln_cfg = candle_nn::LayerNormConfig { affine: false, ..Default::default() }; let norm1 = layer_norm(cfg.d_model, ln_cfg, vb.pp("norm_1"))?; let norm2 = layer_norm(cfg.d_model, ln_cfg, vb.pp("norm_2"))?; let attn = GroupedQueryAttention::new(cfg, vb.pp("attn"))?; let ffn = Ffn::new(cfg, vb.pp("ffn"))?; Ok(Self { norm1, attn, norm2, ffn, }) } fn forward(&mut self, xs: &Tensor, mask: Option<&Tensor>) -> Result<Tensor> { let residual = xs; let xs = xs.apply(&self.norm1)?; let xs = self.attn.forward(&xs, mask)?; let xs = (xs + residual)?; let residual = &xs; let xs = xs.apply(&self.norm2)?.apply(&self.ffn)?; xs + residual } } pub(crate) fn build_alibi_bias(cfg: &Config) -> Result<Tensor> { let full = !cfg.is_causal(); let seq_len = cfg.max_seq_len; let alibi_bias = Tensor::arange(1 - seq_len as i64, 1, &Device::Cpu)?; let alibi_bias = if full { let a1 = alibi_bias.reshape((1, 1, 1, seq_len))?; let a2 = alibi_bias.reshape((1, 1, seq_len, 1))?; a1.broadcast_sub(&a2)?.abs()?.neg()? } else { alibi_bias.reshape((1, 1, 1, seq_len))? }; let mut n_heads2 = 1; while n_heads2 < cfg.n_heads { n_heads2 *= 2 } let slopes = (1..=n_heads2) .map(|v| 1f32 / 2f32.powf((v * cfg.attn_alibi_bias_max) as f32 / n_heads2 as f32)) .collect::<Vec<_>>(); let slopes = if n_heads2 == cfg.n_heads { slopes } else { slopes .iter() .skip(1) .step_by(2) .chain(slopes.iter().step_by(2)) .take(cfg.n_heads) .cloned() .collect::<Vec<f32>>() }; let slopes = Tensor::new(slopes, &Device::Cpu)?.reshape((1, (), 1, 1))?; alibi_bias.to_dtype(DType::F32)?.broadcast_mul(&slopes) } #[derive(Debug, Clone)] pub struct Model { wte: Embedding, blocks: Vec<MPTBlock>, norm_f: LayerNorm, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let wte = Embedding::new(cfg.vocab_size, cfg.d_model, vb.pp("wte"))?; let vb_b = vb.pp("blocks"); let mut blocks = Vec::with_capacity(cfg.n_layers); for i in 0..cfg.n_layers { let block = MPTBlock::new(cfg, vb_b.pp(i))?; blocks.push(block) } let ln_cfg = candle_nn::LayerNormConfig { affine: false, ..Default::default() }; let norm_f = candle_nn::layer_norm(cfg.d_model, ln_cfg, vb.pp("norm_f"))?; Ok(Self { wte, blocks, norm_f, }) } pub fn forward(&mut self, xs: &Tensor) -> Result<Tensor> { let (_b_size, seq_len) = xs.dims2()?; let mut xs = xs.apply(&self.wte)?; let mask = if seq_len <= 1 { None } else { Some(get_mask(seq_len, xs.device())?) }; for block in self.blocks.iter_mut() { xs = block.forward(&xs, mask.as_ref())?; } let xs = xs.apply(&self.norm_f)?; let logits = xs .narrow(1, seq_len - 1, 1)? .squeeze(1)? .matmul(&self.wte.embeddings().t()?)? .squeeze(1)?; Ok(logits) } } pub(crate) fn get_mask(size: usize, device: &Device) -> Result<Tensor> { let mask: Vec<_> = (0..size) .flat_map(|i| (0..size).map(move |j| u8::from(j > i))) .collect(); Tensor::from_slice(&mask, (size, size), device) } pub(crate) fn masked_fill(on_false: &Tensor, mask: &Tensor, on_true: f32) -> Result<Tensor> { let shape = mask.shape(); let on_true = Tensor::new(on_true, on_false.device())?.broadcast_as(shape.dims())?; let m = mask.where_cond(&on_true, on_false)?; Ok(m) }
candle/candle-transformers/src/models/mpt.rs/0
{ "file_path": "candle/candle-transformers/src/models/mpt.rs", "repo_id": "candle", "token_count": 5366 }
60
//! BLIP model implementation with quantization support. //! //! BLIP is a vision-language model for image understanding and generation tasks. //! This implementation provides quantization for reduced memory and compute. //! //! Key characteristics: //! - Vision encoder using ViT architecture //! - Text decoder using BERT-style transformer //! - Cross-attention between vision and text features //! - Support for 8-bit quantization //! //! References: //! - [BLIP Paper](https://arxiv.org/abs/2201.12086) //! - [Hugging Face Implementation](https://huggingface.co/docs/transformers/model_doc/blip) //! use super::quantized_blip_text as blip_text; use crate::quantized_nn::{layer_norm, linear, Linear}; pub use crate::quantized_var_builder::VarBuilder; use candle::{Module, Result, Tensor, D}; use candle_nn::{Conv2d, Conv2dConfig, LayerNorm}; pub type VisionConfig = super::blip::VisionConfig; pub type Config = super::blip::Config; #[derive(Debug, Clone)] struct VisionEmbeddings { class_embedding: Tensor, patch_embedding: Conv2d, position_embedding: Tensor, } impl VisionEmbeddings { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let class_embedding = vb .get((1, 1, cfg.hidden_size), "class_embedding")? .dequantize(vb.device())?; let conv_cfg = Conv2dConfig { stride: cfg.patch_size, ..Default::default() }; let pe_vb = vb.pp("patch_embedding"); let pe_weight = pe_vb .get( (cfg.hidden_size, 3, cfg.patch_size, cfg.patch_size), "weight", )? .dequantize(vb.device())?; let pe_bias = pe_vb .get(cfg.hidden_size, "bias")? .dequantize(vb.device())?; let patch_embedding = Conv2d::new(pe_weight, Some(pe_bias), conv_cfg); let num_patches1 = cfg.image_size / cfg.patch_size; let num_patches = num_patches1 * num_patches1; let num_positions = num_patches + 1; let position_embedding = vb .get((1, num_positions, cfg.hidden_size), "position_embedding")? .dequantize(vb.device())?; Ok(Self { class_embedding, patch_embedding, position_embedding, }) } } impl Module for VisionEmbeddings { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let target_dtype = xs.dtype(); let b_size = xs.dim(0)?; let patch_embeds = xs.apply(&self.patch_embedding)?.flatten_from(2)?.t()?; let d = self.class_embedding.dim(D::Minus1)?; let class_embeds = self .class_embedding .broadcast_as((b_size, 1, d))? .to_dtype(target_dtype)?; let embeddings = Tensor::cat(&[&class_embeds, &patch_embeds], 1)?; let position_embedding = self.position_embedding.narrow(1, 0, embeddings.dim(1)?)?; embeddings.broadcast_add(&position_embedding) } } #[derive(Debug, Clone)] struct Attention { qkv: Linear, projection: Linear, scale: f64, num_heads: usize, } impl Attention { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let embed_dim = cfg.hidden_size; let num_heads = cfg.num_attention_heads; let head_dim = embed_dim / num_heads; let scale = 1f64 / (head_dim as f64).sqrt(); let qkv = linear(embed_dim, 3 * embed_dim, vb.pp("qkv"))?; let projection = linear(embed_dim, embed_dim, vb.pp("projection"))?; Ok(Self { qkv, projection, scale, num_heads, }) } fn forward(&self, xs: &Tensor, attn_mask: Option<&Tensor>) -> Result<Tensor> { let (b_sz, tgt_len, embed_dim) = xs.dims3()?; let mixed_qkv = xs .apply(&self.qkv)? .reshape((b_sz, tgt_len, 3, self.num_heads, embed_dim / self.num_heads))? .permute((2, 0, 3, 1, 4))?; let query = mixed_qkv.get(0)?; let key = mixed_qkv.get(1)?; let value = mixed_qkv.get(2)?; let attention_scores = query.matmul(&key.t()?)?; let attention_scores = (attention_scores * self.scale)?; let attention_probs = candle_nn::ops::softmax_last_dim(&attention_scores)?; let attention_probs = match attn_mask { None => attention_probs, Some(attn_mask) => (attention_probs * attn_mask)?, }; attention_probs .matmul(&value)? .permute((0, 2, 1, 3))? .flatten_from(D::Minus2)? .apply(&self.projection) } } #[derive(Debug, Clone)] #[allow(clippy::upper_case_acronyms)] struct MLP { activation_fn: candle_nn::Activation, fc1: Linear, fc2: Linear, } impl MLP { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let fc1 = linear(cfg.hidden_size, cfg.intermediate_size, vb.pp("fc1"))?; let fc2 = linear(cfg.intermediate_size, cfg.hidden_size, vb.pp("fc2"))?; Ok(Self { activation_fn: cfg.hidden_act, fc1, fc2, }) } } impl Module for MLP { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.fc1)? .apply(&self.activation_fn)? .apply(&self.fc2) } } #[derive(Debug, Clone)] struct EncoderLayer { self_attn: Attention, layer_norm1: LayerNorm, mlp: MLP, layer_norm2: LayerNorm, } impl EncoderLayer { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let embed_dim = cfg.hidden_size; let self_attn = Attention::new(cfg, vb.pp("self_attn"))?; let layer_norm1 = layer_norm(embed_dim, cfg.layer_norm_eps, vb.pp("layer_norm1"))?; let layer_norm2 = layer_norm(embed_dim, cfg.layer_norm_eps, vb.pp("layer_norm2"))?; let mlp = MLP::new(cfg, vb.pp("mlp"))?; Ok(Self { self_attn, layer_norm1, mlp, layer_norm2, }) } fn forward(&self, xs: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> { let residual = xs; let xs = xs.apply(&self.layer_norm1)?; let xs = self.self_attn.forward(&xs, attention_mask)?; let xs = (xs + residual)?; let residual = &xs; let xs = xs.apply(&self.layer_norm2)?.apply(&self.mlp)?; xs + residual } } #[derive(Debug, Clone)] struct Encoder { layers: Vec<EncoderLayer>, } impl Encoder { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb = vb.pp("layers"); for i in 0..cfg.num_hidden_layers { let layer = EncoderLayer::new(cfg, vb.pp(i))?; layers.push(layer) } Ok(Self { layers }) } fn forward(&self, xs: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> { let mut xs = xs.clone(); for layer in self.layers.iter() { xs = layer.forward(&xs, attention_mask)? } Ok(xs) } } #[derive(Debug, Clone)] pub struct VisionModel { embeddings: VisionEmbeddings, encoder: Encoder, post_layernorm: LayerNorm, } impl VisionModel { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let embeddings = VisionEmbeddings::new(cfg, vb.pp("embeddings"))?; let encoder = Encoder::new(cfg, vb.pp("encoder"))?; let post_layernorm = layer_norm(cfg.hidden_size, cfg.layer_norm_eps, vb.pp("post_layernorm"))?; Ok(Self { embeddings, encoder, post_layernorm, }) } } impl Module for VisionModel { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = xs.apply(&self.embeddings)?; let encoder_outputs = self.encoder.forward(&xs, None)?; // Return the last hidden state rather than pooled outputs. encoder_outputs.apply(&self.post_layernorm) } } #[derive(Debug, Clone)] pub struct BlipForConditionalGeneration { vision_model: VisionModel, text_decoder: blip_text::TextLMHeadModel, } impl BlipForConditionalGeneration { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vision_model = VisionModel::new(&cfg.vision_config, vb.pp("vision_model"))?; let text_decoder = blip_text::TextLMHeadModel::new(&cfg.text_config, vb.pp("text_decoder"))?; Ok(Self { vision_model, text_decoder, }) } pub fn vision_model(&self) -> &VisionModel { &self.vision_model } pub fn text_decoder(&mut self) -> &mut blip_text::TextLMHeadModel { &mut self.text_decoder } pub fn reset_kv_cache(&mut self) { self.text_decoder.reset_kv_cache(); } }
candle/candle-transformers/src/models/quantized_blip.rs/0
{ "file_path": "candle/candle-transformers/src/models/quantized_blip.rs", "repo_id": "candle", "token_count": 4186 }
61
use candle::{DType, IndexOp, Result, Tensor, D}; use candle_nn::VarBuilder; #[derive(Debug)] struct PositionEmbeddingRandom { positional_encoding_gaussian_matrix: Tensor, } impl PositionEmbeddingRandom { fn new(num_pos_feats: usize, vb: VarBuilder) -> Result<Self> { let positional_encoding_gaussian_matrix = vb.get((2, num_pos_feats), "positional_encoding_gaussian_matrix")?; Ok(Self { positional_encoding_gaussian_matrix, }) } fn pe_encoding(&self, coords: &Tensor) -> Result<Tensor> { let coords = coords.affine(2., -1.)?; let coords = coords.broadcast_matmul(&self.positional_encoding_gaussian_matrix)?; let coords = (coords * (2. * std::f64::consts::PI))?; Tensor::cat(&[coords.sin()?, coords.cos()?], D::Minus1) } fn forward(&self, h: usize, w: usize) -> Result<Tensor> { let device = self.positional_encoding_gaussian_matrix.device(); let x_embed = (Tensor::arange(0u32, w as u32, device)?.to_dtype(DType::F32)? + 0.5)?; let y_embed = (Tensor::arange(0u32, h as u32, device)?.to_dtype(DType::F32)? + 0.5)?; let x_embed = (x_embed / w as f64)? .reshape((1, ()))? .broadcast_as((h, w))?; let y_embed = (y_embed / h as f64)? .reshape(((), 1))? .broadcast_as((h, w))?; let coords = Tensor::stack(&[&x_embed, &y_embed], D::Minus1)?; self.pe_encoding(&coords)?.permute((2, 0, 1)) } fn forward_with_coords( &self, coords_input: &Tensor, image_size: (usize, usize), ) -> Result<Tensor> { let coords0 = (coords_input.narrow(D::Minus1, 0, 1)? / image_size.1 as f64)?; let coords1 = (coords_input.narrow(D::Minus1, 1, 1)? / image_size.0 as f64)?; let c = coords_input.dim(D::Minus1)?; let coords_rest = coords_input.narrow(D::Minus1, 2, c - 2)?; let coords = Tensor::cat(&[&coords0, &coords1, &coords_rest], D::Minus1)?; self.pe_encoding(&coords) } } #[derive(Debug)] pub struct PromptEncoder { pe_layer: PositionEmbeddingRandom, point_embeddings: Vec<candle_nn::Embedding>, not_a_point_embed: candle_nn::Embedding, mask_downscaling_conv1: candle_nn::Conv2d, mask_downscaling_ln1: super::LayerNorm2d, mask_downscaling_conv2: candle_nn::Conv2d, mask_downscaling_ln2: super::LayerNorm2d, mask_downscaling_conv3: candle_nn::Conv2d, no_mask_embed: candle_nn::Embedding, image_embedding_size: (usize, usize), input_image_size: (usize, usize), embed_dim: usize, span: tracing::Span, } impl PromptEncoder { pub fn new( embed_dim: usize, image_embedding_size: (usize, usize), input_image_size: (usize, usize), mask_in_chans: usize, vb: VarBuilder, ) -> Result<Self> { let num_points_embeddings = 4; let pe_layer = PositionEmbeddingRandom::new(embed_dim / 2, vb.pp("pe_layer"))?; let not_a_point_embed = candle_nn::embedding(1, embed_dim, vb.pp("not_a_point_embed"))?; let no_mask_embed = candle_nn::embedding(1, embed_dim, vb.pp("no_mask_embed"))?; let cfg = candle_nn::Conv2dConfig { stride: 2, ..Default::default() }; let mask_downscaling_conv1 = candle_nn::conv2d(1, mask_in_chans / 4, 2, cfg, vb.pp("mask_downscaling.0"))?; let mask_downscaling_conv2 = candle_nn::conv2d( mask_in_chans / 4, mask_in_chans, 2, cfg, vb.pp("mask_downscaling.3"), )?; let mask_downscaling_conv3 = candle_nn::conv2d( mask_in_chans, embed_dim, 1, Default::default(), vb.pp("mask_downscaling.6"), )?; let mask_downscaling_ln1 = super::LayerNorm2d::new(mask_in_chans / 4, 1e-6, vb.pp("mask_downscaling.1"))?; let mask_downscaling_ln2 = super::LayerNorm2d::new(mask_in_chans, 1e-6, vb.pp("mask_downscaling.4"))?; let mut point_embeddings = Vec::with_capacity(num_points_embeddings); let vb_e = vb.pp("point_embeddings"); for i in 0..num_points_embeddings { let emb = candle_nn::embedding(1, embed_dim, vb_e.pp(i))?; point_embeddings.push(emb) } let span = tracing::span!(tracing::Level::TRACE, "prompt-encoder"); Ok(Self { pe_layer, point_embeddings, not_a_point_embed, mask_downscaling_conv1, mask_downscaling_ln1, mask_downscaling_conv2, mask_downscaling_ln2, mask_downscaling_conv3, no_mask_embed, image_embedding_size, input_image_size, embed_dim, span, }) } pub fn get_dense_pe(&self) -> Result<Tensor> { self.pe_layer .forward(self.image_embedding_size.0, self.image_embedding_size.1)? .unsqueeze(0) } fn embed_masks(&self, masks: &Tensor) -> Result<Tensor> { masks .apply(&self.mask_downscaling_conv1)? .apply(&self.mask_downscaling_ln1)? .gelu()? .apply(&self.mask_downscaling_conv2)? .apply(&self.mask_downscaling_ln2)? .gelu()? .apply(&self.mask_downscaling_conv3) } fn embed_points(&self, points: &Tensor, labels: &Tensor, pad: bool) -> Result<Tensor> { let points = (points + 0.5)?; let dev = points.device(); let (points, labels) = if pad { let padding_point = Tensor::zeros((points.dim(0)?, 1, 2), DType::F32, dev)?; let padding_label = (Tensor::ones((labels.dim(0)?, 1), DType::F32, dev)? * (-1f64))?; let points = Tensor::cat(&[&points, &padding_point], 1)?; let labels = Tensor::cat(&[labels, &padding_label], 1)?; (points, labels) } else { (points, labels.clone()) }; let point_embedding = self .pe_layer .forward_with_coords(&points, self.input_image_size)?; let labels = labels.unsqueeze(2)?.broadcast_as(point_embedding.shape())?; let zeros = point_embedding.zeros_like()?; let point_embedding = labels.lt(0f32)?.where_cond( &self .not_a_point_embed .embeddings() .broadcast_as(zeros.shape())?, &point_embedding, )?; let labels0 = labels.eq(0f32)?.where_cond( &self.point_embeddings[0] .embeddings() .broadcast_as(zeros.shape())?, &zeros, )?; let point_embedding = (point_embedding + labels0)?; let labels1 = labels.eq(1f32)?.where_cond( &self.point_embeddings[1] .embeddings() .broadcast_as(zeros.shape())?, &zeros, )?; let point_embedding = (point_embedding + labels1)?; Ok(point_embedding) } fn embed_boxes(&self, boxes: &Tensor) -> Result<Tensor> { let boxes = (boxes + 0.5)?; let coords = boxes.reshape(((), 2, 2))?; let corner_embedding = self .pe_layer .forward_with_coords(&coords, self.input_image_size)?; let ce1 = corner_embedding.i((.., 0))?; let ce2 = corner_embedding.i((.., 1))?; let ce1 = (ce1 + self.point_embeddings[2].embeddings())?; let ce2 = (ce2 + self.point_embeddings[3].embeddings())?; Tensor::cat(&[&ce1, &ce2], 1) } pub fn forward( &self, points: Option<(&Tensor, &Tensor)>, boxes: Option<&Tensor>, masks: Option<&Tensor>, ) -> Result<(Tensor, Tensor)> { let _enter = self.span.enter(); let se_points = match points { Some((coords, labels)) => Some(self.embed_points(coords, labels, boxes.is_none())?), None => None, }; let se_boxes = match boxes { Some(boxes) => Some(self.embed_boxes(boxes)?), None => None, }; let sparse_embeddings = match (se_points, se_boxes) { (Some(se_points), Some(se_boxes)) => Tensor::cat(&[se_points, se_boxes], 1)?, (Some(se_points), None) => se_points, (None, Some(se_boxes)) => se_boxes, (None, None) => { let dev = self.no_mask_embed.embeddings().device(); Tensor::zeros((1, 0, self.embed_dim), DType::F32, dev)? } }; let dense_embeddings = match masks { None => { let emb = self.no_mask_embed.embeddings(); emb.reshape((1, (), 1, 1))?.expand(( 1, emb.elem_count(), self.image_embedding_size.0, self.image_embedding_size.1, ))? } Some(masks) => self.embed_masks(masks)?, }; Ok((sparse_embeddings, dense_embeddings)) } }
candle/candle-transformers/src/models/segment_anything/prompt_encoder.rs/0
{ "file_path": "candle/candle-transformers/src/models/segment_anything/prompt_encoder.rs", "repo_id": "candle", "token_count": 4745 }
62
//! 2D UNet Building Blocks //! use super::attention::{ AttentionBlock, AttentionBlockConfig, SpatialTransformer, SpatialTransformerConfig, }; use super::resnet::{ResnetBlock2D, ResnetBlock2DConfig}; use crate::models::with_tracing::{conv2d, Conv2d}; use candle::{Module, Result, Tensor, D}; use candle_nn as nn; #[derive(Debug)] struct Downsample2D { conv: Option<Conv2d>, padding: usize, span: tracing::Span, } impl Downsample2D { fn new( vs: nn::VarBuilder, in_channels: usize, use_conv: bool, out_channels: usize, padding: usize, ) -> Result<Self> { let conv = if use_conv { let config = nn::Conv2dConfig { stride: 2, padding, ..Default::default() }; let conv = conv2d(in_channels, out_channels, 3, config, vs.pp("conv"))?; Some(conv) } else { None }; let span = tracing::span!(tracing::Level::TRACE, "downsample2d"); Ok(Self { conv, padding, span, }) } } impl Module for Downsample2D { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); match &self.conv { None => xs.avg_pool2d(2), Some(conv) => { if self.padding == 0 { let xs = xs .pad_with_zeros(D::Minus1, 0, 1)? .pad_with_zeros(D::Minus2, 0, 1)?; conv.forward(&xs) } else { conv.forward(xs) } } } } } // This does not support the conv-transpose mode. #[derive(Debug)] struct Upsample2D { conv: Conv2d, span: tracing::Span, } impl Upsample2D { fn new(vs: nn::VarBuilder, in_channels: usize, out_channels: usize) -> Result<Self> { let config = nn::Conv2dConfig { padding: 1, ..Default::default() }; let conv = conv2d(in_channels, out_channels, 3, config, vs.pp("conv"))?; let span = tracing::span!(tracing::Level::TRACE, "upsample2d"); Ok(Self { conv, span }) } } impl Upsample2D { fn forward(&self, xs: &Tensor, size: Option<(usize, usize)>) -> Result<Tensor> { let _enter = self.span.enter(); let xs = match size { None => { let (_bsize, _channels, h, w) = xs.dims4()?; xs.upsample_nearest2d(2 * h, 2 * w)? } Some((h, w)) => xs.upsample_nearest2d(h, w)?, }; self.conv.forward(&xs) } } #[derive(Debug, Clone, Copy)] pub struct DownEncoderBlock2DConfig { pub num_layers: usize, pub resnet_eps: f64, pub resnet_groups: usize, pub output_scale_factor: f64, pub add_downsample: bool, pub downsample_padding: usize, } impl Default for DownEncoderBlock2DConfig { fn default() -> Self { Self { num_layers: 1, resnet_eps: 1e-6, resnet_groups: 32, output_scale_factor: 1., add_downsample: true, downsample_padding: 1, } } } #[derive(Debug)] pub struct DownEncoderBlock2D { resnets: Vec<ResnetBlock2D>, downsampler: Option<Downsample2D>, span: tracing::Span, pub config: DownEncoderBlock2DConfig, } impl DownEncoderBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, out_channels: usize, config: DownEncoderBlock2DConfig, ) -> Result<Self> { let resnets: Vec<_> = { let vs = vs.pp("resnets"); let conv_cfg = ResnetBlock2DConfig { eps: config.resnet_eps, out_channels: Some(out_channels), groups: config.resnet_groups, output_scale_factor: config.output_scale_factor, temb_channels: None, ..Default::default() }; (0..(config.num_layers)) .map(|i| { let in_channels = if i == 0 { in_channels } else { out_channels }; ResnetBlock2D::new(vs.pp(i.to_string()), in_channels, conv_cfg) }) .collect::<Result<Vec<_>>>()? }; let downsampler = if config.add_downsample { let downsample = Downsample2D::new( vs.pp("downsamplers").pp("0"), out_channels, true, out_channels, config.downsample_padding, )?; Some(downsample) } else { None }; let span = tracing::span!(tracing::Level::TRACE, "down-enc2d"); Ok(Self { resnets, downsampler, span, config, }) } } impl Module for DownEncoderBlock2D { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = xs.clone(); for resnet in self.resnets.iter() { xs = resnet.forward(&xs, None)? } match &self.downsampler { Some(downsampler) => downsampler.forward(&xs), None => Ok(xs), } } } #[derive(Debug, Clone, Copy)] pub struct UpDecoderBlock2DConfig { pub num_layers: usize, pub resnet_eps: f64, pub resnet_groups: usize, pub output_scale_factor: f64, pub add_upsample: bool, } impl Default for UpDecoderBlock2DConfig { fn default() -> Self { Self { num_layers: 1, resnet_eps: 1e-6, resnet_groups: 32, output_scale_factor: 1., add_upsample: true, } } } #[derive(Debug)] pub struct UpDecoderBlock2D { resnets: Vec<ResnetBlock2D>, upsampler: Option<Upsample2D>, span: tracing::Span, pub config: UpDecoderBlock2DConfig, } impl UpDecoderBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, out_channels: usize, config: UpDecoderBlock2DConfig, ) -> Result<Self> { let resnets: Vec<_> = { let vs = vs.pp("resnets"); let conv_cfg = ResnetBlock2DConfig { out_channels: Some(out_channels), eps: config.resnet_eps, groups: config.resnet_groups, output_scale_factor: config.output_scale_factor, temb_channels: None, ..Default::default() }; (0..(config.num_layers)) .map(|i| { let in_channels = if i == 0 { in_channels } else { out_channels }; ResnetBlock2D::new(vs.pp(i.to_string()), in_channels, conv_cfg) }) .collect::<Result<Vec<_>>>()? }; let upsampler = if config.add_upsample { let upsample = Upsample2D::new(vs.pp("upsamplers").pp("0"), out_channels, out_channels)?; Some(upsample) } else { None }; let span = tracing::span!(tracing::Level::TRACE, "up-dec2d"); Ok(Self { resnets, upsampler, span, config, }) } } impl Module for UpDecoderBlock2D { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = xs.clone(); for resnet in self.resnets.iter() { xs = resnet.forward(&xs, None)? } match &self.upsampler { Some(upsampler) => upsampler.forward(&xs, None), None => Ok(xs), } } } #[derive(Debug, Clone, Copy)] pub struct UNetMidBlock2DConfig { pub num_layers: usize, pub resnet_eps: f64, pub resnet_groups: Option<usize>, pub attn_num_head_channels: Option<usize>, // attention_type "default" pub output_scale_factor: f64, } impl Default for UNetMidBlock2DConfig { fn default() -> Self { Self { num_layers: 1, resnet_eps: 1e-6, resnet_groups: Some(32), attn_num_head_channels: Some(1), output_scale_factor: 1., } } } #[derive(Debug)] pub struct UNetMidBlock2D { resnet: ResnetBlock2D, attn_resnets: Vec<(AttentionBlock, ResnetBlock2D)>, span: tracing::Span, pub config: UNetMidBlock2DConfig, } impl UNetMidBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, temb_channels: Option<usize>, config: UNetMidBlock2DConfig, ) -> Result<Self> { let vs_resnets = vs.pp("resnets"); let vs_attns = vs.pp("attentions"); let resnet_groups = config .resnet_groups .unwrap_or_else(|| usize::min(in_channels / 4, 32)); let resnet_cfg = ResnetBlock2DConfig { eps: config.resnet_eps, groups: resnet_groups, output_scale_factor: config.output_scale_factor, temb_channels, ..Default::default() }; let resnet = ResnetBlock2D::new(vs_resnets.pp("0"), in_channels, resnet_cfg)?; let attn_cfg = AttentionBlockConfig { num_head_channels: config.attn_num_head_channels, num_groups: resnet_groups, rescale_output_factor: config.output_scale_factor, eps: config.resnet_eps, }; let mut attn_resnets = vec![]; for index in 0..config.num_layers { let attn = AttentionBlock::new(vs_attns.pp(index.to_string()), in_channels, attn_cfg)?; let resnet = ResnetBlock2D::new( vs_resnets.pp((index + 1).to_string()), in_channels, resnet_cfg, )?; attn_resnets.push((attn, resnet)) } let span = tracing::span!(tracing::Level::TRACE, "mid2d"); Ok(Self { resnet, attn_resnets, span, config, }) } pub fn forward(&self, xs: &Tensor, temb: Option<&Tensor>) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = self.resnet.forward(xs, temb)?; for (attn, resnet) in self.attn_resnets.iter() { xs = resnet.forward(&attn.forward(&xs)?, temb)? } Ok(xs) } } #[derive(Debug, Clone, Copy)] pub struct UNetMidBlock2DCrossAttnConfig { pub num_layers: usize, pub resnet_eps: f64, pub resnet_groups: Option<usize>, pub attn_num_head_channels: usize, // attention_type "default" pub output_scale_factor: f64, pub cross_attn_dim: usize, pub sliced_attention_size: Option<usize>, pub use_linear_projection: bool, pub transformer_layers_per_block: usize, } impl Default for UNetMidBlock2DCrossAttnConfig { fn default() -> Self { Self { num_layers: 1, resnet_eps: 1e-6, resnet_groups: Some(32), attn_num_head_channels: 1, output_scale_factor: 1., cross_attn_dim: 1280, sliced_attention_size: None, // Sliced attention disabled use_linear_projection: false, transformer_layers_per_block: 1, } } } #[derive(Debug)] pub struct UNetMidBlock2DCrossAttn { resnet: ResnetBlock2D, attn_resnets: Vec<(SpatialTransformer, ResnetBlock2D)>, span: tracing::Span, pub config: UNetMidBlock2DCrossAttnConfig, } impl UNetMidBlock2DCrossAttn { pub fn new( vs: nn::VarBuilder, in_channels: usize, temb_channels: Option<usize>, use_flash_attn: bool, config: UNetMidBlock2DCrossAttnConfig, ) -> Result<Self> { let vs_resnets = vs.pp("resnets"); let vs_attns = vs.pp("attentions"); let resnet_groups = config .resnet_groups .unwrap_or_else(|| usize::min(in_channels / 4, 32)); let resnet_cfg = ResnetBlock2DConfig { eps: config.resnet_eps, groups: resnet_groups, output_scale_factor: config.output_scale_factor, temb_channels, ..Default::default() }; let resnet = ResnetBlock2D::new(vs_resnets.pp("0"), in_channels, resnet_cfg)?; let n_heads = config.attn_num_head_channels; let attn_cfg = SpatialTransformerConfig { depth: config.transformer_layers_per_block, num_groups: resnet_groups, context_dim: Some(config.cross_attn_dim), sliced_attention_size: config.sliced_attention_size, use_linear_projection: config.use_linear_projection, }; let mut attn_resnets = vec![]; for index in 0..config.num_layers { let attn = SpatialTransformer::new( vs_attns.pp(index.to_string()), in_channels, n_heads, in_channels / n_heads, use_flash_attn, attn_cfg, )?; let resnet = ResnetBlock2D::new( vs_resnets.pp((index + 1).to_string()), in_channels, resnet_cfg, )?; attn_resnets.push((attn, resnet)) } let span = tracing::span!(tracing::Level::TRACE, "xa-mid2d"); Ok(Self { resnet, attn_resnets, span, config, }) } pub fn forward( &self, xs: &Tensor, temb: Option<&Tensor>, encoder_hidden_states: Option<&Tensor>, ) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = self.resnet.forward(xs, temb)?; for (attn, resnet) in self.attn_resnets.iter() { xs = resnet.forward(&attn.forward(&xs, encoder_hidden_states)?, temb)? } Ok(xs) } } #[derive(Debug, Clone, Copy)] pub struct DownBlock2DConfig { pub num_layers: usize, pub resnet_eps: f64, // resnet_time_scale_shift: "default" // resnet_act_fn: "swish" pub resnet_groups: usize, pub output_scale_factor: f64, pub add_downsample: bool, pub downsample_padding: usize, } impl Default for DownBlock2DConfig { fn default() -> Self { Self { num_layers: 1, resnet_eps: 1e-6, resnet_groups: 32, output_scale_factor: 1., add_downsample: true, downsample_padding: 1, } } } #[derive(Debug)] pub struct DownBlock2D { resnets: Vec<ResnetBlock2D>, downsampler: Option<Downsample2D>, span: tracing::Span, pub config: DownBlock2DConfig, } impl DownBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, out_channels: usize, temb_channels: Option<usize>, config: DownBlock2DConfig, ) -> Result<Self> { let vs_resnets = vs.pp("resnets"); let resnet_cfg = ResnetBlock2DConfig { out_channels: Some(out_channels), eps: config.resnet_eps, output_scale_factor: config.output_scale_factor, temb_channels, ..Default::default() }; let resnets = (0..config.num_layers) .map(|i| { let in_channels = if i == 0 { in_channels } else { out_channels }; ResnetBlock2D::new(vs_resnets.pp(i.to_string()), in_channels, resnet_cfg) }) .collect::<Result<Vec<_>>>()?; let downsampler = if config.add_downsample { let downsampler = Downsample2D::new( vs.pp("downsamplers").pp("0"), out_channels, true, out_channels, config.downsample_padding, )?; Some(downsampler) } else { None }; let span = tracing::span!(tracing::Level::TRACE, "down2d"); Ok(Self { resnets, downsampler, span, config, }) } pub fn forward(&self, xs: &Tensor, temb: Option<&Tensor>) -> Result<(Tensor, Vec<Tensor>)> { let _enter = self.span.enter(); let mut xs = xs.clone(); let mut output_states = vec![]; for resnet in self.resnets.iter() { xs = resnet.forward(&xs, temb)?; output_states.push(xs.clone()); } let xs = match &self.downsampler { Some(downsampler) => { let xs = downsampler.forward(&xs)?; output_states.push(xs.clone()); xs } None => xs, }; Ok((xs, output_states)) } } #[derive(Debug, Clone, Copy)] pub struct CrossAttnDownBlock2DConfig { pub downblock: DownBlock2DConfig, pub attn_num_head_channels: usize, pub cross_attention_dim: usize, // attention_type: "default" pub sliced_attention_size: Option<usize>, pub use_linear_projection: bool, pub transformer_layers_per_block: usize, } impl Default for CrossAttnDownBlock2DConfig { fn default() -> Self { Self { downblock: Default::default(), attn_num_head_channels: 1, cross_attention_dim: 1280, sliced_attention_size: None, use_linear_projection: false, transformer_layers_per_block: 1, } } } #[derive(Debug)] pub struct CrossAttnDownBlock2D { downblock: DownBlock2D, attentions: Vec<SpatialTransformer>, span: tracing::Span, pub config: CrossAttnDownBlock2DConfig, } impl CrossAttnDownBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, out_channels: usize, temb_channels: Option<usize>, use_flash_attn: bool, config: CrossAttnDownBlock2DConfig, ) -> Result<Self> { let downblock = DownBlock2D::new( vs.clone(), in_channels, out_channels, temb_channels, config.downblock, )?; let n_heads = config.attn_num_head_channels; let cfg = SpatialTransformerConfig { depth: config.transformer_layers_per_block, context_dim: Some(config.cross_attention_dim), num_groups: config.downblock.resnet_groups, sliced_attention_size: config.sliced_attention_size, use_linear_projection: config.use_linear_projection, }; let vs_attn = vs.pp("attentions"); let attentions = (0..config.downblock.num_layers) .map(|i| { SpatialTransformer::new( vs_attn.pp(i.to_string()), out_channels, n_heads, out_channels / n_heads, use_flash_attn, cfg, ) }) .collect::<Result<Vec<_>>>()?; let span = tracing::span!(tracing::Level::TRACE, "xa-down2d"); Ok(Self { downblock, attentions, span, config, }) } pub fn forward( &self, xs: &Tensor, temb: Option<&Tensor>, encoder_hidden_states: Option<&Tensor>, ) -> Result<(Tensor, Vec<Tensor>)> { let _enter = self.span.enter(); let mut output_states = vec![]; let mut xs = xs.clone(); for (resnet, attn) in self.downblock.resnets.iter().zip(self.attentions.iter()) { xs = resnet.forward(&xs, temb)?; xs = attn.forward(&xs, encoder_hidden_states)?; output_states.push(xs.clone()); } let xs = match &self.downblock.downsampler { Some(downsampler) => { let xs = downsampler.forward(&xs)?; output_states.push(xs.clone()); xs } None => xs, }; Ok((xs, output_states)) } } #[derive(Debug, Clone, Copy)] pub struct UpBlock2DConfig { pub num_layers: usize, pub resnet_eps: f64, // resnet_time_scale_shift: "default" // resnet_act_fn: "swish" pub resnet_groups: usize, pub output_scale_factor: f64, pub add_upsample: bool, } impl Default for UpBlock2DConfig { fn default() -> Self { Self { num_layers: 1, resnet_eps: 1e-6, resnet_groups: 32, output_scale_factor: 1., add_upsample: true, } } } #[derive(Debug)] pub struct UpBlock2D { pub resnets: Vec<ResnetBlock2D>, upsampler: Option<Upsample2D>, span: tracing::Span, pub config: UpBlock2DConfig, } impl UpBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, prev_output_channels: usize, out_channels: usize, temb_channels: Option<usize>, config: UpBlock2DConfig, ) -> Result<Self> { let vs_resnets = vs.pp("resnets"); let resnet_cfg = ResnetBlock2DConfig { out_channels: Some(out_channels), temb_channels, eps: config.resnet_eps, output_scale_factor: config.output_scale_factor, ..Default::default() }; let resnets = (0..config.num_layers) .map(|i| { let res_skip_channels = if i == config.num_layers - 1 { in_channels } else { out_channels }; let resnet_in_channels = if i == 0 { prev_output_channels } else { out_channels }; let in_channels = resnet_in_channels + res_skip_channels; ResnetBlock2D::new(vs_resnets.pp(i.to_string()), in_channels, resnet_cfg) }) .collect::<Result<Vec<_>>>()?; let upsampler = if config.add_upsample { let upsampler = Upsample2D::new(vs.pp("upsamplers").pp("0"), out_channels, out_channels)?; Some(upsampler) } else { None }; let span = tracing::span!(tracing::Level::TRACE, "up2d"); Ok(Self { resnets, upsampler, span, config, }) } pub fn forward( &self, xs: &Tensor, res_xs: &[Tensor], temb: Option<&Tensor>, upsample_size: Option<(usize, usize)>, ) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = xs.clone(); for (index, resnet) in self.resnets.iter().enumerate() { xs = Tensor::cat(&[&xs, &res_xs[res_xs.len() - index - 1]], 1)?; xs = xs.contiguous()?; xs = resnet.forward(&xs, temb)?; } match &self.upsampler { Some(upsampler) => upsampler.forward(&xs, upsample_size), None => Ok(xs), } } } #[derive(Debug, Clone, Copy)] pub struct CrossAttnUpBlock2DConfig { pub upblock: UpBlock2DConfig, pub attn_num_head_channels: usize, pub cross_attention_dim: usize, // attention_type: "default" pub sliced_attention_size: Option<usize>, pub use_linear_projection: bool, pub transformer_layers_per_block: usize, } impl Default for CrossAttnUpBlock2DConfig { fn default() -> Self { Self { upblock: Default::default(), attn_num_head_channels: 1, cross_attention_dim: 1280, sliced_attention_size: None, use_linear_projection: false, transformer_layers_per_block: 1, } } } #[derive(Debug)] pub struct CrossAttnUpBlock2D { pub upblock: UpBlock2D, pub attentions: Vec<SpatialTransformer>, span: tracing::Span, pub config: CrossAttnUpBlock2DConfig, } impl CrossAttnUpBlock2D { pub fn new( vs: nn::VarBuilder, in_channels: usize, prev_output_channels: usize, out_channels: usize, temb_channels: Option<usize>, use_flash_attn: bool, config: CrossAttnUpBlock2DConfig, ) -> Result<Self> { let upblock = UpBlock2D::new( vs.clone(), in_channels, prev_output_channels, out_channels, temb_channels, config.upblock, )?; let n_heads = config.attn_num_head_channels; let cfg = SpatialTransformerConfig { depth: config.transformer_layers_per_block, context_dim: Some(config.cross_attention_dim), num_groups: config.upblock.resnet_groups, sliced_attention_size: config.sliced_attention_size, use_linear_projection: config.use_linear_projection, }; let vs_attn = vs.pp("attentions"); let attentions = (0..config.upblock.num_layers) .map(|i| { SpatialTransformer::new( vs_attn.pp(i.to_string()), out_channels, n_heads, out_channels / n_heads, use_flash_attn, cfg, ) }) .collect::<Result<Vec<_>>>()?; let span = tracing::span!(tracing::Level::TRACE, "xa-up2d"); Ok(Self { upblock, attentions, span, config, }) } pub fn forward( &self, xs: &Tensor, res_xs: &[Tensor], temb: Option<&Tensor>, upsample_size: Option<(usize, usize)>, encoder_hidden_states: Option<&Tensor>, ) -> Result<Tensor> { let _enter = self.span.enter(); let mut xs = xs.clone(); for (index, resnet) in self.upblock.resnets.iter().enumerate() { xs = Tensor::cat(&[&xs, &res_xs[res_xs.len() - index - 1]], 1)?; xs = xs.contiguous()?; xs = resnet.forward(&xs, temb)?; xs = self.attentions[index].forward(&xs, encoder_hidden_states)?; } match &self.upblock.upsampler { Some(upsampler) => upsampler.forward(&xs, upsample_size), None => Ok(xs), } } }
candle/candle-transformers/src/models/stable_diffusion/unet_2d_blocks.rs/0
{ "file_path": "candle/candle-transformers/src/models/stable_diffusion/unet_2d_blocks.rs", "repo_id": "candle", "token_count": 13813 }
63
//! Whisper Model Implementation //! //! Whisper is an automatic speech recognition (ASR) system trained on large amounts //! of multilingual and multitask supervised data collected from the web. It can be used to //! convert audio files (in the `.wav` format) to text. Supported features include //! language detection as well as multilingual speech recognition. //! //! - ⚡ [Interactive Wasm Example](https://huggingface.co/spaces/lmz/candle-whisper) //! - 💻 [GH Link](https://github.com/openai/whisper) //! - 💻 Transformers Python [reference implementation](https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py) //! //! pub mod audio; pub mod model; pub mod quantized_model; use serde::Deserialize; // The names in comments correspond to the original implementation: // https://github.com/openai/whisper/blob/f572f2161ba831bae131364c3bffdead7af6d210/whisper/model.py#L17 #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct Config { pub num_mel_bins: usize, // n_mels pub max_source_positions: usize, // n_audio_ctx pub d_model: usize, // n_audio_state pub encoder_attention_heads: usize, // n_audio_head pub encoder_layers: usize, // n_audio_layer pub vocab_size: usize, // n_vocab pub max_target_positions: usize, // n_text_ctx // pub n_text_state: usize, pub decoder_attention_heads: usize, // n_text_head pub decoder_layers: usize, // n_text_layer #[serde(default)] pub suppress_tokens: Vec<u32>, } pub const DTYPE: candle::DType = candle::DType::F32; // Audio parameters. pub const SAMPLE_RATE: usize = 16000; pub const N_FFT: usize = 400; pub const HOP_LENGTH: usize = 160; pub const CHUNK_LENGTH: usize = 30; pub const N_SAMPLES: usize = CHUNK_LENGTH * SAMPLE_RATE; // 480000 samples in a 30-second chunk pub const N_FRAMES: usize = N_SAMPLES / HOP_LENGTH; // 3000 frames in a mel spectrogram input pub const NO_SPEECH_THRESHOLD: f64 = 0.6; pub const LOGPROB_THRESHOLD: f64 = -1.0; pub const TEMPERATURES: [f64; 6] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]; pub const COMPRESSION_RATIO_THRESHOLD: f64 = 2.4; // Tokenizer dependent bits. pub const SOT_TOKEN: &str = "<|startoftranscript|>"; pub const TRANSCRIBE_TOKEN: &str = "<|transcribe|>"; pub const TRANSLATE_TOKEN: &str = "<|translate|>"; pub const NO_TIMESTAMPS_TOKEN: &str = "<|notimestamps|>"; pub const EOT_TOKEN: &str = "<|endoftext|>"; pub const NO_SPEECH_TOKENS: [&str; 2] = ["<|nocaptions|>", "<|nospeech|>"];
candle/candle-transformers/src/models/whisper/mod.rs/0
{ "file_path": "candle/candle-transformers/src/models/whisper/mod.rs", "repo_id": "candle", "token_count": 1018 }
64
//! Utilities for quanitized network layers //! //! This module contains various implementations of standard neural network layers, modules and //! utilities including embedding, linear layers, and various normalization techniques. //! Most implementations provide quantized weights support. use crate::models::with_tracing::QMatMul; use crate::quantized_var_builder::VarBuilder; use candle::quantized::QTensor; use candle::{Module, Result, Tensor}; #[derive(Debug, Clone)] pub struct Embedding { inner: candle_nn::Embedding, span: tracing::Span, } impl Embedding { pub fn new(d1: usize, d2: usize, vb: VarBuilder) -> Result<Self> { let embeddings = vb.get((d1, d2), "weight")?.dequantize(vb.device())?; let inner = candle_nn::Embedding::new(embeddings, d2); let span = tracing::span!(tracing::Level::TRACE, "embedding"); Ok(Self { inner, span }) } pub fn embeddings(&self) -> &Tensor { self.inner.embeddings() } } impl Module for Embedding { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); self.inner.forward(xs) } } #[derive(Debug, Clone)] pub struct Linear { weight: QMatMul, bias: Option<Tensor>, } impl Linear { pub fn from_arc(weight: std::sync::Arc<QTensor>, bias: Option<Tensor>) -> Result<Self> { let weight = QMatMul::from_weights(weight)?; Ok(Self { weight, bias }) } pub fn from_weights(weight: QMatMul, bias: Option<Tensor>) -> Self { Self { weight, bias } } } impl Module for Linear { fn forward(&self, x: &Tensor) -> candle::Result<Tensor> { let x = x.apply(&self.weight)?; match &self.bias { None => Ok(x), Some(bias) => x.broadcast_add(bias), } } } pub fn linear_b(in_dim: usize, out_dim: usize, bias: bool, vb: VarBuilder) -> Result<Linear> { let bias = if bias { Some(vb.get(out_dim, "bias")?.dequantize(vb.device())?) } else { None }; let weight = QMatMul::new(in_dim, out_dim, vb)?; Ok(Linear { weight, bias }) } pub fn linear(in_dim: usize, out_dim: usize, vb: VarBuilder) -> Result<Linear> { let bias = vb.get(out_dim, "bias")?.dequantize(vb.device())?; let weight = QMatMul::new(in_dim, out_dim, vb)?; Ok(Linear { weight, bias: Some(bias), }) } pub fn layer_norm(size: usize, eps: f64, vb: VarBuilder) -> Result<candle_nn::LayerNorm> { let weight = vb.get(size, "weight")?.dequantize(vb.device())?; let bias = vb.get(size, "bias")?.dequantize(vb.device())?; Ok(candle_nn::LayerNorm::new(weight, bias, eps)) } pub fn layer_norm_no_bias(size: usize, eps: f64, vb: VarBuilder) -> Result<candle_nn::LayerNorm> { let weight = vb.get(size, "weight")?.dequantize(vb.device())?; Ok(candle_nn::LayerNorm::new_no_bias(weight, eps)) } pub fn linear_no_bias(in_dim: usize, out_dim: usize, vb: VarBuilder) -> Result<Linear> { let weight = QMatMul::new(in_dim, out_dim, vb)?; Ok(Linear { weight, bias: None }) } #[derive(Debug, Clone)] pub struct RmsNorm { weight: Tensor, eps: f64, span: tracing::Span, } impl RmsNorm { pub fn new(size: usize, eps: f64, vb: VarBuilder) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "rms-norm"); let weight = vb.get(size, "weight")?.dequantize(vb.device())?; Ok(Self { weight, eps, span }) } pub fn from_qtensor(weight: QTensor, eps: f64) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "rms-norm"); let weight = weight.dequantize(&weight.device())?; Ok(Self { weight, eps, span }) } } impl Module for RmsNorm { fn forward(&self, x: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); candle_nn::ops::rms_norm(x, &self.weight, self.eps as f32) } }
candle/candle-transformers/src/quantized_nn.rs/0
{ "file_path": "candle/candle-transformers/src/quantized_nn.rs", "repo_id": "candle", "token_count": 1681 }
65
//load the candle Whisper decoder wasm module import init, { Decoder } from "./build/m.js"; async function fetchArrayBuffer(url) { const cacheName = "whisper-candle-cache"; const cache = await caches.open(cacheName); const cachedResponse = await cache.match(url); if (cachedResponse) { const data = await cachedResponse.arrayBuffer(); return new Uint8Array(data); } const res = await fetch(url, { cache: "force-cache" }); cache.put(url, res.clone()); return new Uint8Array(await res.arrayBuffer()); } class Whisper { static instance = {}; // Retrieve the Whisper model. When called for the first time, // this will load the model and save it for future use. static async getInstance(params) { const { weightsURL, modelID, tokenizerURL, mel_filtersURL, configURL, quantized, is_multilingual, timestamps, task, language, } = params; // load individual modelID only once if (!this.instance[modelID]) { await init(); self.postMessage({ status: "loading", message: "Loading Model" }); const [ weightsArrayU8, tokenizerArrayU8, mel_filtersArrayU8, configArrayU8, ] = await Promise.all([ fetchArrayBuffer(weightsURL), fetchArrayBuffer(tokenizerURL), fetchArrayBuffer(mel_filtersURL), fetchArrayBuffer(configURL), ]); this.instance[modelID] = new Decoder( weightsArrayU8, tokenizerArrayU8, mel_filtersArrayU8, configArrayU8, quantized, is_multilingual, timestamps, task, language ); } else { self.postMessage({ status: "loading", message: "Model Already Loaded" }); } return this.instance[modelID]; } } self.addEventListener("message", async (event) => { const { weightsURL, modelID, tokenizerURL, configURL, mel_filtersURL, audioURL, } = event.data; try { self.postMessage({ status: "decoding", message: "Starting Decoder" }); let quantized = false; if (modelID.includes("quantized")) { quantized = true; } let is_multilingual = false; if (modelID.includes("multilingual")) { is_multilingual = true; } let timestamps = true; const decoder = await Whisper.getInstance({ weightsURL, modelID, tokenizerURL, mel_filtersURL, configURL, quantized, is_multilingual, timestamps, task: null, language: null, }); self.postMessage({ status: "decoding", message: "Loading Audio" }); const audioArrayU8 = await fetchArrayBuffer(audioURL); self.postMessage({ status: "decoding", message: "Running Decoder..." }); const segments = decoder.decode(audioArrayU8); // Send the segment back to the main thread as JSON self.postMessage({ status: "complete", message: "complete", output: JSON.parse(segments), }); } catch (e) { self.postMessage({ error: e }); } });
candle/candle-wasm-examples/whisper/whisperWorker.js/0
{ "file_path": "candle/candle-wasm-examples/whisper/whisperWorker.js", "repo_id": "candle", "token_count": 1215 }
66
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.
candle/candle-wasm-tests/README.md/0
{ "file_path": "candle/candle-wasm-tests/README.md", "repo_id": "candle", "token_count": 98 }
67
# Chat UI **Find the docs at [hf.co/docs/chat-ui](https://huggingface.co/docs/chat-ui/index).** ![Chat UI repository thumbnail](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/chatui-websearch.png) A chat interface using open source models, eg OpenAssistant or Llama. It is a SvelteKit app and it powers the [HuggingChat app on hf.co/chat](https://huggingface.co/chat). 0. [Quickstart](#quickstart) 1. [No Setup Deploy](#no-setup-deploy) 2. [Setup](#setup) 3. [Launch](#launch) 4. [Web Search](#web-search) 5. [Text Embedding Models](#text-embedding-models) 6. [Extra parameters](#extra-parameters) 7. [Common issues](#common-issues) 8. [Deploying to a HF Space](#deploying-to-a-hf-space) 9. [Building](#building) ## Quickstart ### Docker image You can deploy a chat-ui instance in a single command using the docker image. Get your huggingface token from [here](https://huggingface.co/settings/tokens). ```bash docker run -p 3000 -e HF_TOKEN=hf_*** -v db:/data ghcr.io/huggingface/chat-ui-db:latest ``` Take a look at the [`.env` file](https://github.com/huggingface/chat-ui/blob/main/.env) and the readme to see all the environment variables that you can set. We have endpoint support for all OpenAI API compatible local services as well as many other providers like Anthropic, Cloudflare, Google Vertex AI, etc. ### Local setup You can quickly start a locally running chat-ui & LLM text-generation server thanks to chat-ui's [llama.cpp server support](https://huggingface.co/docs/chat-ui/configuration/models/providers/llamacpp). **Step 1 (Start llama.cpp server):** Install llama.cpp w/ brew (for Mac): ```bash # install llama.cpp brew install llama.cpp ``` or [build directly from the source](https://github.com/ggerganov/llama.cpp/blob/master/docs/build.md) for your target device: ``` git clone https://github.com/ggerganov/llama.cpp && cd llama.cpp && make ``` Next, start the server with the [LLM of your choice](https://huggingface.co/models?library=gguf): ```bash # start llama.cpp server (using hf.co/microsoft/Phi-3-mini-4k-instruct-gguf as an example) llama-server --hf-repo microsoft/Phi-3-mini-4k-instruct-gguf --hf-file Phi-3-mini-4k-instruct-q4.gguf -c 4096 ``` A local LLaMA.cpp HTTP Server will start on `http://localhost:8080`. Read more [here](https://huggingface.co/docs/chat-ui/configuration/models/providers/llamacpp). **Step 3 (make sure you have MongoDb running locally):** ```bash docker run -d -p 27017:27017 --name mongo-chatui mongo:latest ``` Read more [here](#database). **Step 4 (clone chat-ui):** ```bash git clone https://github.com/huggingface/chat-ui cd chat-ui ``` **Step 5 (tell chat-ui to use local llama.cpp server):** Add the following to your `.env.local`: ```ini MODELS=`[ { "name": "microsoft/Phi-3-mini-4k-instruct", "endpoints": [{ "type" : "llamacpp", "baseURL": "http://localhost:8080" }], }, ]` ``` Read more [here](https://huggingface.co/docs/chat-ui/configuration/models/providers/llamacpp). **Step 6 (start chat-ui):** ```bash npm install npm run dev -- --open ``` Read more [here](#launch). <img class="hidden dark:block" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/chat-ui/llamacpp-dark.png" height="auto"/> ## No Setup Deploy If you don't want to configure, setup, and launch your own Chat UI yourself, you can use this option as a fast deploy alternative. You can deploy your own customized Chat UI instance with any supported [LLM](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending) of your choice on [Hugging Face Spaces](https://huggingface.co/spaces). To do so, use the chat-ui template [available here](https://huggingface.co/new-space?template=huggingchat/chat-ui-template). Set `HF_TOKEN` in [Space secrets](https://huggingface.co/docs/hub/spaces-overview#managing-secrets) to deploy a model with gated access or a model in a private repository. It's also compatible with [Inference for PROs](https://huggingface.co/blog/inference-pro) curated list of powerful models with higher rate limits. Make sure to create your personal token first in your [User Access Tokens settings](https://huggingface.co/settings/tokens). Read the full tutorial [here](https://huggingface.co/docs/hub/spaces-sdks-docker-chatui#chatui-on-spaces). ## Setup The default config for Chat UI is stored in the `.env` file. You will need to override some values to get Chat UI to run locally. This is done in `.env.local`. Start by creating a `.env.local` file in the root of the repository. The bare minimum config you need to get Chat UI to run locally is the following: ```env MONGODB_URL=<the URL to your MongoDB instance> HF_TOKEN=<your access token> ``` ### Database The chat history is stored in a MongoDB instance, and having a DB instance available is needed for Chat UI to work. You can use a local MongoDB instance. The easiest way is to spin one up using docker: ```bash docker run -d -p 27017:27017 --name mongo-chatui mongo:latest ``` In which case the url of your DB will be `MONGODB_URL=mongodb://localhost:27017`. Alternatively, you can use a [free MongoDB Atlas](https://www.mongodb.com/pricing) instance for this, Chat UI should fit comfortably within their free tier. After which you can set the `MONGODB_URL` variable in `.env.local` to match your instance. ### Hugging Face Access Token If you use a remote inference endpoint, you will need a Hugging Face access token to run Chat UI locally. You can get one from [your Hugging Face profile](https://huggingface.co/settings/tokens). ## Launch After you're done with the `.env.local` file you can run Chat UI locally with: ```bash npm install npm run dev ``` ## Web Search Chat UI features a powerful Web Search feature. It works by: 1. Generating an appropriate search query from the user prompt. 2. Performing web search and extracting content from webpages. 3. Creating embeddings from texts using a text embedding model. 4. From these embeddings, find the ones that are closest to the user query using a vector similarity search. Specifically, we use `inner product` distance. 5. Get the corresponding texts to those closest embeddings and perform [Retrieval-Augmented Generation](https://huggingface.co/papers/2005.11401) (i.e. expand user prompt by adding those texts so that an LLM can use this information). ## Text Embedding Models By default (for backward compatibility), when `TEXT_EMBEDDING_MODELS` environment variable is not defined, [transformers.js](https://huggingface.co/docs/transformers.js) embedding models will be used for embedding tasks, specifically, [Xenova/gte-small](https://huggingface.co/Xenova/gte-small) model. You can customize the embedding model by setting `TEXT_EMBEDDING_MODELS` in your `.env.local` file. For example: ```env TEXT_EMBEDDING_MODELS = `[ { "name": "Xenova/gte-small", "displayName": "Xenova/gte-small", "description": "locally running embedding", "chunkCharLength": 512, "endpoints": [ {"type": "transformersjs"} ] }, { "name": "intfloat/e5-base-v2", "displayName": "intfloat/e5-base-v2", "description": "hosted embedding model", "chunkCharLength": 768, "preQuery": "query: ", # See https://huggingface.co/intfloat/e5-base-v2#faq "prePassage": "passage: ", # See https://huggingface.co/intfloat/e5-base-v2#faq "endpoints": [ { "type": "tei", "url": "http://127.0.0.1:8080/", "authorization": "TOKEN_TYPE TOKEN" // optional authorization field. Example: "Basic VVNFUjpQQVNT" } ] } ]` ``` The required fields are `name`, `chunkCharLength` and `endpoints`. Supported text embedding backends are: [`transformers.js`](https://huggingface.co/docs/transformers.js), [`TEI`](https://github.com/huggingface/text-embeddings-inference) and [`OpenAI`](https://platform.openai.com/docs/guides/embeddings). `transformers.js` models run locally as part of `chat-ui`, whereas `TEI` models run in a different environment & accessed through an API endpoint. `openai` models are accessed through the [OpenAI API](https://platform.openai.com/docs/guides/embeddings). When more than one embedding models are supplied in `.env.local` file, the first will be used by default, and the others will only be used on LLM's which configured `embeddingModel` to the name of the model. ## Extra parameters ### OpenID connect The login feature is disabled by default and users are attributed a unique ID based on their browser. But if you want to use OpenID to authenticate your users, you can add the following to your `.env.local` file: ```env OPENID_CONFIG=`{ PROVIDER_URL: "<your OIDC issuer>", CLIENT_ID: "<your OIDC client ID>", CLIENT_SECRET: "<your OIDC client secret>", SCOPES: "openid profile", TOLERANCE: // optional RESOURCE: // optional }` ``` These variables will enable the openID sign-in modal for users. ### Trusted header authentication You can set the env variable `TRUSTED_EMAIL_HEADER` to point to the header that contains the user's email address. This will allow you to authenticate users from the header. This setup is usually combined with a proxy that will be in front of chat-ui and will handle the auth and set the header. > [!WARNING] > Make sure to only allow requests to chat-ui through your proxy which handles authentication, otherwise users could authenticate as anyone by setting the header manually! Only set this up if you understand the implications and know how to do it correctly. Here is a list of header names for common auth providers: - Tailscale Serve: `Tailscale-User-Login` - Cloudflare Access: `Cf-Access-Authenticated-User-Email` - oauth2-proxy: `X-Forwarded-Email` ### Theming You can use a few environment variables to customize the look and feel of chat-ui. These are by default: ```env PUBLIC_APP_NAME=ChatUI PUBLIC_APP_ASSETS=chatui PUBLIC_APP_COLOR=blue PUBLIC_APP_DESCRIPTION="Making the community's best AI chat models available to everyone." PUBLIC_APP_DATA_SHARING= PUBLIC_APP_DISCLAIMER= ``` - `PUBLIC_APP_NAME` The name used as a title throughout the app. - `PUBLIC_APP_ASSETS` Is used to find logos & favicons in `static/$PUBLIC_APP_ASSETS`, current options are `chatui` and `huggingchat`. - `PUBLIC_APP_COLOR` Can be any of the [tailwind colors](https://tailwindcss.com/docs/customizing-colors#default-color-palette). - `PUBLIC_APP_DATA_SHARING` Can be set to 1 to add a toggle in the user settings that lets your users opt-in to data sharing with models creator. - `PUBLIC_APP_DISCLAIMER` If set to 1, we show a disclaimer about generated outputs on login. ### Web Search config You can enable the web search through an API by adding `YDC_API_KEY` ([docs.you.com](https://docs.you.com)) or `SERPER_API_KEY` ([serper.dev](https://serper.dev/)) or `SERPAPI_KEY` ([serpapi.com](https://serpapi.com/)) or `SERPSTACK_API_KEY` ([serpstack.com](https://serpstack.com/)) or `SEARCHAPI_KEY` ([searchapi.io](https://www.searchapi.io/)) to your `.env.local`. You can also simply enable the local google websearch by setting `USE_LOCAL_WEBSEARCH=true` in your `.env.local` or specify a SearXNG instance by adding the query URL to `SEARXNG_QUERY_URL`. You can enable javascript when parsing webpages to improve compatibility with `WEBSEARCH_JAVASCRIPT=true` at the cost of increased CPU usage. You'll want at least 4 cores when enabling. ### Custom models You can customize the parameters passed to the model or even use a new model by updating the `MODELS` variable in your `.env.local`. The default one can be found in `.env` and looks like this : ```env MODELS=`[ { "name": "mistralai/Mistral-7B-Instruct-v0.2", "displayName": "mistralai/Mistral-7B-Instruct-v0.2", "description": "Mistral 7B is a new Apache 2.0 model, released by Mistral AI that outperforms Llama2 13B in benchmarks.", "websiteUrl": "https://mistral.ai/news/announcing-mistral-7b/", "preprompt": "", "chatPromptTemplate" : "<s>{{#each messages}}{{#ifUser}}[INST] {{#if @first}}{{#if @root.preprompt}}{{@root.preprompt}}\n{{/if}}{{/if}}{{content}} [/INST]{{/ifUser}}{{#ifAssistant}}{{content}}</s>{{/ifAssistant}}{{/each}}", "parameters": { "temperature": 0.3, "top_p": 0.95, "repetition_penalty": 1.2, "top_k": 50, "truncate": 3072, "max_new_tokens": 1024, "stop": ["</s>"] }, "promptExamples": [ { "title": "Write an email", "prompt": "As a restaurant owner, write a professional email to the supplier to get these products every week: \n\n- Wine (x10)\n- Eggs (x24)\n- Bread (x12)" }, { "title": "Code a game", "prompt": "Code a basic snake game in python, give explanations for each step." }, { "title": "Recipe help", "prompt": "How do I make a delicious lemon cheesecake?" } ] } ]` ``` You can change things like the parameters, or customize the preprompt to better suit your needs. You can also add more models by adding more objects to the array, with different preprompts for example. #### chatPromptTemplate In 2025 most chat-completion endpoints (local or remotely hosted) support the OpenAI-compatible API and take arrays of messages. If not, when querying the model for a chat response, the `chatPromptTemplate` template is used. `messages` is an array of chat messages, it has the format `[{ content: string }, ...]`. To identify if a message is a user message or an assistant message the `ifUser` and `ifAssistant` block helpers can be used. The following is the default `chatPromptTemplate`, although newlines and indentiation have been added for readability. You can find the prompts used in production for HuggingChat [here](https://github.com/huggingface/chat-ui/blob/main/PROMPTS.md). ```prompt {{preprompt}} {{#each messages}} {{#ifUser}}{{@root.userMessageToken}}{{content}}{{@root.userMessageEndToken}}{{/ifUser}} {{#ifAssistant}}{{@root.assistantMessageToken}}{{content}}{{@root.assistantMessageEndToken}}{{/ifAssistant}} {{/each}} {{assistantMessageToken}} ``` > [!INFO] > We also support Jinja2 templates for the `chatPromptTemplate` in addition to Handlebars templates. On startup we first try to compile with Jinja and if that fails we fall back to interpreting `chatPromptTemplate` as handlebars. #### Multi modal model We currently support [IDEFICS](https://huggingface.co/blog/idefics) (hosted on TGI), OpenAI and Claude 3 as multimodal models. You can enable it by setting `multimodal: true` in your `MODELS` configuration. For IDEFICS, you must have a [PRO HF Api token](https://huggingface.co/settings/tokens). For OpenAI, see the [OpenAI section](#openai-api-compatible-models). For Anthropic, see the [Anthropic section](#anthropic). ```env { "name": "HuggingFaceM4/idefics-80b-instruct", "multimodal" : true, "description": "IDEFICS is the new multimodal model by Hugging Face.", "preprompt": "", "chatPromptTemplate" : "{{#each messages}}{{#ifUser}}User: {{content}}{{/ifUser}}<end_of_utterance>\nAssistant: {{#ifAssistant}}{{content}}\n{{/ifAssistant}}{{/each}}", "parameters": { "temperature": 0.1, "top_p": 0.95, "repetition_penalty": 1.2, "top_k": 12, "truncate": 1000, "max_new_tokens": 1024, "stop": ["<end_of_utterance>", "User:", "\nUser:"] } } ``` #### Running your own models using a custom endpoint If you want to, instead of hitting models on the Hugging Face Inference API, you can run your own models locally. A good option is to hit a [text-generation-inference](https://github.com/huggingface/text-generation-inference), or a llama.cpp endpoint. You will find an example for TGI in the official [Chat UI Spaces Docker template](https://huggingface.co/new-space?template=huggingchat/chat-ui-template) for instance: both this app and a text-generation-inference server run inside the same container. To do this, you can add your own endpoints to the `MODELS` variable in `.env.local`, by adding an `"endpoints"` key for each model in `MODELS`. ```env { // rest of the model config here "endpoints": [{ "type" : "tgi", "url": "https://HOST:PORT", }] } ``` If `endpoints` are left unspecified, ChatUI will look for the model on the hosted Hugging Face inference API using the model name. ##### OpenAI API compatible models Chat UI can be used with any API server that supports OpenAI API compatibility, for example [text-generation-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai), [LocalAI](https://github.com/go-skynet/LocalAI), [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md), [llama-cpp-python](https://github.com/abetlen/llama-cpp-python), and [ialacol](https://github.com/chenhunghan/ialacol) and [vllm](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html). The following example config makes Chat UI works with [text-generation-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai), the `endpoint.baseUrl` is the url of the OpenAI API compatible server, this overrides the baseUrl to be used by OpenAI instance. The `endpoint.completion` determine which endpoint to be used, default is `chat_completions` which uses `v1/chat/completions`, change to `endpoint.completion` to `completions` to use the `v1/completions` endpoint. Parameters not supported by OpenAI (e.g., top_k, repetition_penalty, etc.) must be set in the extraBody of endpoints. Be aware that setting them in parameters will cause them to be omitted. ``` MODELS=`[ { "name": "text-generation-webui", "id": "text-generation-webui", "parameters": { "temperature": 0.9, "top_p": 0.95, "max_new_tokens": 1024, "stop": [] }, "endpoints": [{ "type" : "openai", "baseURL": "http://localhost:8000/v1", "extraBody": { "repetition_penalty": 1.2, "top_k": 50, "truncate": 1000 } }] } ]` ``` The `openai` type includes official OpenAI models. You can add, for example, GPT4/GPT3.5 as a "openai" model: ``` OPENAI_API_KEY=#your openai api key here MODELS=`[{ "name": "gpt-4", "displayName": "GPT 4", "endpoints" : [{ "type": "openai" }] }, { "name": "gpt-3.5-turbo", "displayName": "GPT 3.5 Turbo", "endpoints" : [{ "type": "openai" }] }]` ``` You may also consume any model provider that provides compatible OpenAI API endpoint. For example, you may self-host [Portkey](https://github.com/Portkey-AI/gateway) gateway and experiment with Claude or GPTs offered by Azure OpenAI. Example for Claude from Anthropic: ``` MODELS=`[{ "name": "claude-2.1", "displayName": "Claude 2.1", "description": "Anthropic has been founded by former OpenAI researchers...", "parameters": { "temperature": 0.5, "max_new_tokens": 4096, }, "endpoints": [ { "type": "openai", "baseURL": "https://gateway.example.com/v1", "defaultHeaders": { "x-portkey-config": '{"provider":"anthropic","api_key":"sk-ant-abc...xyz"}' } } ] }]` ``` Example for GPT 4 deployed on Azure OpenAI: ``` MODELS=`[{ "id": "gpt-4-1106-preview", "name": "gpt-4-1106-preview", "displayName": "gpt-4-1106-preview", "parameters": { "temperature": 0.5, "max_new_tokens": 4096, }, "endpoints": [ { "type": "openai", "baseURL": "https://{resource-name}.openai.azure.com/openai/deployments/{deployment-id}", "defaultHeaders": { "api-key": "{api-key}" }, "defaultQuery": { "api-version": "2023-05-15" } } ] }]` ``` Or try Mistral from [Deepinfra](https://deepinfra.com/mistralai/Mistral-7B-Instruct-v0.1/api?example=openai-http): > Note, apiKey can either be set custom per endpoint, or globally using `OPENAI_API_KEY` variable. ``` MODELS=`[{ "name": "mistral-7b", "displayName": "Mistral 7B", "description": "A 7B dense Transformer, fast-deployed and easily customisable. Small, yet powerful for a variety of use cases. Supports English and code, and a 8k context window.", "parameters": { "temperature": 0.5, "max_new_tokens": 4096, }, "endpoints": [ { "type": "openai", "baseURL": "https://api.deepinfra.com/v1/openai", "apiKey": "abc...xyz" } ] }]` ``` _Non-streaming endpoints_ For endpoints that don´t support streaming like o1 on Azure, you can pass `streamingSupported: false` in your endpoint config: ``` MODELS=`[{ "id": "o1-preview", "name": "o1-preview", "displayName": "o1-preview", "systemRoleSupported": false, "endpoints": [ { "type": "openai", "baseURL": "https://my-deployment.openai.azure.com/openai/deployments/o1-preview", "defaultHeaders": { "api-key": "$SECRET" }, "streamingSupported": false, } ] }]` ``` ##### Llama.cpp API server chat-ui also supports the llama.cpp API server directly without the need for an adapter. You can do this using the `llamacpp` endpoint type. If you want to run Chat UI with llama.cpp, you can do the following, using [microsoft/Phi-3-mini-4k-instruct-gguf](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-gguf) as an example model: ```bash # install llama.cpp brew install llama.cpp # start llama.cpp server llama-server --hf-repo microsoft/Phi-3-mini-4k-instruct-gguf --hf-file Phi-3-mini-4k-instruct-q4.gguf -c 4096 ``` ```env MODELS=`[ { "name": "Local Zephyr", "chatPromptTemplate": "<|system|>\n{{preprompt}}</s>\n{{#each messages}}{{#ifUser}}<|user|>\n{{content}}</s>\n<|assistant|>\n{{/ifUser}}{{#ifAssistant}}{{content}}</s>\n{{/ifAssistant}}{{/each}}", "parameters": { "temperature": 0.1, "top_p": 0.95, "repetition_penalty": 1.2, "top_k": 50, "truncate": 1000, "max_new_tokens": 2048, "stop": ["</s>"] }, "endpoints": [ { "url": "http://127.0.0.1:8080", "type": "llamacpp" } ] } ]` ``` Start chat-ui with `npm run dev` and you should be able to chat with Zephyr locally. #### Ollama We also support the Ollama inference server. Spin up a model with ```cli ollama run mistral ``` Then specify the endpoints like so: ```env MODELS=`[ { "name": "Ollama Mistral", "chatPromptTemplate": "<s>{{#each messages}}{{#ifUser}}[INST] {{#if @first}}{{#if @root.preprompt}}{{@root.preprompt}}\n{{/if}}{{/if}} {{content}} [/INST]{{/ifUser}}{{#ifAssistant}}{{content}}</s> {{/ifAssistant}}{{/each}}", "parameters": { "temperature": 0.1, "top_p": 0.95, "repetition_penalty": 1.2, "top_k": 50, "truncate": 3072, "max_new_tokens": 1024, "stop": ["</s>"] }, "endpoints": [ { "type": "ollama", "url" : "http://127.0.0.1:11434", "ollamaName" : "mistral" } ] } ]` ``` #### Anthropic We also support Anthropic models (including multimodal ones via `multmodal: true`) through the official SDK. You may provide your API key via the `ANTHROPIC_API_KEY` env variable, or alternatively, through the `endpoints.apiKey` as per the following example. ``` MODELS=`[ { "name": "claude-3-haiku-20240307", "displayName": "Claude 3 Haiku", "description": "Fastest and most compact model for near-instant responsiveness", "multimodal": true, "parameters": { "max_new_tokens": 4096, }, "endpoints": [ { "type": "anthropic", // optionals "apiKey": "sk-ant-...", "baseURL": "https://api.anthropic.com", "defaultHeaders": {}, "defaultQuery": {} } ] }, { "name": "claude-3-sonnet-20240229", "displayName": "Claude 3 Sonnet", "description": "Ideal balance of intelligence and speed", "multimodal": true, "parameters": { "max_new_tokens": 4096, }, "endpoints": [ { "type": "anthropic", // optionals "apiKey": "sk-ant-...", "baseURL": "https://api.anthropic.com", "defaultHeaders": {}, "defaultQuery": {} } ] }, { "name": "claude-3-opus-20240229", "displayName": "Claude 3 Opus", "description": "Most powerful model for highly complex tasks", "multimodal": true, "parameters": { "max_new_tokens": 4096 }, "endpoints": [ { "type": "anthropic", // optionals "apiKey": "sk-ant-...", "baseURL": "https://api.anthropic.com", "defaultHeaders": {}, "defaultQuery": {} } ] } ]` ``` We also support using Anthropic models running on Vertex AI. Authentication is done using Google Application Default Credentials. Project ID can be provided through the `endpoints.projectId` as per the following example: ``` MODELS=`[ { "name": "claude-3-sonnet@20240229", "displayName": "Claude 3 Sonnet", "description": "Ideal balance of intelligence and speed", "multimodal": true, "parameters": { "max_new_tokens": 4096, }, "endpoints": [ { "type": "anthropic-vertex", "region": "us-central1", "projectId": "gcp-project-id", // optionals "defaultHeaders": {}, "defaultQuery": {} } ] }, { "name": "claude-3-haiku@20240307", "displayName": "Claude 3 Haiku", "description": "Fastest, most compact model for near-instant responsiveness", "multimodal": true, "parameters": { "max_new_tokens": 4096 }, "endpoints": [ { "type": "anthropic-vertex", "region": "us-central1", "projectId": "gcp-project-id", // optionals "defaultHeaders": {}, "defaultQuery": {} } ] } ]` ``` #### Amazon You can also specify your Amazon SageMaker instance as an endpoint for chat-ui. The config goes like this: ```env "endpoints": [ { "type" : "aws", "service" : "sagemaker" "url": "", "accessKey": "", "secretKey" : "", "sessionToken": "", "region": "", "weight": 1 } ] ``` You can also set `"service" : "lambda"` to use a lambda instance. You can get the `accessKey` and `secretKey` from your AWS user, under programmatic access. #### Cloudflare Workers AI You can also use Cloudflare Workers AI to run your own models with serverless inference. You will need to have a Cloudflare account, then get your [account ID](https://developers.cloudflare.com/fundamentals/setup/find-account-and-zone-ids/) as well as your [API token](https://developers.cloudflare.com/workers-ai/get-started/rest-api/#1-get-api-token-and-account-id) for Workers AI. You can either specify them directly in your `.env.local` using the `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` variables, or you can set them directly in the endpoint config. You can find the list of models available on Cloudflare [here](https://developers.cloudflare.com/workers-ai/models/#text-generation). ```env { "name" : "nousresearch/hermes-2-pro-mistral-7b", "tokenizer": "nousresearch/hermes-2-pro-mistral-7b", "parameters": { "stop": ["<|im_end|>"] }, "endpoints" : [ { "type" : "cloudflare" <!-- optionally specify these "accountId": "your-account-id", "authToken": "your-api-token" --> } ] } ``` #### Cohere You can also use Cohere to run their models directly from chat-ui. You will need to have a Cohere account, then get your [API token](https://dashboard.cohere.com/api-keys). You can either specify it directly in your `.env.local` using the `COHERE_API_TOKEN` variable, or you can set it in the endpoint config. Here is an example of a Cohere model config. You can set which model you want to use by setting the `id` field to the model name. ```env { "name" : "CohereForAI/c4ai-command-r-v01", "id": "command-r", "description": "C4AI Command-R is a research release of a 35 billion parameter highly performant generative model", "endpoints": [ { "type": "cohere", <!-- optionally specify these, or use COHERE_API_TOKEN "apiKey": "your-api-token" --> } ] } ``` ##### Google Vertex models Chat UI can connect to the google Vertex API endpoints ([List of supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models)). To enable: 1. [Select](https://console.cloud.google.com/project) or [create](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project) a Google Cloud project. 1. [Enable billing for your project](https://cloud.google.com/billing/docs/how-to/modify-project). 1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). 1. [Set up authentication with a service account](https://cloud.google.com/docs/authentication/getting-started) so you can access the API from your local workstation. The service account credentials file can be imported as an environmental variable: ```env GOOGLE_APPLICATION_CREDENTIALS = clientid.json ``` Make sure your docker container has access to the file and the variable is correctly set. Afterwards Google Vertex endpoints can be configured as following: ``` MODELS=`[ //... { "name": "gemini-1.5-pro", "displayName": "Vertex Gemini Pro 1.5", "multimodal": true, "endpoints" : [{ "type": "vertex", "project": "abc-xyz", "location": "europe-west3", "extraBody": { "model_version": "gemini-1.5-pro-preview-0409", }, // Optional "safetyThreshold": "BLOCK_MEDIUM_AND_ABOVE", "apiEndpoint": "", // alternative api endpoint url, "tools": [{ "googleSearchRetrieval": { "disableAttribution": true } }], "multimodal": { "image": { "supportedMimeTypes": ["image/png", "image/jpeg", "image/webp"], "preferredMimeType": "image/png", "maxSizeInMB": 5, "maxWidth": 2000, "maxHeight": 1000, } } }] }, ]` ``` ##### LangServe LangChain applications that are deployed using LangServe can be called with the following config: ``` MODELS=`[ //... { "name": "summarization-chain", //model-name "endpoints" : [{ "type": "langserve", "url" : "http://127.0.0.1:8100", }] }, ]` ``` ### Model Context Protocol (MCP) Support (Upcoming) The project is planning to introduce support for the Model Context Protocol (MCP). MCP is a specification designed to standardize how language models receive and understand context from various sources. This will enable more flexible and powerful integrations, allowing models to seamlessly access and utilize a broader range of information, such as user history, external documents, or real-time data, in a structured way. This is an upcoming feature, and we believe it will significantly enhance the capabilities and extensibility of Chat UI. We are actively seeking contributions from the community to help design, implement, and integrate MCP support into Chat UI. If you are interested in shaping the future of how Chat UI handles model context and want to contribute to this exciting development, please look for issues tagged with 'MCP' or 'Model Context Protocol' on our issue tracker. Your expertise and input would be invaluable! ### Custom endpoint authorization #### Basic and Bearer Custom endpoints may require authorization, depending on how you configure them. Authentication will usually be set either with `Basic` or `Bearer`. For `Basic` we will need to generate a base64 encoding of the username and password. `echo -n "USER:PASS" | base64` > VVNFUjpQQVNT For `Bearer` you can use a token, which can be grabbed from [here](https://huggingface.co/settings/tokens). You can then add the generated information and the `authorization` parameter to your `.env.local`. ```env "endpoints": [ { "url": "https://HOST:PORT", "authorization": "Basic VVNFUjpQQVNT", } ] ``` Please note that if `HF_TOKEN` is also set or not empty, it will take precedence. #### Models hosted on multiple custom endpoints If the model being hosted will be available on multiple servers/instances add the `weight` parameter to your `.env.local`. The `weight` will be used to determine the probability of requesting a particular endpoint. ```env "endpoints": [ { "url": "https://HOST:PORT", "weight": 1 }, { "url": "https://HOST:PORT", "weight": 2 } ... ] ``` #### Client Certificate Authentication (mTLS) Custom endpoints may require client certificate authentication, depending on how you configure them. To enable mTLS between Chat UI and your custom endpoint, you will need to set the `USE_CLIENT_CERTIFICATE` to `true`, and add the `CERT_PATH` and `KEY_PATH` parameters to your `.env.local`. These parameters should point to the location of the certificate and key files on your local machine. The certificate and key files should be in PEM format. The key file can be encrypted with a passphrase, in which case you will also need to add the `CLIENT_KEY_PASSWORD` parameter to your `.env.local`. If you're using a certificate signed by a private CA, you will also need to add the `CA_PATH` parameter to your `.env.local`. This parameter should point to the location of the CA certificate file on your local machine. If you're using a self-signed certificate, e.g. for testing or development purposes, you can set the `REJECT_UNAUTHORIZED` parameter to `false` in your `.env.local`. This will disable certificate validation, and allow Chat UI to connect to your custom endpoint. #### Specific Embedding Model A model can use any of the embedding models defined in `.env.local`, (currently used when web searching), by default it will use the first embedding model, but it can be changed with the field `embeddingModel`: ```env TEXT_EMBEDDING_MODELS = `[ { "name": "Xenova/gte-small", "chunkCharLength": 512, "endpoints": [ {"type": "transformersjs"} ] }, { "name": "intfloat/e5-base-v2", "chunkCharLength": 768, "endpoints": [ {"type": "tei", "url": "http://127.0.0.1:8080/", "authorization": "Basic VVNFUjpQQVNT"}, {"type": "tei", "url": "http://127.0.0.1:8081/"} ] } ]` MODELS=`[ { "name": "Ollama Mistral", "chatPromptTemplate": "...", "embeddingModel": "intfloat/e5-base-v2" "parameters": { ... }, "endpoints": [ ... ] } ]` ``` ### Reasoning Models ChatUI supports specialized reasoning/Chain-of-Thought (CoT) models through the `reasoning` configuration field. When properly configured, this displays a UI widget that allows users to view or collapse the model’s reasoning steps. We support three types of reasoning parsing: #### Token-Based Delimitations For models like DeepSeek R1, token-based delimitations can be used to identify reasoning steps. This is done by specifying the `beginToken` and `endToken` fields in the `reasoning` configuration. Example configuration for DeepSeek R1 (token-based): ```json { "name": "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", // ... "reasoning": { "type": "tokens", "beginToken": "<think>", "endToken": "</think>" } } ``` #### Summarizing the Chain of Thought For models like QwQ, which return a chain of thought but do not explicitly provide a final answer, the `summarize` type can be used. This automatically summarizes the reasoning steps using the `TASK_MODEL` (or the first model in the configuration if `TASK_MODEL` is not specified) and displays the summary as the final answer. Example configuration for QwQ (summarize-based): ```json { "name": "Qwen/QwQ-32B-Preview", // ... "reasoning": { "type": "summarize" } } ``` #### Regex-Based Delimitations In some cases, the final answer can be extracted from the model output using a regular expression. This is achieved by specifying the `regex` field in the `reasoning` configuration. For example, if your model wraps the final answer in a `\boxed{}` tag, you can use the following configuration: ```json { "name": "model/yourmodel", // ... "reasoning": { "type": "regex", "regex": "\\\\boxed\\{(.+?)\\}" } } ``` #### Enabling/Disabling Reasoning Summary You can toggle the summaries that are displayed alongside the CoT by changing the `REASONING_SUMMARY` env variable. ```env REASONING_SUMMARY=false ``` ## Common issues ### 403:You don't have access to this conversation Most likely you are running chat-ui over HTTP. The recommended option is to setup something like NGINX to handle HTTPS and proxy the requests to chat-ui. If you really need to run over HTTP you can add `COOKIE_SECURE=false` and `COOKIE_SAMESITE=lax` to your `.env.local`. Make sure to set your `PUBLIC_ORIGIN` in your `.env.local` to the correct URL as well. ## Deploying to a HF Space Create a `DOTENV_LOCAL` secret to your HF space with the content of your .env.local, and they will be picked up automatically when you run. ## Building To create a production version of your app: ```bash npm run build ``` You can preview the production build with `npm run preview`. > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment. ## Config changes for HuggingChat The config file for HuggingChat is stored in the `chart/env/prod.yaml` file. It is the source of truth for the environment variables used for our CI/CD pipeline. For HuggingChat, as we need to customize the app color, as well as the base path, we build a custom docker image. You can find the workflow here. > [!TIP] > If you want to make changes to the model config used in production for HuggingChat, you should do so against `chart/env/prod.yaml`. ### Running a copy of HuggingChat locally If you want to run an exact copy of HuggingChat locally, you will need to do the following first: 1. Create an [OAuth App on the hub](https://huggingface.co/settings/applications/new) with `openid profile email` permissions. Make sure to set the callback URL to something like `http://localhost:5173/chat/login/callback` which matches the right path for your local instance. 2. Create a [HF Token](https://huggingface.co/settings/tokens) with your Hugging Face account. You will need a Pro account to be able to access some of the larger models available through HuggingChat. 3. Create a free account with [serper.dev](https://serper.dev/) (you will get 2500 free search queries) 4. Run an instance of mongoDB, however you want. (Local or remote) You can then create a new `.env.SECRET_CONFIG` file with the following content ```env MONGODB_URL=<link to your mongo DB from step 4> HF_TOKEN=<your HF token from step 2> OPENID_CONFIG=`{ PROVIDER_URL: "https://huggingface.co", CLIENT_ID: "<your client ID from step 1>", CLIENT_SECRET: "<your client secret from step 1>", }` SERPER_API_KEY=<your serper API key from step 3> MESSAGES_BEFORE_LOGIN=<can be any numerical value, or set to 0 to require login> ``` You can then run `npm run updateLocalEnv` in the root of chat-ui. This will create a `.env.local` file which combines the `chart/env/prod.yaml` and the `.env.SECRET_CONFIG` file. You can then run `npm run dev` to start your local instance of HuggingChat. ### Populate database > [!WARNING] > The `MONGODB_URL` used for this script will be fetched from `.env.local`. Make sure it's correct! The command runs directly on the database. You can populate the database using faker data using the `populate` script: ```bash npm run populate <flags here> ``` At least one flag must be specified, the following flags are available: - `reset` - resets the database - `all` - populates all tables - `users` - populates the users table - `settings` - populates the settings table for existing users - `assistants` - populates the assistants table for existing users - `conversations` - populates the conversations table for existing users For example, you could use it like so: ```bash npm run populate reset ``` to clear out the database. Then login in the app to create your user and run the following command: ```bash npm run populate users settings assistants conversations ``` to populate the database with fake data, including fake conversations and assistants for your user. ## Building the docker images locally You can build the docker images locally using the following commands: ```bash docker build -t chat-ui-db:latest --build-arg INCLUDE_DB=true . docker build -t chat-ui:latest --build-arg INCLUDE_DB=false . docker build -t huggingchat:latest --build-arg INCLUDE_DB=false --build-arg APP_BASE=/chat --build-arg PUBLIC_APP_COLOR=yellow --build-arg SKIP_LLAMA_CPP_BUILD=true . ``` If you want to run the images with your local .env.local you have two options ```bash DOTENV_LOCAL=$(<.env.local) docker run --network=host -e DOTENV_LOCAL chat-ui-db ``` ```bash docker run --network=host --mount type=bind,source="$(pwd)/.env.local",target=/app/.env.local chat-ui-db ```
chat-ui/README.md/0
{ "file_path": "chat-ui/README.md", "repo_id": "chat-ui", "token_count": 14968 }
68
# Common Issues ## 403:You don't have access to this conversation Most likely you are running chat-ui over HTTP. The recommended option is to setup something like NGINX to handle HTTPS and proxy the requests to chat-ui. If you really need to run over HTTP you can add `ALLOW_INSECURE_COOKIES=true` to your `.env.local`. Make sure to set your `PUBLIC_ORIGIN` in your `.env.local` to the correct URL as well.
chat-ui/docs/source/configuration/common-issues.md/0
{ "file_path": "chat-ui/docs/source/configuration/common-issues.md", "repo_id": "chat-ui", "token_count": 118 }
69
# OpenID The login feature is disabled by default and users are attributed a unique ID based on their browser. But if you want to use OpenID to authenticate your users, you can add the following to your `.env.local` file: ```ini OPENID_CONFIG=`{ PROVIDER_URL: "<your OIDC issuer>", CLIENT_ID: "<your OIDC client ID>", CLIENT_SECRET: "<your OIDC client secret>", SCOPES: "openid profile", TOLERANCE: // optional RESOURCE: // optional }` ``` Redirect URI: `/login/callback`
chat-ui/docs/source/configuration/open-id.md/0
{ "file_path": "chat-ui/docs/source/configuration/open-id.md", "repo_id": "chat-ui", "token_count": 160 }
70
import sade from "sade"; // @ts-expect-error: vite-node makes the var available but the typescript compiler doesn't see them import { config, ready } from "$lib/server/config"; const prog = sade("config"); await ready; prog .command("clear") .describe("Clear all config keys") .action(async () => { console.log("Clearing config..."); await clear(); }); prog .command("add <key> <value>") .describe("Add a new config key") .action(async (key: string, value: string) => { await add(key, value); }); prog .command("remove <key>") .describe("Remove a config key") .action(async (key: string) => { console.log(`Removing ${key}`); await remove(key); process.exit(0); }); prog .command("help") .describe("Show help information") .action(() => { prog.help(); process.exit(0); }); async function clear() { await config.clear(); process.exit(0); } async function add(key: string, value: string) { if (!key || !value) { console.error("Key and value are required"); process.exit(1); } await config.set(key as keyof typeof config.keysFromEnv, value); process.exit(0); } async function remove(key: string) { if (!key) { console.error("Key is required"); process.exit(1); } await config.delete(key as keyof typeof config.keysFromEnv); process.exit(0); } // Parse arguments and handle help automatically prog.parse(process.argv);
chat-ui/scripts/config.ts/0
{ "file_path": "chat-ui/scripts/config.ts", "repo_id": "chat-ui", "token_count": 510 }
71
<script lang="ts"> import type { Model } from "$lib/types/Model"; import type { Assistant } from "$lib/types/Assistant"; import { onMount } from "svelte"; import { page } from "$app/state"; import { base } from "$app/paths"; import CarbonPen from "~icons/carbon/pen"; import CarbonUpload from "~icons/carbon/upload"; import CarbonHelpFilled from "~icons/carbon/help"; import CarbonSettingsAdjust from "~icons/carbon/settings-adjust"; import CarbonTools from "~icons/carbon/tools"; import { useSettingsStore } from "$lib/stores/settings"; import IconInternet from "./icons/IconInternet.svelte"; import TokensCounter from "./TokensCounter.svelte"; import HoverTooltip from "./HoverTooltip.svelte"; import { findCurrentModel } from "$lib/utils/models"; import AssistantToolPicker from "./AssistantToolPicker.svelte"; import { error } from "$lib/stores/errors"; import { goto } from "$app/navigation"; import { usePublicConfig } from "$lib/utils/PublicConfig.svelte"; const publicConfig = usePublicConfig(); type AssistantFront = Omit<Assistant, "_id" | "createdById"> & { _id: string }; interface Props { assistant?: AssistantFront | undefined; models?: Model[]; } let errors = $state< { field: string; message: string; }[] >([]); let { assistant = undefined, models = [] }: Props = $props(); let files: FileList | null = $state(null); const settings = useSettingsStore(); let modelId = $state(""); let systemPrompt = $state(assistant?.preprompt ?? ""); let dynamicPrompt = $state(assistant?.dynamicPrompt ?? false); let showModelSettings = $state(Object.values(assistant?.generateSettings ?? {}).some((v) => !!v)); onMount(async () => { modelId = findCurrentModel(models, assistant ? assistant.modelId : $settings.activeModel).id; }); let inputMessage1 = $state(assistant?.exampleInputs[0] ?? ""); let inputMessage2 = $state(assistant?.exampleInputs[1] ?? ""); let inputMessage3 = $state(assistant?.exampleInputs[2] ?? ""); let inputMessage4 = $state(assistant?.exampleInputs[3] ?? ""); function clearError(field: string) { errors = errors.filter((e) => e.field !== field); } function onFilesChange(e: Event) { const inputEl = e.target as HTMLInputElement; if (inputEl.files?.length && inputEl.files[0].size > 0) { if (!inputEl.files[0].type.includes("image")) { inputEl.files = null; files = null; errors = [{ field: "avatar", message: "Only images are allowed" }]; return; } files = inputEl.files; clearError("avatar"); deleteExistingAvatar = false; } } function getError(field: string) { return errors.find((error) => error.field === field)?.message ?? ""; } let deleteExistingAvatar = $state(false); let loading = $state(false); let ragMode: false | "links" | "domains" | "all" = $state( assistant?.rag?.allowAllDomains ? "all" : (assistant?.rag?.allowedLinks?.length ?? 0 > 0) ? "links" : (assistant?.rag?.allowedDomains?.length ?? 0) > 0 ? "domains" : false ); let tools = $state(assistant?.tools ?? []); const regex = /{{\s?(get|post|url|today)(=.*?)?\s?}}/g; let templateVariables = $derived([...systemPrompt.matchAll(regex)]); let selectedModel = $derived(models.find((m) => m.id === modelId)); </script> <form class="relative flex h-full flex-col overflow-y-auto md:p-8 md:pt-0" enctype="multipart/form-data" onsubmit={async (e) => { e.preventDefault(); if (!e.target) { return; } const formData = new FormData(e.target as HTMLFormElement, e.submitter); loading = true; if (files?.[0] && files[0].size > 0) { formData.set("avatar", files[0]); } if (deleteExistingAvatar === true) { if (assistant?.avatar) { // if there is an avatar we explicitly removei t formData.set("avatar", "null"); } else { // else we just remove it from the input formData.delete("avatar"); } } else { if (files === null) { formData.delete("avatar"); } } formData.delete("ragMode"); if (ragMode === false || !page.data.enableAssistantsRAG) { formData.set("ragAllowAll", "false"); formData.set("ragLinkList", ""); formData.set("ragDomainList", ""); } else if (ragMode === "all") { formData.set("ragAllowAll", "true"); formData.set("ragLinkList", ""); formData.set("ragDomainList", ""); } else if (ragMode === "links") { formData.set("ragAllowAll", "false"); formData.set("ragDomainList", ""); } else if (ragMode === "domains") { formData.set("ragAllowAll", "false"); formData.set("ragLinkList", ""); } formData.set("tools", tools.join(",")); let response: Response; if (assistant?._id) { response = await fetch(`${base}/api/assistant/${assistant._id}`, { method: "PATCH", body: formData, }); if (response.ok) { goto(`${base}/settings/assistants/${assistant?._id}`, { invalidateAll: true }); } else { if (response.status === 400) { const data = await response.json(); errors = data.errors; } else { $error = response.statusText; } loading = false; } } else { response = await fetch(`${base}/api/assistant`, { method: "POST", body: formData, }); if (response.ok) { const { assistantId } = await response.json(); goto(`${base}/settings/assistants/${assistantId}`, { invalidateAll: true }); } else { if (response.status === 400) { const data = await response.json(); errors = data.errors; } else { $error = response.statusText; } loading = false; } } }} > {#if assistant} <h2 class="text-xl font-semibold"> Edit Assistant: {assistant?.name ?? "assistant"} </h2> <p class="mb-6 text-sm text-gray-500"> Modifying an existing assistant will propagate the changes to all users. </p> {:else} <h2 class="text-xl font-semibold">Create new assistant</h2> <p class="mb-6 text-sm text-gray-500"> Create and share your own AI Assistant. All assistants are <span class="rounded-full border px-2 py-0.5 leading-none">public</span > </p> {/if} <div class="grid h-full w-full flex-1 grid-cols-2 gap-6 text-sm max-sm:grid-cols-1"> <div class="col-span-1 flex flex-col gap-4"> <div> <div class="mb-1 block pb-2 text-sm font-semibold">Avatar</div> <input type="file" accept="image/*" name="avatar" id="avatar" class="hidden" onchange={onFilesChange} /> {#if (files && files[0]) || (assistant?.avatar && !deleteExistingAvatar)} <div class="group relative mx-auto h-12 w-12"> {#if files && files[0]} <img src={URL.createObjectURL(files[0])} alt="avatar" class="crop mx-auto h-12 w-12 cursor-pointer rounded-full object-cover" /> {:else if assistant?.avatar} <img src="{base}/settings/assistants/{assistant._id}/avatar.jpg?hash={assistant.avatar}" alt="avatar" class="crop mx-auto h-12 w-12 cursor-pointer rounded-full object-cover" /> {/if} <label for="avatar" class="invisible absolute bottom-0 h-12 w-12 rounded-full bg-black bg-opacity-50 p-1 group-hover:visible hover:visible" > <CarbonPen class="mx-auto my-auto h-full cursor-pointer text-center text-white" /> </label> </div> <div class="mx-auto w-max pt-1"> <button type="button" onclick={(e) => { e.preventDefault(); e.stopPropagation(); files = null; deleteExistingAvatar = true; clearError("avatar"); }} class="mx-auto w-max text-center text-xs text-gray-600 hover:underline" > Delete </button> </div> {:else} <div class="mb-1 flex w-max flex-row gap-4"> <label for="avatar" class="btn flex h-8 rounded-lg border bg-white px-3 py-1 text-gray-500 shadow-sm transition-all hover:bg-gray-100" > <CarbonUpload class="mr-2 text-xs " /> Upload </label> </div> {/if} <p class="text-xs text-red-500">{getError("avatar")}</p> </div> <label> <div class="mb-1 font-semibold">Name</div> <input name="name" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="Assistant Name" value={assistant?.name ?? ""} oninput={() => clearError("name")} /> <p class="text-xs text-red-500">{getError("name")}</p> </label> <label> <div class="mb-1 font-semibold">Description</div> <textarea name="description" class="h-15 w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="It knows everything about python" value={assistant?.description ?? ""} oninput={() => clearError("description")} ></textarea> <p class="text-xs text-red-500">{getError("description")}</p> </label> <label> <div class="mb-1 font-semibold">Model</div> <div class="flex gap-2"> <select name="modelId" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" bind:value={modelId} onchange={() => clearError("modelId")} > {#each models.filter((model) => !model.unlisted) as model} <option value={model.id}>{model.displayName}</option> {/each} </select> <p class="text-xs text-red-500">{getError("modelId")}</p> <button type="button" class="flex aspect-square items-center gap-2 whitespace-nowrap rounded-lg border px-3 {showModelSettings ? 'border-blue-500/20 bg-blue-50 text-blue-600' : ''}" onclick={() => (showModelSettings = !showModelSettings)} ><CarbonSettingsAdjust class="text-xs" /></button > </div> <div class="mt-2 rounded-lg border border-blue-500/20 bg-blue-500/5 px-2 py-0.5" class:hidden={!showModelSettings} > <p class="text-xs text-red-500">{getError("inputMessage1")}</p> <div class="my-2 grid grid-cols-1 gap-2.5 sm:grid-cols-2 sm:grid-rows-2"> <label for="temperature" class="flex justify-between"> <span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm"> Temperature <HoverTooltip label="Temperature: Controls creativity, higher values allow more variety." > <CarbonHelpFilled class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600" /> </HoverTooltip> </span> <input type="number" name="temperature" min="0.1" max="2" step="0.1" class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1" placeholder={selectedModel?.parameters?.temperature?.toString() ?? "1"} value={assistant?.generateSettings?.temperature ?? ""} /> </label> <label for="top_p" class="flex justify-between"> <span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm"> Top P <HoverTooltip label="Top P: Sets word choice boundaries, lower values tighten focus." > <CarbonHelpFilled class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600" /> </HoverTooltip> </span> <input type="number" name="top_p" class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1" min="0.05" max="1" step="0.05" placeholder={selectedModel?.parameters?.top_p?.toString() ?? "1"} value={assistant?.generateSettings?.top_p ?? ""} /> </label> <label for="repetition_penalty" class="flex justify-between"> <span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm"> Repetition penalty <HoverTooltip label="Repetition penalty: Prevents reuse, higher values decrease repetition." > <CarbonHelpFilled class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600" /> </HoverTooltip> </span> <input type="number" name="repetition_penalty" min="0.1" max="2" step="0.05" class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1" placeholder={selectedModel?.parameters?.repetition_penalty?.toString() ?? "1.0"} value={assistant?.generateSettings?.repetition_penalty ?? ""} /> </label> <label for="top_k" class="flex justify-between"> <span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm"> Top K <HoverTooltip label="Top K: Restricts word options, lower values for predictability." > <CarbonHelpFilled class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600" /> </HoverTooltip> </span> <input type="number" name="top_k" min="5" max="100" step="5" class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1" placeholder={selectedModel?.parameters?.top_k?.toString() ?? "50"} value={assistant?.generateSettings?.top_k ?? ""} /> </label> </div> </div> </label> <label> <div class="mb-1 font-semibold">User start messages</div> <div class="grid gap-1.5 text-sm md:grid-cols-2"> <input name="exampleInput1" placeholder="Start Message 1" bind:value={inputMessage1} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" oninput={() => clearError("inputMessage1")} /> <input name="exampleInput2" placeholder="Start Message 2" bind:value={inputMessage2} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" oninput={() => clearError("inputMessage1")} /> <input name="exampleInput3" placeholder="Start Message 3" bind:value={inputMessage3} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" oninput={() => clearError("inputMessage1")} /> <input name="exampleInput4" placeholder="Start Message 4" bind:value={inputMessage4} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" oninput={() => clearError("inputMessage1")} /> </div> <p class="text-xs text-red-500">{getError("inputMessage1")}</p> </label> {#if selectedModel?.tools} <div> <span class="text-smd font-semibold" >Tools <CarbonTools class="inline text-xs text-purple-600" /> <span class="ml-1 rounded bg-gray-100 px-1 py-0.5 text-xxs font-normal text-gray-600" >Experimental</span > </span> <p class="text-xs text-gray-500"> Choose up to 3 community tools that will be used with this assistant. </p> </div> <AssistantToolPicker bind:toolIds={tools} /> {/if} {#if page.data.enableAssistantsRAG} <div class="flex flex-col flex-nowrap pb-4"> <span class="mt-2 text-smd font-semibold" >Internet access <IconInternet classNames="inline text-sm text-blue-600" /> {#if publicConfig.isHuggingChat} <a href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/385" target="_blank" class="ml-0.5 rounded bg-gray-100 px-1 py-0.5 text-xxs font-normal text-gray-700 underline decoration-gray-400" >Give feedback</a > {/if} </span> <label class="mt-1"> <input checked={!ragMode} onchange={() => (ragMode = false)} type="radio" name="ragMode" value={false} /> <span class="my-2 text-sm" class:font-semibold={!ragMode}> Default </span> {#if !ragMode} <span class="block text-xs text-gray-500"> Assistant will not use internet to do information retrieval and will respond faster. Recommended for most Assistants. </span> {/if} </label> <label class="mt-1"> <input checked={ragMode === "all"} onchange={() => (ragMode = "all")} type="radio" name="ragMode" value={"all"} /> <span class="my-2 text-sm" class:font-semibold={ragMode === "all"}> Web search </span> {#if ragMode === "all"} <span class="block text-xs text-gray-500"> Assistant will do a web search on each user request to find information. </span> {/if} </label> <label class="mt-1"> <input checked={ragMode === "domains"} onchange={() => (ragMode = "domains")} type="radio" name="ragMode" value={false} /> <span class="my-2 text-sm" class:font-semibold={ragMode === "domains"}> Domains search </span> </label> {#if ragMode === "domains"} <span class="mb-2 text-xs text-gray-500"> Specify domains and URLs that the application can search, separated by commas. </span> <input name="ragDomainList" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="wikipedia.org,bbc.com" value={assistant?.rag?.allowedDomains?.join(",") ?? ""} oninput={() => clearError("ragDomainList")} /> <p class="text-xs text-red-500">{getError("ragDomainList")}</p> {/if} <label class="mt-1"> <input checked={ragMode === "links"} onchange={() => (ragMode = "links")} type="radio" name="ragMode" value={false} /> <span class="my-2 text-sm" class:font-semibold={ragMode === "links"}> Specific Links </span> </label> {#if ragMode === "links"} <span class="mb-2 text-xs text-gray-500"> Specify a maximum of 10 direct URLs that the Assistant will access. HTML & Plain Text only, separated by commas </span> <input name="ragLinkList" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="https://raw.githubusercontent.com/huggingface/chat-ui/main/README.md" value={assistant?.rag?.allowedLinks.join(",") ?? ""} oninput={() => clearError("ragLinkList")} /> <p class="text-xs text-red-500">{getError("ragLinkList")}</p> {/if} </div> {/if} </div> <div class="relative col-span-1 flex h-full flex-col"> <div class="mb-1 flex justify-between text-sm"> <span class="block font-semibold"> Instructions (System Prompt) </span> {#if dynamicPrompt && templateVariables.length} <div class="relative"> <button type="button" class="peer rounded bg-blue-500/20 px-1 text-xs text-blue-600 focus:bg-blue-500/30 focus:text-blue-800 sm:text-sm" > {templateVariables.length} template variable{templateVariables.length > 1 ? "s" : ""} </button> <div class="invisible absolute right-0 top-6 z-10 rounded-lg border bg-white p-2 text-xs shadow-lg peer-focus:visible hover:visible sm:w-96" > Will perform a GET or POST request and inject the response into the prompt. Works better with plain text, csv or json content. {#each templateVariables as match} <div> <a href={match[1].toLowerCase() === "get" ? match[2] : "#"} target={match[1].toLowerCase() === "get" ? "_blank" : ""} class="text-gray-500 underline decoration-gray-300" > {match[1].toUpperCase()}: {match[2]} </a> </div> {/each} </div> </div> {/if} </div> <label class="pb-2 text-sm has-[:checked]:font-semibold"> <input type="checkbox" name="dynamicPrompt" bind:checked={dynamicPrompt} /> Dynamic Prompt <p class="mb-2 text-xs font-normal text-gray-500"> Allow the use of template variables {"{{get=https://example.com/path}}"} to insert dynamic content into your prompt by making GET requests to specified URLs on each inference. You can also send the user's message as the body of a POST request, using {"{{post=https://example.com/path}}"}. Use {"{{today}}"} to include the current date. </p> </label> <div class="relative mb-20 flex h-full flex-col gap-2"> <textarea name="preprompt" class="min-h-[8lh] flex-1 rounded-lg border-2 border-gray-200 bg-gray-100 p-2 text-sm" placeholder="You'll act as..." bind:value={systemPrompt} oninput={() => clearError("preprompt")} ></textarea> {#if modelId} {@const model = models.find((_model) => _model.id === modelId)} {#if model?.tokenizer && systemPrompt} <TokensCounter classNames="absolute bottom-4 right-4" prompt={systemPrompt} modelTokenizer={model.tokenizer} truncate={model?.parameters?.truncate} /> {/if} {/if} <p class="text-xs text-red-500">{getError("preprompt")}</p> </div> <div class="absolute bottom-6 flex w-full justify-end gap-2 md:right-0 md:w-fit"> <a href={assistant ? `${base}/settings/assistants/${assistant?._id}` : `${base}/settings`} class="flex items-center justify-center rounded-full bg-gray-200 px-5 py-2 font-semibold text-gray-600" > Cancel </a> <button type="submit" disabled={loading} aria-disabled={loading} class="flex items-center justify-center rounded-full bg-black px-8 py-2 font-semibold" class:bg-gray-200={loading} class:text-gray-600={loading} class:text-white={!loading} > {assistant ? "Save" : "Create"} </button> </div> </div> </div> </form>
chat-ui/src/lib/components/AssistantSettings.svelte/0
{ "file_path": "chat-ui/src/lib/components/AssistantSettings.svelte", "repo_id": "chat-ui", "token_count": 9694 }
72
<script lang="ts"> import { goto } from "$app/navigation"; import { base } from "$app/paths"; import { page } from "$app/state"; import IconDazzled from "./icons/IconDazzled.svelte"; import Modal from "./Modal.svelte"; let { onClose }: { onClose: () => void } = $props(); </script> <Modal on:close={onClose} width="!max-w-[400px] !m-4"> <div class="from-primary-500/40 via-primary-500/10 to-primary-500/0 flex w-full flex-col items-center gap-3 bg-gradient-to-b px-5 pb-4 pt-9 text-center sm:px-6" > <div class="flex flex-wrap items-center gap-2"> <IconDazzled classNames="text-3xl mx-auto" /> <h2 class="flex flex-wrap items-center text-lg font-semibold text-gray-800"> This model is currently overloaded. </h2> </div> <p class="text-sm text-gray-500"> Please try again later or consider using a different model. We currently have {page.data .models.length} models available. </p> <div class="flex w-full flex-col items-center gap-4 pt-4"> <button onclick={() => (onClose(), goto(`${base}/models`))} class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900" > See all available models </button> <button onclick={onClose} class="flex w-fit flex-wrap items-center justify-center whitespace-nowrap px-2 py-1 text-gray-600 transition-colors hover:text-gray-900" > Close </button> </div> </div> </Modal>
chat-ui/src/lib/components/OverloadedModal.svelte/0
{ "file_path": "chat-ui/src/lib/components/OverloadedModal.svelte", "repo_id": "chat-ui", "token_count": 608 }
73
<script lang="ts"> import CarbonUpload from "~icons/carbon/upload"; interface Props { classNames?: string; files: File[]; mimeTypes: string[]; } let { classNames = "", files = $bindable(), mimeTypes }: Props = $props(); /** * Due to a bug with Svelte, we cannot use bind:files with multiple * So we use this workaround **/ const onFileChange = (e: Event) => { if (!e.target) return; const target = e.target as HTMLInputElement; files = [...files, ...(target.files ?? [])]; }; </script> <button class="btn relative h-8 rounded-lg border bg-white px-3 py-1 text-sm text-gray-500 shadow-sm hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 {classNames}" > <input class="absolute w-full cursor-pointer opacity-0" aria-label="Upload file" type="file" onchange={onFileChange} accept={mimeTypes.join(",")} /> <CarbonUpload class="mr-2 text-xxs" /> Upload file </button>
chat-ui/src/lib/components/UploadBtn.svelte/0
{ "file_path": "chat-ui/src/lib/components/UploadBtn.svelte", "repo_id": "chat-ui", "token_count": 351 }
74
<script lang="ts"> import type { Message } from "$lib/types/Message"; import CarbonThumbsUp from "~icons/carbon/thumbs-up"; import CarbonThumbsDown from "~icons/carbon/thumbs-down"; import { createEventDispatcher } from "svelte"; interface Props { message: Message; } let { message }: Props = $props(); const dispatch = createEventDispatcher<{ vote: { score: Message["score"]; id: Message["id"] }; }>(); </script> <button class="btn rounded-sm p-1 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300 {message.score && message.score > 0 ? 'text-green-500 hover:text-green-500 dark:text-green-400 hover:dark:text-green-400' : ''}" title={message.score === 1 ? "Remove +1" : "+1"} type="button" onclick={() => dispatch("vote", { score: message.score === 1 ? 0 : 1, id: message.id })} > <CarbonThumbsUp class="h-[1.14em] w-[1.14em]" /> </button> <button class="btn rounded-sm p-1 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300 {message.score && message.score < 0 ? 'text-red-500 hover:text-red-500 dark:text-red-400 hover:dark:text-red-400' : ''}" title={message.score === -1 ? "Remove -1" : "-1"} type="button" onclick={() => dispatch("vote", { score: message.score === -1 ? 0 : -1, id: message.id })} > <CarbonThumbsDown class="h-[1.14em] w-[1.14em]" /> </button>
chat-ui/src/lib/components/chat/Vote.svelte/0
{ "file_path": "chat-ui/src/lib/components/chat/Vote.svelte", "repo_id": "chat-ui", "token_count": 527 }
75
import { Database } from "$lib/server/database"; import { acquireLock, refreshLock } from "$lib/migrations/lock"; import type { ObjectId } from "mongodb"; import { subDays } from "date-fns"; import { logger } from "$lib/server/logger"; import { collections } from "$lib/server/database"; import { Semaphores } from "$lib/types/Semaphore"; let hasLock = false; let lockId: ObjectId | null = null; async function getLastComputationTime(): Promise<Date> { const lastStats = await collections.assistantStats.findOne({}, { sort: { "date.at": -1 } }); return lastStats?.date?.at || new Date(0); } async function shouldComputeStats(): Promise<boolean> { const lastComputationTime = await getLastComputationTime(); const oneDayAgo = new Date(Date.now() - 24 * 3_600_000); return lastComputationTime < oneDayAgo; } async function refreshAssistantsCountsHelper() { if (!hasLock) { return; } try { await (await Database.getInstance()).getClient().withSession((session) => session.withTransaction(async () => { await ( await Database.getInstance() ) .getCollections() .assistants.aggregate([ { $project: { _id: 1 } }, { $set: { last24HoursCount: 0 } }, { $unionWith: { coll: "assistants.stats", pipeline: [ { $match: { "date.at": { $gte: subDays(new Date(), 1) }, "date.span": "hour" }, }, { $group: { _id: "$assistantId", last24HoursCount: { $sum: "$count" }, }, }, ], }, }, { $group: { _id: "$_id", last24HoursCount: { $sum: "$last24HoursCount" }, }, }, { $merge: { into: "assistants", on: "_id", whenMatched: "merge", whenNotMatched: "discard", }, }, ]) .next(); }) ); } catch (e) { logger.error(e, "Refresh assistants counter failed!"); } } async function maintainLock() { if (hasLock && lockId) { hasLock = await refreshLock(Semaphores.ASSISTANTS_COUNT, lockId); if (!hasLock) { lockId = null; } } else if (!hasLock) { lockId = (await acquireLock(Semaphores.ASSISTANTS_COUNT)) || null; hasLock = !!lockId; } setTimeout(maintainLock, 10_000); } export function refreshAssistantsCounts() { const ONE_HOUR_MS = 3_600_000; maintainLock().then(async () => { if (await shouldComputeStats()) { refreshAssistantsCountsHelper(); } setInterval(async () => { if (await shouldComputeStats()) { refreshAssistantsCountsHelper(); } }, 24 * ONE_HOUR_MS); }); }
chat-ui/src/lib/jobs/refresh-assistants-counts.ts/0
{ "file_path": "chat-ui/src/lib/jobs/refresh-assistants-counts.ts", "repo_id": "chat-ui", "token_count": 1163 }
76
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 addToolsToSettings from "./03-add-tools-in-settings"; import updateMessageUpdates from "./04-update-message-updates"; import updateMessageFiles from "./05-update-message-files"; import trimMessageUpdates from "./06-trim-message-updates"; import resetTools from "./07-reset-tools-in-settings"; import updateFeaturedToReview from "./08-update-featured-to-review"; import deleteEmptyConversations from "./09-delete-empty-conversations"; import updateReportsAssistantId from "./10-update-reports-assistantid"; export interface Migration { _id: ObjectId; name: string; up: (client: Database) => Promise<boolean>; down?: (client: Database) => Promise<boolean>; runForFreshInstall?: "only" | "never"; // leave unspecified to run for both runForHuggingChat?: "only" | "never"; // leave unspecified to run for both runEveryTime?: boolean; } export const migrations: Migration[] = [ updateSearchAssistant, updateAssistantsModels, addToolsToSettings, updateMessageUpdates, updateMessageFiles, trimMessageUpdates, resetTools, updateFeaturedToReview, deleteEmptyConversations, updateReportsAssistantId, ];
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": 403 }
77
import { z } from "zod"; import type { EmbeddingEndpoint, Embedding } from "../embeddingEndpoints"; import { chunk } from "$lib/utils/chunk"; import { config } from "$lib/server/config"; export const embeddingEndpointOpenAIParametersSchema = z.object({ weight: z.number().int().positive().default(1), model: z.any(), type: z.literal("openai"), url: z.string().url().default("https://api.openai.com/v1/embeddings"), apiKey: z.string().default(config.OPENAI_API_KEY), defaultHeaders: z.record(z.string()).default({}), }); export async function embeddingEndpointOpenAI( input: z.input<typeof embeddingEndpointOpenAIParametersSchema> ): Promise<EmbeddingEndpoint> { const { url, model, apiKey, defaultHeaders } = embeddingEndpointOpenAIParametersSchema.parse(input); const maxBatchSize = model.maxBatchSize || 100; return async ({ inputs }) => { const requestURL = new URL(url); const batchesInputs = chunk(inputs, maxBatchSize); const batchesResults = await Promise.all( batchesInputs.map(async (batchInputs) => { const response = await fetch(requestURL, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), ...defaultHeaders, }, body: JSON.stringify({ input: batchInputs, model: model.name }), }); const embeddings: Embedding[] = []; const responseObject = await response.json(); for (const embeddingObject of responseObject.data) { embeddings.push(embeddingObject.embedding); } return embeddings; }) ); const flatAllEmbeddings = batchesResults.flat(); return flatAllEmbeddings; }; }
chat-ui/src/lib/server/embeddingEndpoints/openai/embeddingEndpoints.ts/0
{ "file_path": "chat-ui/src/lib/server/embeddingEndpoints/openai/embeddingEndpoints.ts", "repo_id": "chat-ui", "token_count": 619 }
78
import { z } from "zod"; import type { Endpoint, TextGenerationStreamOutputWithToolsAndWebSources } from "../endpoints"; import { createImageProcessorOptionsValidator, makeImageProcessor } from "../images"; import { INFERENCE_PROVIDERS, InferenceClient } from "@huggingface/inference"; import { config } from "$lib/server/config"; import type { Tool, ToolCall } from "$lib/types/Tool"; import type { ChatCompletionStreamOutput } from "@huggingface/tasks"; import type { FunctionDefinition } from "openai/resources/index.mjs"; import type { ChatCompletionTool, FunctionParameters } from "openai/resources/index.mjs"; import { logger } from "$lib/server/logger"; import type { MessageFile } from "$lib/types/Message"; import { v4 as uuidv4 } from "uuid"; import type { Conversation } from "$lib/types/Conversation"; import { downloadFile } from "$lib/server/files/downloadFile"; import { jsonrepair } from "jsonrepair"; type DeltaToolCall = NonNullable< ChatCompletionStreamOutput["choices"][number]["delta"]["tool_calls"] >[number]; function createChatCompletionToolsArray(tools: Tool[] | undefined): ChatCompletionTool[] { const toolChoices = [] as ChatCompletionTool[]; if (tools === undefined) { return toolChoices; } for (const t of tools) { const requiredProperties = [] as string[]; const properties = {} as Record<string, unknown>; for (const idx in t.inputs) { const parameterDefinition = t.inputs[idx]; const parameter = {} as Record<string, unknown>; switch (parameterDefinition.type) { case "str": parameter.type = "string"; break; case "float": case "int": parameter.type = "number"; break; case "bool": parameter.type = "boolean"; break; case "file": throw new Error("File type's currently not supported"); default: throw new Error(`Unknown tool IO type: ${t}`); } if ("description" in parameterDefinition) { parameter.description = parameterDefinition.description; } if (parameterDefinition.paramType == "required") { requiredProperties.push(t.inputs[idx].name); } properties[t.inputs[idx].name] = parameter; } const functionParameters: FunctionParameters = { type: "object", ...(requiredProperties.length > 0 ? { required: requiredProperties } : {}), properties, }; const functionDefinition: FunctionDefinition = { name: t.name, description: t.description, parameters: functionParameters, }; const toolDefinition: ChatCompletionTool = { type: "function", function: functionDefinition, }; toolChoices.push(toolDefinition); } return toolChoices; } export const endpointInferenceClientParametersSchema = z.object({ type: z.literal("inference-client"), weight: z.number().int().positive().default(1), model: z.any(), provider: z.enum(INFERENCE_PROVIDERS).optional(), modelName: z.string().optional(), baseURL: z.string().optional(), multimodal: z .object({ image: createImageProcessorOptionsValidator({ supportedMimeTypes: [ "image/png", "image/jpeg", "image/webp", "image/avif", "image/tiff", "image/gif", ], preferredMimeType: "image/webp", maxSizeInMB: Infinity, maxWidth: 4096, maxHeight: 4096, }), }) .default({}), customHeaders: z.record(z.string(), z.string()).default({}), }); export async function endpointInferenceClient( input: z.input<typeof endpointInferenceClientParametersSchema> ): Promise<Endpoint> { const { model, provider, modelName, baseURL, multimodal, customHeaders } = endpointInferenceClientParametersSchema.parse(input); if (!!provider && !!baseURL) { throw new Error("provider and baseURL cannot both be provided"); } const client = baseURL ? new InferenceClient(config.HF_TOKEN, { endpointUrl: baseURL }) : new InferenceClient(config.HF_TOKEN); const imageProcessor = multimodal.image ? makeImageProcessor(multimodal.image) : undefined; async function prepareFiles(files: MessageFile[], conversationId?: Conversation["_id"]) { if (!imageProcessor) { return []; } const processedFiles = await Promise.all( files .filter((file) => file.mime.startsWith("image/")) .map(async (file) => { if (file.type === "hash" && conversationId) { file = await downloadFile(file.value, conversationId); } return imageProcessor(file); }) ); return processedFiles.map((file) => ({ type: "image_url" as const, image_url: { url: `data:${file.mime};base64,${file.image.toString("base64")}`, }, })); } return async ({ messages, generateSettings, tools, toolResults, preprompt, conversationId }) => { /* eslint-disable @typescript-eslint/no-explicit-any */ let messagesArray = (await Promise.all( messages.map(async (message) => { return { role: message.from, content: [ ...(await prepareFiles(message.files ?? [], conversationId)), { type: "text" as const, text: message.content }, ], }; }) )) as any[]; if ( !model.systemRoleSupported && messagesArray.length > 0 && messagesArray[0]?.role === "system" ) { messagesArray[0].role = "user"; } else if (messagesArray[0].role !== "system") { messagesArray.unshift({ role: "system", content: preprompt ?? "", }); } if (toolResults && toolResults.length > 0) { messagesArray = [ ...messagesArray, { role: "assistant", content: [ { type: "text" as const, text: "", }, ], tool_calls: toolResults.map((toolResult) => ({ type: "function", function: { name: toolResult.call.name, arguments: JSON.stringify(toolResult.call.parameters), }, id: toolResult?.call?.toolId || uuidv4(), })), }, ...toolResults.map((toolResult) => ({ role: model.systemRoleSupported ? "tool" : "user", content: [ { type: "text" as const, text: JSON.stringify(toolResult), }, ], tool_call_id: toolResult?.call?.toolId || uuidv4(), })), ]; } messagesArray = messagesArray.reduce((acc: typeof messagesArray, current) => { if (acc.length === 0 || current.role !== acc[acc.length - 1].role) { acc.push(current); } else { const prevMessage = acc[acc.length - 1]; prevMessage.content = [ ...prevMessage.content.filter((item: any) => item.type !== "text"), ...current.content.filter((item: any) => item.type !== "text"), { type: "text" as const, text: [ ...prevMessage.content.filter((item: any) => item.type === "text"), ...current.content.filter((item: any) => item.type === "text"), ] .map((item: any) => item.text) .join("\n") .replace(/^\n/, ""), }, ]; prevMessage.files = [...(prevMessage?.files ?? []), ...(current?.files ?? [])]; prevMessage.tool_calls = [ ...(prevMessage?.tool_calls ?? []), ...(current?.tool_calls ?? []), ]; } return acc; }, []); const toolCallChoices = createChatCompletionToolsArray(tools); const stream = client.chatCompletionStream( { ...model.parameters, ...generateSettings, model: modelName ?? model.id ?? model.name, provider: baseURL ? undefined : provider || ("hf-inference" as const), messages: messagesArray, ...(toolCallChoices.length > 0 ? { tools: toolCallChoices, tool_choice: "auto" } : {}), toolResults, }, { fetch: async (url, options) => { return fetch(url, { ...options, headers: { ...options?.headers, "X-Use-Cache": "false", "ChatUI-Conversation-ID": conversationId?.toString() ?? "", ...customHeaders, }, }); }, } ); let tokenId = 0; let generated_text = ""; const finalToolCalls: DeltaToolCall[] = []; async function* convertStream(): AsyncGenerator< TextGenerationStreamOutputWithToolsAndWebSources, void, void > { for await (const chunk of stream) { const token = chunk.choices?.[0]?.delta?.content || ""; generated_text += token; const toolCalls = chunk.choices?.[0]?.delta?.tool_calls ?? []; for (const toolCall of toolCalls) { const index = toolCall.index ?? 0; if (!finalToolCalls[index]) { finalToolCalls[index] = toolCall; } else { if (finalToolCalls[index].function.arguments === undefined) { finalToolCalls[index].function.arguments = ""; } if (toolCall.function.arguments) { finalToolCalls[index].function.arguments += toolCall.function.arguments; } } } yield { token: { id: tokenId++, text: token, logprob: 0, special: false, }, details: null, generated_text: null, }; } let mappedToolCalls: ToolCall[] | undefined; try { if (finalToolCalls.length === 0) { mappedToolCalls = undefined; } else { // Ensure finalToolCalls is an array const toolCallsArray = Array.isArray(finalToolCalls) ? finalToolCalls : [finalToolCalls]; mappedToolCalls = toolCallsArray.map((tc) => ({ id: tc.id, name: tc.function.name ?? "", parameters: JSON.parse(jsonrepair(tc.function.arguments || "{}")), })); } } catch (e) { logger.error(e, "error mapping tool calls"); } yield { token: { id: tokenId++, text: "", logprob: 0, special: true, toolCalls: mappedToolCalls, }, generated_text, details: null, }; } return convertStream(); }; }
chat-ui/src/lib/server/endpoints/inference-client/endpointInferenceClient.ts/0
{ "file_path": "chat-ui/src/lib/server/endpoints/inference-client/endpointInferenceClient.ts", "repo_id": "chat-ui", "token_count": 3853 }
79
import { config } from "$lib/server/config"; import type { ToolResult, Tool } from "$lib/types/Tool"; import { MessageReasoningUpdateType, MessageUpdateType, type MessageUpdate, } from "$lib/types/MessageUpdate"; import { AbortedGenerations } from "../abortedGenerations"; import type { TextGenerationContext } from "./types"; import type { EndpointMessage } from "../endpoints/endpoints"; import { generateFromDefaultEndpoint } from "../generateFromDefaultEndpoint"; import { generateSummaryOfReasoning } from "./reasoning"; import { logger } from "../logger"; type GenerateContext = Omit<TextGenerationContext, "messages"> & { messages: EndpointMessage[] }; export async function* generate( { model, endpoint, conv, messages, assistant, isContinue, promptedAt }: GenerateContext, toolResults: ToolResult[], preprompt?: string, tools?: Tool[] ): AsyncIterable<MessageUpdate> { // reasoning mode is false by default let reasoning = false; let reasoningBuffer = ""; let lastReasoningUpdate = new Date(); let status = ""; const startTime = new Date(); if ( model.reasoning && // if the beginToken is an empty string, the model starts in reasoning mode (model.reasoning.type === "regex" || model.reasoning.type === "summarize" || (model.reasoning.type === "tokens" && model.reasoning.beginToken === "")) ) { // if the model has reasoning in regex or summarize mode, it starts in reasoning mode // and we extract the answer from the reasoning reasoning = true; yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Status, status: "Started reasoning...", }; } for await (const output of await endpoint({ messages, preprompt, continueMessage: isContinue, generateSettings: assistant?.generateSettings, tools, toolResults, isMultimodal: model.multimodal, conversationId: conv._id, })) { // text generation completed if (output.generated_text) { let interrupted = !output.token.special && !model.parameters.stop?.includes(output.token.text); let text = output.generated_text.trimEnd(); for (const stopToken of model.parameters.stop ?? []) { if (!text.endsWith(stopToken)) continue; interrupted = false; text = text.slice(0, text.length - stopToken.length); } let finalAnswer = text; if (model.reasoning && model.reasoning.type === "regex") { const regex = new RegExp(model.reasoning.regex); finalAnswer = regex.exec(reasoningBuffer)?.[1] ?? text; } else if (model.reasoning && model.reasoning.type === "summarize") { yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Status, status: "Summarizing reasoning...", }; try { const summary = yield* generateFromDefaultEndpoint({ messages: [ { from: "user", content: `Question: ${ messages[messages.length - 1].content }\n\nReasoning: ${reasoningBuffer}`, }, ], preprompt: `Your task is to summarize concisely all your reasoning steps and then give the final answer. Keep it short, one short paragraph at most. If the reasoning steps explicitly include a code solution, make sure to include it in your answer. If the user is just having a casual conversation that doesn't require explanations, answer directly without explaining your steps, otherwise make sure to summarize step by step, make sure to skip dead-ends in your reasoning and removing excess detail. Do not use prefixes such as Response: or Answer: when answering to the user.`, generateSettings: { max_new_tokens: 1024, }, }); finalAnswer = summary; yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Status, status: `Done in ${Math.round((new Date().getTime() - startTime.getTime()) / 1000)}s.`, }; } catch (e) { finalAnswer = text; logger.error(e); } } else if (model.reasoning && model.reasoning.type === "tokens") { // make sure to remove the content of the reasoning buffer from // the final answer to avoid duplication // if the beginToken is an empty string, we don't need to remove anything const beginIndex = model.reasoning.beginToken ? reasoningBuffer.indexOf(model.reasoning.beginToken) : 0; const endIndex = reasoningBuffer.lastIndexOf(model.reasoning.endToken); if (beginIndex !== -1 && endIndex !== -1) { // Remove the reasoning section (including tokens) from final answer finalAnswer = text.slice(0, beginIndex) + text.slice(endIndex + model.reasoning.endToken.length); } } yield { type: MessageUpdateType.FinalAnswer, text: finalAnswer, interrupted, webSources: output.webSources, }; continue; } if (model.reasoning && model.reasoning.type === "tokens") { if (output.token.text === model.reasoning.beginToken) { reasoning = true; reasoningBuffer += output.token.text; continue; } else if (output.token.text === model.reasoning.endToken) { reasoning = false; reasoningBuffer += output.token.text; yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Status, status: `Done in ${Math.round((new Date().getTime() - startTime.getTime()) / 1000)}s.`, }; continue; } } // ignore special tokens if (output.token.special) continue; // pass down normal token if (reasoning) { reasoningBuffer += output.token.text; if (model.reasoning && model.reasoning.type === "tokens") { // split reasoning buffer so that anything that comes after the end token is separated // add it to the normal buffer, and yield two updates, one for the reasoning and one for the normal content // also set reasoning to false if (reasoningBuffer.lastIndexOf(model.reasoning.endToken) !== -1) { const endTokenIndex = reasoningBuffer.lastIndexOf(model.reasoning.endToken); const textBuffer = reasoningBuffer.slice(endTokenIndex + model.reasoning.endToken.length); reasoningBuffer = reasoningBuffer.slice( 0, endTokenIndex + model.reasoning.endToken.length + 1 ); yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Stream, token: output.token.text, }; yield { type: MessageUpdateType.Stream, token: textBuffer, }; yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Status, status: `Done in ${Math.round((new Date().getTime() - startTime.getTime()) / 1000)}s.`, }; reasoning = false; continue; } } // yield status update if it has changed if (status !== "") { yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Status, status, }; status = ""; } // create a new status every 5 seconds if ( config.REASONING_SUMMARY === "true" && new Date().getTime() - lastReasoningUpdate.getTime() > 4000 ) { lastReasoningUpdate = new Date(); try { generateSummaryOfReasoning(reasoningBuffer).then((summary) => { status = summary; }); } catch (e) { logger.error(e); } } yield { type: MessageUpdateType.Reasoning, subtype: MessageReasoningUpdateType.Stream, token: output.token.text, }; } else { yield { type: MessageUpdateType.Stream, token: output.token.text }; } // abort check const date = AbortedGenerations.getInstance().getAbortTime(conv._id.toString()); if (date && date > promptedAt) { logger.info(`Aborting generation for conversation ${conv._id}`); break; } // no output check if (!output) break; } }
chat-ui/src/lib/server/textGeneration/generate.ts/0
{ "file_path": "chat-ui/src/lib/server/textGeneration/generate.ts", "repo_id": "chat-ui", "token_count": 2795 }
80
import { MetricsServer } from "$lib/server/metrics"; import type { WebSearchScrapedSource, WebSearchUsedSource } from "$lib/types/WebSearch"; import type { EmbeddingBackendModel } from "../../embeddingModels"; import { getSentenceSimilarity, innerProduct } from "../../sentenceSimilarity"; import { MarkdownElementType, type MarkdownElement } from "../markdown/types"; import { stringifyMarkdownElement } from "../markdown/utils/stringify"; import { getCombinedSentenceSimilarity } from "./combine"; import { flattenTree } from "./tree"; const MIN_CHARS = 3_000; const SOFT_MAX_CHARS = 8_000; export async function findContextSources( sources: WebSearchScrapedSource[], prompt: string, embeddingModel: EmbeddingBackendModel ) { const startTime = Date.now(); const sourcesMarkdownElems = sources.map((source) => flattenTree(source.page.markdownTree)); const markdownElems = sourcesMarkdownElems.flat(); // When using CPU embedding (transformersjs), join sentences together to the max character limit // to reduce inference time const embeddingFunc = embeddingModel.endpoints[0].type === "transformersjs" ? getCombinedSentenceSimilarity : getSentenceSimilarity; const embeddings = await embeddingFunc( embeddingModel, prompt, markdownElems .map(stringifyMarkdownElement) // Safety in case the stringified markdown elements are too long // but chunking should have happened earlier .map((elem) => elem.slice(0, embeddingModel.chunkCharLength)) ); const topEmbeddings = embeddings .sort((a, b) => a.distance - b.distance) .filter((embedding) => markdownElems[embedding.idx].type !== MarkdownElementType.Header); let totalChars = 0; const selectedMarkdownElems = new Set<MarkdownElement>(); const selectedEmbeddings: number[][] = []; for (const embedding of topEmbeddings) { const elem = markdownElems[embedding.idx]; // Ignore elements that are too similar to already selected elements const tooSimilar = selectedEmbeddings.some( (selectedEmbedding) => innerProduct(selectedEmbedding, embedding.embedding) < 0.01 ); if (tooSimilar) continue; // Add element if (!selectedMarkdownElems.has(elem)) { selectedMarkdownElems.add(elem); selectedEmbeddings.push(embedding.embedding); totalChars += elem.content.length; } // Add element's parent (header) if (elem.parent && !selectedMarkdownElems.has(elem.parent)) { selectedMarkdownElems.add(elem.parent); totalChars += elem.parent.content.length; } if (totalChars > SOFT_MAX_CHARS) break; if (totalChars > MIN_CHARS && embedding.distance > 0.25) break; } const contextSources = sourcesMarkdownElems .map<WebSearchUsedSource>((elems, idx) => { const sourceSelectedElems = elems.filter((elem) => selectedMarkdownElems.has(elem)); const context = sourceSelectedElems.map(stringifyMarkdownElement).join("\n"); const source = sources[idx]; return { ...source, context }; }) .filter((contextSource) => contextSource.context.length > 0); MetricsServer.getMetrics().webSearch.embeddingDuration.observe(Date.now() - startTime); return contextSources; }
chat-ui/src/lib/server/websearch/embed/embed.ts/0
{ "file_path": "chat-ui/src/lib/server/websearch/embed/embed.ts", "repo_id": "chat-ui", "token_count": 1027 }
81
import { config } from "$lib/server/config"; import { logger } from "$lib/server/logger"; import type { WebSearchSource } from "$lib/types/WebSearch"; import { isURL } from "$lib/utils/isUrl"; export default async function searchSearxng(query: string): Promise<WebSearchSource[]> { const abortController = new AbortController(); setTimeout(() => abortController.abort(), 10000); // Insert the query into the URL template let url = config.SEARXNG_QUERY_URL.replace("<query>", query); // Check if "&format=json" already exists in the URL if (!url.includes("&format=json")) { url += "&format=json"; } // Call the URL to return JSON data const jsonResponse = await fetch(url, { signal: abortController.signal, }) .then((response) => response.json() as Promise<{ results: { url: string }[] }>) .catch((error) => { logger.error(error, "Failed to fetch or parse JSON"); throw new Error("Failed to fetch or parse JSON", { cause: error }); }); // Extract 'url' elements from the JSON response and trim to the top 5 URLs const urls = jsonResponse.results.slice(0, 5).map((item) => item.url); if (!urls.length) { throw new Error(`Response doesn't contain any "url" elements`); } // Map URLs to the correct object shape return urls.filter(isURL).map((link) => ({ link })); }
chat-ui/src/lib/server/websearch/search/endpoints/searxng.ts/0
{ "file_path": "chat-ui/src/lib/server/websearch/search/endpoints/searxng.ts", "repo_id": "chat-ui", "token_count": 416 }
82
import { writable } from "svelte/store"; export interface WebSearchParameters { useSearch: boolean; nItems: number; } export const webSearchParameters = writable<WebSearchParameters>({ useSearch: false, nItems: 5, });
chat-ui/src/lib/stores/webSearchParameters.ts/0
{ "file_path": "chat-ui/src/lib/stores/webSearchParameters.ts", "repo_id": "chat-ui", "token_count": 68 }
83
import type { Timestamps } from "./Timestamps"; export interface Semaphore extends Timestamps { key: string; deleteAt: Date; } export enum Semaphores { ASSISTANTS_COUNT = "assistants.count", CONVERSATION_STATS = "conversation.stats", CONFIG_UPDATE = "config.update", MIGRATION = "migration", TEST_MIGRATION = "test.migration", }
chat-ui/src/lib/types/Semaphore.ts/0
{ "file_path": "chat-ui/src/lib/types/Semaphore.ts", "repo_id": "chat-ui", "token_count": 124 }
84
export async function fetchJSON<T>( url: string, options?: { fetch?: typeof window.fetch; allowNull?: boolean; } ): Promise<T> { const response = await (options?.fetch ?? fetch)(url); if (!response.ok) { throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`); } // Handle empty responses (which parse to null) const text = await response.text(); if (!text || text.trim() === "") { if (options?.allowNull) { return null as T; } throw new Error(`Received empty response from ${url} but allowNull is not set to true`); } return JSON.parse(text); }
chat-ui/src/lib/utils/fetchJSON.ts/0
{ "file_path": "chat-ui/src/lib/utils/fetchJSON.ts", "repo_id": "chat-ui", "token_count": 210 }
85
export async function captureScreen(): Promise<string> { let stream: MediaStream | undefined; try { // This will show the native browser dialog for screen capture stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false, }); // Create a canvas element to capture the screenshot const canvas = document.createElement("canvas"); const video = document.createElement("video"); // Wait for the video to load metadata await new Promise((resolve) => { video.onloadedmetadata = () => { canvas.width = video.videoWidth; canvas.height = video.videoHeight; video.play(); resolve(null); }; if (stream) { video.srcObject = stream; } else { throw Error("No stream available"); } }); // Draw the video frame to canvas const context = canvas.getContext("2d"); context?.drawImage(video, 0, 0, canvas.width, canvas.height); // Convert to base64 return canvas.toDataURL("image/png"); } catch (error) { console.error("Error capturing screenshot:", error); throw error; } finally { // Stop all tracks if (stream) { stream.getTracks().forEach((track) => track.stop()); } } }
chat-ui/src/lib/utils/screenshot.ts/0
{ "file_path": "chat-ui/src/lib/utils/screenshot.ts", "repo_id": "chat-ui", "token_count": 402 }
86
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 === -1) throw new Error("Message not found"); return conv.messages.slice(0, index + 1); } else { // find the message with the right id then create the ancestor tree const message = conv.messages.find((m) => m.id === id); if (!message) throw new Error("Message not found"); return [ ...(message.ancestors?.map((ancestorId) => { const ancestor = conv.messages.find((m) => m.id === ancestorId); if (!ancestor) throw new Error("Ancestor not found"); return ancestor; }) ?? []), message, ]; } }
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 }
87
import { collections } from "$lib/server/database"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { asssistantSchema, uploadAssistantAvatar } from "../utils.js"; import { requiresUser } from "$lib/server/auth.js"; import sharp from "sharp"; import { generateSearchTokens } from "$lib/utils/searchTokens"; export async function GET({ params }) { const id = params.id; const assistantId = new ObjectId(id); const assistant = await collections.assistants.findOne({ _id: assistantId, }); if (assistant) { return Response.json(assistant); } else { return Response.json({ message: "Assistant not found" }, { status: 404 }); } } export async function PATCH({ request, locals, params }) { const assistant = await collections.assistants.findOne({ _id: new ObjectId(params.id), }); if (!assistant) { throw Error("Assistant not found"); } if (assistant.createdById.toString() !== (locals.user?._id ?? locals.sessionId).toString()) { throw Error("You are not the author of this assistant"); } const formData = Object.fromEntries(await request.formData()); const parse = await asssistantSchema.safeParseAsync(formData); if (!parse.success) { // Loop through the errors array and create a custom errors array const errors = parse.error.errors.map((error) => { return { field: error.path[0], message: error.message, }; }); return new Response(JSON.stringify({ error: true, errors }), { status: 400 }); } // can only create assistants when logged in, IF login is setup if (!locals.user && requiresUser) { const errors = [{ field: "preprompt", message: "Must be logged in. Unauthorized" }]; return new Response(JSON.stringify({ error: true, errors }), { status: 400 }); } const exampleInputs: string[] = [ parse?.data?.exampleInput1 ?? "", parse?.data?.exampleInput2 ?? "", parse?.data?.exampleInput3 ?? "", parse?.data?.exampleInput4 ?? "", ].filter((input) => !!input); const deleteAvatar = parse.data.avatar === "null"; let hash; if (parse.data.avatar && parse.data.avatar !== "null" && parse.data.avatar.size > 0) { let image; try { image = await sharp(await parse.data.avatar.arrayBuffer()) .resize(512, 512, { fit: "inside" }) .jpeg({ quality: 80 }) .toBuffer(); } catch (e) { const errors = [{ field: "avatar", message: (e as Error).message }]; return new Response(JSON.stringify({ error: true, errors }), { status: 400 }); } const fileCursor = collections.bucket.find({ filename: assistant._id.toString() }); // Step 2: Delete the existing file if it exists let fileId = await fileCursor.next(); while (fileId) { await collections.bucket.delete(fileId._id); fileId = await fileCursor.next(); } hash = await uploadAssistantAvatar(new File([image], "avatar.jpg"), assistant._id); } else if (deleteAvatar) { // delete the avatar const fileCursor = collections.bucket.find({ filename: assistant._id.toString() }); let fileId = await fileCursor.next(); while (fileId) { await collections.bucket.delete(fileId._id); fileId = await fileCursor.next(); } } const { acknowledged } = await collections.assistants.updateOne( { _id: assistant._id, }, { $set: { name: parse.data.name, description: parse.data.description, modelId: parse.data.modelId, preprompt: parse.data.preprompt, exampleInputs, avatar: deleteAvatar ? undefined : (hash ?? assistant.avatar), updatedAt: new Date(), rag: { allowedLinks: parse.data.ragLinkList, allowedDomains: parse.data.ragDomainList, allowAllDomains: parse.data.ragAllowAll, }, tools: parse.data.tools, dynamicPrompt: parse.data.dynamicPrompt, searchTokens: generateSearchTokens(parse.data.name), generateSettings: { temperature: parse.data.temperature, top_p: parse.data.top_p, repetition_penalty: parse.data.repetition_penalty, top_k: parse.data.top_k, }, }, } ); if (acknowledged) { return new Response(JSON.stringify({ success: true, assistantId: assistant._id }), { status: 200, }); } else { return new Response(JSON.stringify({ error: true, message: "Update failed" }), { status: 500 }); } } export async function DELETE({ params, locals }) { const assistant = await collections.assistants.findOne({ _id: new ObjectId(params.id) }); if (!assistant) { return error(404, "Assistant not found"); } if ( assistant.createdById.toString() !== (locals.user?._id ?? locals.sessionId).toString() && !locals.isAdmin ) { return error(403, "You are not the author of this assistant"); } await collections.assistants.deleteOne({ _id: assistant._id }); // and remove it from all users settings await collections.settings.updateMany( { assistants: { $in: [assistant._id] }, }, { $pull: { assistants: assistant._id }, } ); // and delete all avatars const fileCursor = collections.bucket.find({ filename: assistant._id.toString() }); // Step 2: Delete the existing file if it exists let fileId = await fileCursor.next(); while (fileId) { await collections.bucket.delete(fileId._id); fileId = await fileCursor.next(); } return new Response("Assistant deleted", { status: 200 }); }
chat-ui/src/routes/api/assistant/[id]/+server.ts/0
{ "file_path": "chat-ui/src/routes/api/assistant/[id]/+server.ts", "repo_id": "chat-ui", "token_count": 1859 }
88
import { authCondition } from "$lib/server/auth"; import type { Conversation } from "$lib/types/Conversation"; import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; export async function GET({ locals }) { if (locals.user?._id || locals.sessionId) { const settings = await collections.settings.findOne(authCondition(locals)); const conversations = await collections.conversations .find(authCondition(locals)) .sort({ updatedAt: -1 }) .project<Pick<Conversation, "assistantId">>({ assistantId: 1, }) .limit(300) .toArray(); const userAssistants = settings?.assistants?.map((assistantId) => assistantId.toString()) ?? []; const userAssistantsSet = new Set(userAssistants); const assistantIds = [ ...userAssistants.map((el) => new ObjectId(el)), ...(conversations.map((conv) => conv.assistantId).filter((el) => !!el) as ObjectId[]), ]; const assistants = await collections.assistants.find({ _id: { $in: assistantIds } }).toArray(); const res = assistants .filter((el) => userAssistantsSet.has(el._id.toString())) .map((el) => ({ ...el, _id: el._id.toString(), createdById: undefined, createdByMe: el.createdById.toString() === (locals.user?._id ?? locals.sessionId).toString(), })); return Response.json(res); } else { return Response.json({ message: "Must have session cookie" }, { status: 401 }); } }
chat-ui/src/routes/api/user/assistants/+server.ts/0
{ "file_path": "chat-ui/src/routes/api/user/assistants/+server.ts", "repo_id": "chat-ui", "token_count": 509 }
89
import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import type { SharedConversation } from "$lib/types/SharedConversation"; import { hashConv } from "$lib/utils/hashConv"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { nanoid } from "nanoid"; export async function POST({ params, locals }) { const conversation = await collections.conversations.findOne({ _id: new ObjectId(params.id), ...authCondition(locals), }); if (!conversation) { error(404, "Conversation not found"); } const hash = await hashConv(conversation); const existingShare = await collections.sharedConversations.findOne({ hash }); if (existingShare) { return new Response( JSON.stringify({ shareId: existingShare._id, }), { headers: { "Content-Type": "application/json" } } ); } const shared: SharedConversation = { _id: nanoid(7), hash, createdAt: new Date(), updatedAt: new Date(), rootMessageId: conversation.rootMessageId, messages: conversation.messages, title: conversation.title, model: conversation.model, embeddingModel: conversation.embeddingModel, preprompt: conversation.preprompt, assistantId: conversation.assistantId, }; await collections.sharedConversations.insertOne(shared); // copy files from `${conversation._id}-` to `${shared._id}-` const files = await collections.bucket .find({ filename: { $regex: `${conversation._id}-` } }) .toArray(); await Promise.all( files.map(async (file) => { const newFilename = file.filename.replace(`${conversation._id}-`, `${shared._id}-`); // copy files from `${conversation._id}-` to `${shared._id}-` by downloading and reuploaidng const downloadStream = collections.bucket.openDownloadStream(file._id); const uploadStream = collections.bucket.openUploadStream(newFilename, { metadata: { ...file.metadata, conversation: shared._id.toString() }, }); downloadStream.pipe(uploadStream); }) ); return new Response( JSON.stringify({ shareId: shared._id, }), { headers: { "Content-Type": "application/json" } } ); }
chat-ui/src/routes/conversation/[id]/share/+server.ts/0
{ "file_path": "chat-ui/src/routes/conversation/[id]/share/+server.ts", "repo_id": "chat-ui", "token_count": 731 }
90
export const ssr = false;
chat-ui/src/routes/settings/(nav)/+layout.ts/0
{ "file_path": "chat-ui/src/routes/settings/(nav)/+layout.ts", "repo_id": "chat-ui", "token_count": 8 }
91
import { handleResponse, useAPIClient } from "$lib/APIClient"; export const load = async ({ url, fetch }) => { const client = useAPIClient({ fetch }); return client.tools.search .get({ query: Object.fromEntries(url.searchParams.entries()) }) .then(handleResponse); };
chat-ui/src/routes/tools/+page.ts/0
{ "file_path": "chat-ui/src/routes/tools/+page.ts", "repo_id": "chat-ui", "token_count": 91 }
92
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none"> <path fill="#2063EC" d="M4 15.55C4 9.72 8.72 5 14.55 5h4.11a9.34 9.34 0 1 1 0 18.68H7.58l-2.89 2.8a.41.41 0 0 1-.69-.3V15.55Z" /> </svg>
chat-ui/static/chatui/logo.svg/0
{ "file_path": "chat-ui/static/chatui/logo.svg", "repo_id": "chat-ui", "token_count": 125 }
93
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="none"> <path fill="#FFD21E" d="M4 15.55C4 9.72 8.72 5 14.55 5h4.11a9.34 9.34 0 1 1 0 18.68H7.58l-2.89 2.8a.41.41 0 0 1-.69-.3V15.55Z" /> <path fill="#32343D" d="M19.63 12.48c.37.14.52.9.9.7.71-.38.98-1.27.6-1.98a1.46 1.46 0 0 0-1.98-.61 1.47 1.47 0 0 0-.6 1.99c.17.34.74-.21 1.08-.1ZM12.72 12.48c-.37.14-.52.9-.9.7a1.47 1.47 0 0 1-.6-1.98 1.46 1.46 0 0 1 1.98-.61c.71.38.98 1.27.6 1.99-.18.34-.74-.21-1.08-.1ZM16.24 19.55c2.89 0 3.82-2.58 3.82-3.9 0-1.33-1.71.7-3.82.7-2.1 0-3.8-2.03-3.8-.7 0 1.32.92 3.9 3.8 3.9Z" /> <path fill="#FF323D" d="M18.56 18.8c-.57.44-1.33.75-2.32.75-.92 0-1.65-.27-2.2-.68.3-.63.87-1.11 1.55-1.32.12-.03.24.17.36.38.12.2.24.4.37.4s.26-.2.39-.4.26-.4.38-.36a2.56 2.56 0 0 1 1.47 1.23Z" /> </svg>
chat-ui/static/huggingchat/logo.svg/0
{ "file_path": "chat-ui/static/huggingchat/logo.svg", "repo_id": "chat-ui", "token_count": 523 }
94
# Add patterns of files dvc should ignore, which could improve # the performance. Learn more at # https://dvc.org/doc/user-guide/dvcignore
datasets/.dvcignore/0
{ "file_path": "datasets/.dvcignore", "repo_id": "datasets", "token_count": 40 }
95
# How to contribute to Datasets? [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md) Datasets is an open source project, so all contributions and suggestions are welcome. You can contribute in many different ways: giving ideas, answering questions, reporting bugs, proposing enhancements, improving the documentation, fixing bugs,... Many thanks in advance to every contributor. In order to facilitate healthy, constructive behavior in an open and inclusive community, we all respect and abide by our [code of conduct](CODE_OF_CONDUCT.md). ## How to work on an open Issue? You have the list of open Issues at: https://github.com/huggingface/datasets/issues Some of them may have the label `help wanted`: that means that any contributor is welcomed! If you would like to work on any of the open Issues: 1. Make sure it is not already assigned to someone else. You have the assignee (if any) on the top of the right column of the Issue page. 2. You can self-assign it by commenting on the Issue page with the keyword: `#self-assign`. 3. Work on your self-assigned issue and eventually create a Pull Request. ## How to create a Pull Request? If you want to add a dataset see specific instructions in the section [*How to add a dataset*](#how-to-add-a-dataset). 1. Fork the [repository](https://github.com/huggingface/datasets) by clicking on the 'Fork' button on the repository's page. This creates a copy of the code under your GitHub user account. 2. Clone your fork to your local disk, and add the base repository as a remote: ```bash git clone git@github.com:<your Github handle>/datasets.git cd datasets git remote add upstream https://github.com/huggingface/datasets.git ``` 3. Create a new branch to hold your development changes: ```bash git checkout -b a-descriptive-name-for-my-changes ``` **do not** work on the `main` branch. 4. Set up a development environment by running the following command in a virtual environment: Simple setup with code formatting only (recommended) ```bash pip install -e ".[quality]" ``` Advanced setup with all the optional dependencies ```bash pip install -e ".[dev]" ``` (If datasets was already installed in the virtual environment, remove it with `pip uninstall datasets` before reinstalling it in editable mode with the `-e` flag.) 5. Develop the features on your branch. 6. Format your code. Run `black` and `ruff` so that your newly added files look nice with the following command: ```bash make style ``` 7. _(Optional)_ You can also use [`pre-commit`](https://pre-commit.com/) to format your code automatically each time run `git commit`, instead of running `make style` manually. To do this, install `pre-commit` via `pip install pre-commit` and then run `pre-commit install` in the project's root directory to set up the hooks. Note that if any files were formatted by `pre-commit` hooks during committing, you have to run `git commit` again . 8. Once you're happy with your contribution, add your changed files and make a commit to record your changes locally: ```bash git add -u git commit ``` It is a good idea to sync your copy of the code with the original repository regularly. This way you can quickly account for changes: ```bash git fetch upstream git rebase upstream/main ``` 9. Once you are satisfied, push the changes to your fork repo using: ```bash git push -u origin a-descriptive-name-for-my-changes ``` Go the webpage of your fork on GitHub. Click on "Pull request" to send your changes to the project maintainers for review. ## Datasets on Hugging Face ### How to add a dataset on Hugging Face You can share your dataset on https://huggingface.co/datasets directly using your account (no need to open a PR on GitHub), see the documentation: * [Create a dataset and upload files on the website](https://huggingface.co/docs/datasets/upload_dataset) * [Advanced guide using the CLI](https://huggingface.co/docs/datasets/share) ### How to contribute to the dataset cards Improving the documentation of datasets is an ever-increasing effort, and we invite users to contribute by sharing their insights with the community in the `README.md` dataset cards provided for each dataset. If you see that a dataset card is missing information that you are in a position to provide (as an author of the dataset or as an experienced user), the best thing you can do is to open a Pull Request on the Hugging Face Hub. To do, go to the "Files and versions" tab of the dataset page and edit the `README.md` file. We provide: * a [template](https://github.com/huggingface/datasets/blob/main/templates/README.md) * a [guide](https://github.com/huggingface/datasets/blob/main/templates/README_guide.md) describing what information should go into each of the paragraphs * and if you need inspiration, we recommend looking through a [completed example](https://huggingface.co/datasets/eli5/blob/main/README.md) If you are a **dataset author**... you know what to do, it is your dataset after all ;) ! We would especially appreciate if you could help us fill in information about the process of creating the dataset, and take a moment to reflect on its social impact and possible limitations if you haven't already done so in the dataset paper or in another data statement. If you are a **user of a dataset**, the main source of information should be the dataset paper if it is available: we recommend pulling information from there into the relevant paragraphs of the template. We also eagerly welcome discussions on the [Considerations for Using the Data](https://github.com/huggingface/datasets/blob/main/templates/README_guide.md#considerations-for-using-the-data) based on existing scholarship or personal experience that would benefit the whole community. Finally, if you want more information on the how and why of dataset cards, we strongly recommend reading the foundational works [Datasheets for Datasets](https://arxiv.org/abs/1803.09010) and [Data Statements for NLP](https://www.aclweb.org/anthology/Q18-1041/). Thank you for your contribution! ## Code of conduct This project adheres to the HuggingFace [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to abide by this code.
datasets/CONTRIBUTING.md/0
{ "file_path": "datasets/CONTRIBUTING.md", "repo_id": "datasets", "token_count": 1794 }
96
# Cache management When you download a dataset from Hugging Face, the data are stored locally on your computer. Files from Hugging Face are stored as usual in the `huggingface_hub` cache, which is at `~/.cache/huggingface/hub` by default. See the [Hub cache documentation](https://huggingface.co/docs/huggingface_hub/guides/manage-cache) for more details and how to change its location. The Hub cache allows 🤗 Datasets to avoid re-downloading dataset files from Hugging Face every time you use them. 🤗 Datasets also has its own cache to store datasets converted in Arrow format (the format used by [`Dataset`] objects). This guide focuses on the 🤗 Datasets cache and will show you how to: - Change the cache directory. - Control how a dataset is loaded from the cache. - Clean up cache files in the directory. - Enable or disable caching. ## Cache directory The default 🤗 Datasets cache directory is `~/.cache/huggingface/datasets`. Change the cache location by setting the shell environment variable, `HF_HOME` to another directory: ``` $ export HF_HOME="/path/to/another/directory/datasets" ``` Alternatively, you can set the `HF_DATASETS_CACHE` environment variable to control only the datasets-specific cache directory: ``` $ export HF_DATASETS_CACHE="/path/to/datasets_cache" ``` ⚠️ This only applies to files written by the `datasets` library (e.g., Arrow files and indices). It does **not** affect files downloaded from the Hugging Face Hub (such as models, tokenizers, or raw dataset sources), which are located in `~/.cache/huggingface/hub` by default and controlled separately via the `HF_HUB_CACHE` variable: ``` $ export HF_HUB_CACHE="/path/to/hub_cache" ``` 💡 If you'd like to relocate all Hugging Face caches — including datasets and hub downloads — use the `HF_HOME` variable instead: ``` $ export HF_HOME="/path/to/cache_root" ``` This results in: - datasets cache → `/path/to/cache_root/datasets` - hub cache → `/path/to/cache_root/hub` These distinctions are especially useful when working in shared environments or networked file systems (e.g., NFS). See [issue #7480](https://github.com/huggingface/datasets/issues/7480) for discussion on how users encountered unexpected cache locations when `HF_HUB_CACHE` was not set alongside `HF_DATASETS_CACHE`. When you load a dataset, you also have the option to change where the data is cached. Change the `cache_dir` parameter to the path you want: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('username/dataset', cache_dir="/path/to/another/directory/datasets") ``` ## Download mode After you download a dataset, control how it is loaded by [`load_dataset`] with the `download_mode` parameter. By default, 🤗 Datasets will reuse a dataset if it exists. But if you need the original dataset without any processing functions applied, re-download the files as shown below: ```py >>> from datasets import load_dataset >>> dataset = load_dataset('rajpurkar/squad', download_mode='force_redownload') ``` Refer to [`DownloadMode`] for a full list of download modes. ## Cache files Clean up the Arrow cache files in the directory with [`Dataset.cleanup_cache_files`]: ```py # Returns the number of removed cache files >>> dataset.cleanup_cache_files() 2 ``` ## Enable or disable caching If you're using a cached file locally, it will automatically reload the dataset with any previous transforms you applied to the dataset. Disable this behavior by setting the argument `load_from_cache_file=False` in [`Dataset.map`]: ```py >>> updated_dataset = small_dataset.map(add_prefix, load_from_cache_file=False) ``` In the example above, 🤗 Datasets will execute the function `add_prefix` over the entire dataset again instead of loading the dataset from its previous state. Disable caching on a global scale with [`disable_caching`]: ```py >>> from datasets import disable_caching >>> disable_caching() ``` When you disable caching, 🤗 Datasets will no longer reload cached files when applying transforms to datasets. Any transform you apply on your dataset will be need to be reapplied. <Tip> If you want to reuse a dataset from scratch, try setting the `download_mode` parameter in [`load_dataset`] instead. </Tip> <a id='load_dataset_enhancing_performance'></a> ## Improve performance Disabling the cache and copying the dataset in-memory will speed up dataset operations. There are two options for copying the dataset in-memory: 1. Set `datasets.config.IN_MEMORY_MAX_SIZE` to a nonzero value (in bytes) that fits in your RAM memory. 2. Set the environment variable `HF_DATASETS_IN_MEMORY_MAX_SIZE` to a nonzero value. Note that the first method takes higher precedence.
datasets/docs/source/cache.mdx/0
{ "file_path": "datasets/docs/source/cache.mdx", "repo_id": "datasets", "token_count": 1365 }
97
# Datasets <img class="float-left !m-0 !border-0 !dark:border-0 !shadow-none !max-w-lg w-[150px]" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/datasets_logo.png"/> 🤗 Datasets is a library for easily accessing and sharing AI datasets for Audio, Computer Vision, and Natural Language Processing (NLP) tasks. Load a dataset in a single line of code, and use our powerful data processing and streaming methods to quickly get your dataset ready for training in a deep learning model. Backed by the Apache Arrow format, process large datasets with zero-copy reads without any memory constraints for optimal speed and efficiency. We also feature a deep integration with the [Hugging Face Hub](https://huggingface.co/datasets), allowing you to easily load and share a dataset with the wider machine learning community. Find your dataset today on the [Hugging Face Hub](https://huggingface.co/datasets), and take an in-depth look inside of it with the live viewer. <div class="mt-10"> <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5"> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorial" ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div> <p class="text-gray-700">Learn the basics and become familiar with loading, accessing, and processing a dataset. Start here if you are using 🤗 Datasets for the first time!</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./how_to" ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div> <p class="text-gray-700">Practical guides to help you achieve a specific goal. Take a look at these guides to learn how to use 🤗 Datasets to solve real-world problems.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./about_arrow" ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div> <p class="text-gray-700">High-level explanations for building a better understanding about important topics such as the underlying data format, the cache, and how datasets are generated.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./package_reference/main_classes" ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div> <p class="text-gray-700">Technical descriptions of how 🤗 Datasets classes and methods work.</p> </a> </div> </div>
datasets/docs/source/index.mdx/0
{ "file_path": "datasets/docs/source/index.mdx", "repo_id": "datasets", "token_count": 1017 }
98
# Share a dataset using the CLI At Hugging Face, we are on a mission to democratize good Machine Learning and we believe in the value of open source. That's why we designed 🤗 Datasets so that anyone can share a dataset with the greater ML community. There are currently thousands of datasets in over 100 languages in the Hugging Face Hub, and the Hugging Face team always welcomes new contributions! Dataset repositories offer features such as: - Free dataset hosting - Dataset versioning - Commit history and diffs - Metadata for discoverability - Dataset cards for documentation, licensing, limitations, etc. - [Dataset Viewer](https://huggingface.co/docs/hub/datasets-viewer) This guide will show you how to share a dataset folder or repository that can be easily accessed by anyone. <a id='upload_dataset_repo'></a> ## Add a dataset You can share your dataset with the community with a dataset repository on the Hugging Face Hub. It can also be a private dataset if you want to control who has access to it. In a dataset repository, you can host all your data files and [configure your dataset](./repository_structure#define-your-splits-in-yaml) to define which file goes to which split. The following formats are supported: CSV, TSV, JSON, JSON lines, text, Parquet, Arrow, SQLite, WebDataset. Many kinds of compressed file types are also supported: GZ, BZ2, LZ4, LZMA or ZSTD. For example, your dataset can be made of `.json.gz` files. When loading a dataset from the Hub, all the files in the supported formats are loaded, following the [repository structure](./repository_structure). For more information on how to load a dataset from the Hub, take a look at the [load a dataset from the Hub](./load_hub) tutorial. ### Create the repository Sharing a community dataset will require you to create an account on [hf.co](https://huggingface.co/join) if you don't have one yet. You can directly create a [new dataset repository](https://huggingface.co/login?next=%2Fnew-dataset) from your account on the Hugging Face Hub, but this guide will show you how to upload a dataset from the terminal. 1. Make sure you are in the virtual environment where you installed Datasets, and run the following command: ``` huggingface-cli login ``` 2. Login using your Hugging Face Hub credentials, and create a new dataset repository: ``` huggingface-cli repo create my-cool-dataset --type dataset ``` Add the `-organization` flag to create a repository under a specific organization: ``` huggingface-cli repo create my-cool-dataset --type dataset --organization your-org-name ``` ## Prepare your files Check your directory to ensure the only files you're uploading are: - The data files of the dataset - The dataset card `README.md` ## huggingface-cli upload Use the `huggingface-cli upload` command to upload files to the Hub directly. Internally, it uses the same [`upload_file`] and [`upload_folder`] helpers described in the [Upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload). In the examples below, we will walk through the most common use cases. For a full list of available options, you can run: ```bash >>> huggingface-cli upload --help ``` For more general information about `huggingface-cli` you can check the [CLI guide](https://huggingface.co/docs/huggingface_hub/guides/cli). ### Upload an entire folder The default usage for this command is: ```bash # Usage: huggingface-cli upload [dataset_repo_id] [local_path] [path_in_repo] --repo-type dataset ``` To upload the current directory at the root of the repo, use: ```bash >>> huggingface-cli upload my-cool-dataset . . --repo-type dataset https://huggingface.co/datasets/Wauplin/my-cool-dataset/tree/main/ ``` <Tip> If the repo doesn't exist yet, it will be created automatically. </Tip> You can also upload a specific folder: ```bash >>> huggingface-cli upload my-cool-dataset ./data . --repo-type dataset https://huggingface.co/datasetsWauplin/my-cool-dataset/tree/main/ ``` Finally, you can upload a folder to a specific destination on the repo: ```bash >>> huggingface-cli upload my-cool-dataset ./path/to/curated/data /data/train --repo-type dataset https://huggingface.co/datasetsWauplin/my-cool-dataset/tree/main/data/train ``` ### Upload a single file You can also upload a single file by setting `local_path` to point to a file on your machine. If that's the case, `path_in_repo` is optional and will default to the name of your local file: ```bash >>> huggingface-cli upload Wauplin/my-cool-dataset ./files/train.csv --repo-type dataset https://huggingface.co/datasetsWauplin/my-cool-dataset/blob/main/train.csv ``` If you want to upload a single file to a specific directory, set `path_in_repo` accordingly: ```bash >>> huggingface-cli upload Wauplin/my-cool-dataset ./files/train.csv /data/train.csv --repo-type dataset https://huggingface.co/datasetsWauplin/my-cool-dataset/blob/main/data/train.csv ``` ### Upload multiple files To upload multiple files from a folder at once without uploading the entire folder, use the `--include` and `--exclude` patterns. It can also be combined with the `--delete` option to delete files on the repo while uploading new ones. In the example below, we sync the local Space by deleting remote files and uploading all CSV files: ```bash # Sync local Space with Hub (upload new CSV files, delete removed files) >>> huggingface-cli upload Wauplin/my-cool-dataset --repo-type dataset --include="/data/*.csv" --delete="*" --commit-message="Sync local dataset with Hub" ... ``` ### Upload to an organization To upload content to a repo owned by an organization instead of a personal repo, you must explicitly specify it in the `repo_id`: ```bash >>> huggingface-cli upload MyCoolOrganization/my-cool-dataset . . --repo-type dataset https://huggingface.co/datasetsMyCoolOrganization/my-cool-dataset/tree/main/ ``` ### Upload to a specific revision By default, files are uploaded to the `main` branch. If you want to upload files to another branch or reference, use the `--revision` option: ```bash # Upload files to a PR huggingface-cli upload bigcode/the-stack . . --repo-type dataset --revision refs/pr/104 ... ``` **Note:** if `revision` does not exist and `--create-pr` is not set, a branch will be created automatically from the `main` branch. ### Upload and create a PR If you don't have the permission to push to a repo, you must open a PR and let the authors know about the changes you want to make. This can be done by setting the `--create-pr` option: ```bash # Create a PR and upload the files to it >>> huggingface-cli upload bigcode/the-stack --repo-type dataset --revision refs/pr/104 --create-pr . . https://huggingface.co/datasets/bigcode/the-stack/blob/refs%2Fpr%2F104/ ``` ### Upload at regular intervals In some cases, you might want to push regular updates to a repo. For example, this is useful if your dataset is growing over time and you want to upload the data folder every 10 minutes. You can do this using the `--every` option: ```bash # Upload new logs every 10 minutes huggingface-cli upload my-cool-dynamic-dataset data/ --every=10 ``` ### Specify a commit message Use the `--commit-message` and `--commit-description` to set a custom message and description for your commit instead of the default one ```bash >>> huggingface-cli upload Wauplin/my-cool-dataset ./data . --repo-type dataset --commit-message="Version 2" --commit-description="Train size: 4321. Check Dataset Viewer for more details." ... https://huggingface.co/datasetsWauplin/my-cool-dataset/tree/main ``` ### Specify a token To upload files, you must use a token. By default, the token saved locally (using `huggingface-cli login`) will be used. If you want to authenticate explicitly, use the `--token` option: ```bash >>> huggingface-cli upload Wauplin/my-cool-dataset ./data . --repo-type dataset --token=hf_**** ... https://huggingface.co/datasetsWauplin/my-cool-data/tree/main ``` ### Quiet mode By default, the `huggingface-cli upload` command will be verbose. It will print details such as warning messages, information about the uploaded files, and progress bars. If you want to silence all of this, use the `--quiet` option. Only the last line (i.e. the URL to the uploaded files) is printed. This can prove useful if you want to pass the output to another command in a script. ```bash >>> huggingface-cli upload Wauplin/my-cool-dataset ./data . --repo-type dataset --quiet https://huggingface.co/datasets/Wauplin/my-cool-dataset/tree/main ``` ## Enjoy ! Congratulations, your dataset has now been uploaded to the Hugging Face Hub where anyone can load it in a single line of code! 🥳 ``` dataset = load_dataset("Wauplin/my-cool-dataset") ``` If your dataset is supported, it should also have a [Dataset Viewer](https://huggingface.co/docs/hub/datasets-viewer) for everyone to explore the dataset content. Finally, don't forget to enrich the dataset card to document your dataset and make it discoverable! Check out the [Create a dataset card](dataset_card) guide to learn more.
datasets/docs/source/share.mdx/0
{ "file_path": "datasets/docs/source/share.mdx", "repo_id": "datasets", "token_count": 2694 }
99
# Load video data <Tip warning={true}> Video support is experimental and is subject to change. </Tip> Video datasets have [`Video`] type columns, which contain `torchvision` objects. <Tip> To work with video datasets, you need to have the `torchvision` and `av` packages installed. Check out the [installation](https://github.com/pytorch/vision#installation) guide to learn how to install them. </Tip> When you load a video dataset and call the video column, the videos are decoded as `torchvision` Videos: ```py >>> from datasets import load_dataset, Video >>> dataset = load_dataset("path/to/video/folder", split="train") >>> dataset[0]["video"] <torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61d5a0> ``` <Tip warning={true}> Index into a video dataset using the row index first and then the `video` column - `dataset[0]["video"]` - to avoid creating all the video objects in the dataset. Otherwise, this can be a slow and time-consuming process if you have a large dataset. </Tip> For a guide on how to load any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./loading">general loading guide</a>. ## Read frames Access frames directly from a video using the `VideoReader` using `next()`: ```python >>> video = dataset[0]["video"] >>> first_frame = video.get_frame_at(0) >>> first_frame.data.shape (3, 240, 320) >>> first_frame.pts_seconds # timestamp 0.0 ``` To get multiple frames at once, you can call `.get_frames_in_range(start: int, stop: int, step: int)`. This will return a frame batch. This is the efficient way to obtain a long list of frames refer to the [torchcodec docs](https://docs.pytorch.org/torchcodec/stable/generated/torchcodec.decoders.VideoDecoder.html) to see more functions for effiently accessing the data: ```python >>> import torch >>> frames = video.get_frames_in_range(0, 6, 1) >>> frames.data.shape torch.Size([5, 3, 240, 320]) ``` There is also `.get_frames_played_in_range(start_seconds: float, stop_seconds: float)` to access all frames played whithin a certain time range. ```python >>> frames = video.get_frames_played_in_range(.5, 1.2) >>> frames.data.shape torch.Size([42, 3, 240, 320]) ``` ## Local files You can load a dataset from the video path. Use the [`~Dataset.cast_column`] function to accept a column of video file paths, and decode it into a `torchcodec` video with the [`Video`] feature: ```py >>> from datasets import Dataset, Video >>> dataset = Dataset.from_dict({"video": ["path/to/video_1", "path/to/video_2", ..., "path/to/video_n"]}).cast_column("video", Video()) >>> dataset[0]["video"] <torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61e080> ``` If you only want to load the underlying path to the video dataset without decoding the video object, set `decode=False` in the [`Video`] feature: ```py >>> dataset = dataset.cast_column("video", Video(decode=False)) >>> dataset[0]["video"] {'bytes': None, 'path': 'path/to/video/folder/video0.mp4'} ``` ## VideoFolder You can also load a dataset with an `VideoFolder` dataset builder which does not require writing a custom dataloader. This makes `VideoFolder` ideal for quickly creating and loading video datasets with several thousand videos for different vision tasks. Your video dataset structure should look like this: ``` folder/train/dog/golden_retriever.mp4 folder/train/dog/german_shepherd.mp4 folder/train/dog/chihuahua.mp4 folder/train/cat/maine_coon.mp4 folder/train/cat/bengal.mp4 folder/train/cat/birman.mp4 ``` If the dataset follows the `VideoFolder` structure, then you can load it directly with [`load_dataset`]: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("username/dataset_name") >>> # OR locally: >>> dataset = load_dataset("/path/to/folder") ``` For local datasets, this is equivalent to passing `videofolder` manually in [`load_dataset`] and the directory in `data_dir`: ```py >>> dataset = load_dataset("videofolder", data_dir="/path/to/folder") ``` Then you can access the videos as `torchcodec.decoders._video_decoder.VideoDecoder` objects: ``` >>> dataset["train"][0] {"video": <torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61e080>, "label": 0} >>> dataset["train"][-1] {"video": <torchcodec.decoders._video_decoder.VideoDecoder object at 0x14a61e090>, "label": 1} ``` To ignore the information in the metadata file, set `drop_metadata=True` in [`load_dataset`]: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("username/dataset_with_metadata", drop_metadata=True) ``` If you don't have a metadata file, `VideoFolder` automatically infers the label name from the directory name. If you want to drop automatically created labels, set `drop_labels=True`. In this case, your dataset will only contain a video column: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("username/dataset_without_metadata", drop_labels=True) ``` Finally the `filters` argument lets you load only a subset of the dataset, based on a condition on the label or the metadata. This is especially useful if the metadata is in Parquet format, since this format enables fast filtering. It is also recommended to use this argument with `streaming=True`, because by default the dataset is fully downloaded before filtering. ```python >>> filters = [("label", "=", 0)] >>> dataset = load_dataset("username/dataset_name", streaming=True, filters=filters) ``` <Tip> For more information about creating your own `VideoFolder` dataset, take a look at the [Create a video dataset](./video_dataset) guide. </Tip> ## WebDataset The [WebDataset](https://github.com/webdataset/webdataset) format is based on a folder of TAR archives and is suitable for big video datasets. Because of their size, WebDatasets are generally loaded in streaming mode (using `streaming=True`). You can load a WebDataset like this: ```python >>> from datasets import load_dataset >>> dataset = load_dataset("webdataset", data_dir="/path/to/folder", streaming=True) ``` ## Video decoding By default, videos are decoded sequentially as torchvision `VideoReaders` when you iterate on a dataset. It sequentially decodes the metadata of the videos, and doesn't read the video frames until you access them. However it is possible to speed up the dataset significantly using multithreaded decoding: ```python >>> import os >>> num_threads = num_threads = min(32, (os.cpu_count() or 1) + 4) >>> dataset = dataset.decode(num_threads=num_threads) >>> for example in dataset: # up to 20 times faster ! ... ... ``` You can enable multithreading using `num_threads`. This is especially useful to speed up remote data streaming. However it can be slower than `num_threads=0` for local data on fast disks. If you are not interested in the videos decoded as torchvision `VideoReaders` and would like to access the path/bytes instead, you can disable decoding: ```python >>> dataset = dataset.decode(False) ``` Note: [`IterableDataset.decode`] is only available for streaming datasets at the moment.
datasets/docs/source/video_load.mdx/0
{ "file_path": "datasets/docs/source/video_load.mdx", "repo_id": "datasets", "token_count": 2196 }
100
import os import re from functools import partial from glob import has_magic from pathlib import Path, PurePath from typing import Callable, Optional, Union import huggingface_hub from fsspec.core import url_to_fs from huggingface_hub import HfFileSystem from packaging import version from tqdm.contrib.concurrent import thread_map from . import config from .download import DownloadConfig from .naming import _split_re from .splits import Split from .utils import logging from .utils import tqdm as hf_tqdm from .utils.file_utils import _prepare_path_and_storage_options, is_local_path, is_relative_path, xbasename, xjoin from .utils.py_utils import string_to_dict SingleOriginMetadata = Union[tuple[str, str], tuple[str], tuple[()]] SANITIZED_DEFAULT_SPLIT = str(Split.TRAIN) logger = logging.get_logger(__name__) class Url(str): pass class EmptyDatasetError(FileNotFoundError): pass SPLIT_PATTERN_SHARDED = "data/{split}-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*" SPLIT_KEYWORDS = { Split.TRAIN: ["train", "training"], Split.VALIDATION: ["validation", "valid", "dev", "val"], Split.TEST: ["test", "testing", "eval", "evaluation"], } NON_WORDS_CHARS = "-._ 0-9" if config.FSSPEC_VERSION < version.parse("2023.9.0"): KEYWORDS_IN_FILENAME_BASE_PATTERNS = ["**[{sep}/]{keyword}[{sep}]*", "{keyword}[{sep}]*"] KEYWORDS_IN_DIR_NAME_BASE_PATTERNS = [ "{keyword}/**", "{keyword}[{sep}]*/**", "**[{sep}/]{keyword}/**", "**[{sep}/]{keyword}[{sep}]*/**", ] elif config.FSSPEC_VERSION < version.parse("2023.12.0"): KEYWORDS_IN_FILENAME_BASE_PATTERNS = ["**/*[{sep}/]{keyword}[{sep}]*", "{keyword}[{sep}]*"] KEYWORDS_IN_DIR_NAME_BASE_PATTERNS = [ "{keyword}/**/*", "{keyword}[{sep}]*/**/*", "**/*[{sep}/]{keyword}/**/*", "**/*[{sep}/]{keyword}[{sep}]*/**/*", ] else: KEYWORDS_IN_FILENAME_BASE_PATTERNS = ["**/{keyword}[{sep}]*", "**/*[{sep}]{keyword}[{sep}]*"] KEYWORDS_IN_DIR_NAME_BASE_PATTERNS = [ "**/{keyword}/**", "**/{keyword}[{sep}]*/**", "**/*[{sep}]{keyword}/**", "**/*[{sep}]{keyword}[{sep}]*/**", ] DEFAULT_SPLITS = [Split.TRAIN, Split.VALIDATION, Split.TEST] DEFAULT_PATTERNS_SPLIT_IN_FILENAME = { split: [ pattern.format(keyword=keyword, sep=NON_WORDS_CHARS) for keyword in SPLIT_KEYWORDS[split] for pattern in KEYWORDS_IN_FILENAME_BASE_PATTERNS ] for split in DEFAULT_SPLITS } DEFAULT_PATTERNS_SPLIT_IN_DIR_NAME = { split: [ pattern.format(keyword=keyword, sep=NON_WORDS_CHARS) for keyword in SPLIT_KEYWORDS[split] for pattern in KEYWORDS_IN_DIR_NAME_BASE_PATTERNS ] for split in DEFAULT_SPLITS } DEFAULT_PATTERNS_ALL = { Split.TRAIN: ["**"], } ALL_SPLIT_PATTERNS = [SPLIT_PATTERN_SHARDED] ALL_DEFAULT_PATTERNS = [ DEFAULT_PATTERNS_SPLIT_IN_DIR_NAME, DEFAULT_PATTERNS_SPLIT_IN_FILENAME, DEFAULT_PATTERNS_ALL, ] WILDCARD_CHARACTERS = "*[]" FILES_TO_IGNORE = [ "README.md", "config.json", "dataset_info.json", "dataset_infos.json", "dummy_data.zip", "dataset_dict.json", ] def contains_wildcards(pattern: str) -> bool: return any(wildcard_character in pattern for wildcard_character in WILDCARD_CHARACTERS) def sanitize_patterns(patterns: Union[dict, list, str]) -> dict[str, Union[list[str], "DataFilesList"]]: """ Take the data_files patterns from the user, and format them into a dictionary. Each key is the name of the split, and each value is a list of data files patterns (paths or urls). The default split is "train". Returns: patterns: dictionary of split_name -> list of patterns """ if isinstance(patterns, dict): return {str(key): value if isinstance(value, list) else [value] for key, value in patterns.items()} elif isinstance(patterns, str): return {SANITIZED_DEFAULT_SPLIT: [patterns]} elif isinstance(patterns, list): if any(isinstance(pattern, dict) for pattern in patterns): for pattern in patterns: if not ( isinstance(pattern, dict) and len(pattern) == 2 and "split" in pattern and isinstance(pattern.get("path"), (str, list)) ): raise ValueError( f"Expected each split to have a 'path' key which can be a string or a list of strings, but got {pattern}" ) splits = [pattern["split"] for pattern in patterns] if len(set(splits)) != len(splits): raise ValueError(f"Some splits are duplicated in data_files: {splits}") return { str(pattern["split"]): pattern["path"] if isinstance(pattern["path"], list) else [pattern["path"]] for pattern in patterns } else: return {SANITIZED_DEFAULT_SPLIT: patterns} else: return sanitize_patterns(list(patterns)) def _is_inside_unrequested_special_dir(matched_rel_path: str, pattern: str) -> bool: """ When a path matches a pattern, we additionally check if it's inside a special directory we ignore by default (if it starts with a double underscore). Users can still explicitly request a filepath inside such a directory if "__pycache__" is mentioned explicitly in the requested pattern. Some examples: base directory: ./ └── __pycache__ └── b.txt >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "**") True >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "*/b.txt") True >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "__pycache__/*") False >>> _is_inside_unrequested_special_dir("__pycache__/b.txt", "__*/*") False """ # We just need to check if every special directories from the path is present explicitly in the pattern. # Since we assume that the path matches the pattern, it's equivalent to counting that both # the parent path and the parent pattern have the same number of special directories. data_dirs_to_ignore_in_path = [part for part in PurePath(matched_rel_path).parent.parts if part.startswith("__")] data_dirs_to_ignore_in_pattern = [part for part in PurePath(pattern).parent.parts if part.startswith("__")] return len(data_dirs_to_ignore_in_path) != len(data_dirs_to_ignore_in_pattern) def _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(matched_rel_path: str, pattern: str) -> bool: """ When a path matches a pattern, we additionally check if it's a hidden file or if it's inside a hidden directory we ignore by default, i.e. if the file name or a parent directory name starts with a dot. Users can still explicitly request a filepath that is hidden or is inside a hidden directory if the hidden part is mentioned explicitly in the requested pattern. Some examples: base directory: ./ └── .hidden_file.txt >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_file.txt", "**") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_file.txt", ".*") False base directory: ./ └── .hidden_dir └── a.txt >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", "**") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", ".*/*") False >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/a.txt", ".hidden_dir/*") False base directory: ./ └── .hidden_dir └── .hidden_file.txt >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", "**") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".*/*") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".*/.*") False >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".hidden_dir/*") True >>> _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(".hidden_dir/.hidden_file.txt", ".hidden_dir/.*") False """ # We just need to check if every hidden part from the path is present explicitly in the pattern. # Since we assume that the path matches the pattern, it's equivalent to counting that both # the path and the pattern have the same number of hidden parts. hidden_directories_in_path = [ part for part in PurePath(matched_rel_path).parts if part.startswith(".") and not set(part) == {"."} ] hidden_directories_in_pattern = [ part for part in PurePath(pattern).parts if part.startswith(".") and not set(part) == {"."} ] return len(hidden_directories_in_path) != len(hidden_directories_in_pattern) def _get_data_files_patterns(pattern_resolver: Callable[[str], list[str]]) -> dict[str, list[str]]: """ Get the default pattern from a directory or repository by testing all the supported patterns. The first patterns to return a non-empty list of data files is returned. In order, it first tests if SPLIT_PATTERN_SHARDED works, otherwise it tests the patterns in ALL_DEFAULT_PATTERNS. """ # first check the split patterns like data/{split}-00000-of-00001.parquet for split_pattern in ALL_SPLIT_PATTERNS: pattern = split_pattern.replace("{split}", "*") try: data_files = pattern_resolver(pattern) except FileNotFoundError: continue if len(data_files) > 0: splits: set[str] = set() for p in data_files: p_parts = string_to_dict(xbasename(p), xbasename(split_pattern)) assert p_parts is not None splits.add(p_parts["split"]) if any(not re.match(_split_re, split) for split in splits): raise ValueError(f"Split name should match '{_split_re}'' but got '{splits}'.") sorted_splits = [str(split) for split in DEFAULT_SPLITS if split in splits] + sorted( splits - {str(split) for split in DEFAULT_SPLITS} ) return {split: [split_pattern.format(split=split)] for split in sorted_splits} # then check the default patterns based on train/valid/test splits for patterns_dict in ALL_DEFAULT_PATTERNS: non_empty_splits = [] for split, patterns in patterns_dict.items(): for pattern in patterns: try: data_files = pattern_resolver(pattern) except FileNotFoundError: continue if len(data_files) > 0: non_empty_splits.append(split) break if non_empty_splits: return {split: patterns_dict[split] for split in non_empty_splits} raise FileNotFoundError(f"Couldn't resolve pattern {pattern} with resolver {pattern_resolver}") def resolve_pattern( pattern: str, base_path: str, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> list[str]: """ Resolve the paths and URLs of the data files from the pattern passed by the user. You can use patterns to resolve multiple local files. Here are a few examples: - *.csv to match all the CSV files at the first level - **.csv to match all the CSV files at any level - data/* to match all the files inside "data" - data/** to match all the files inside "data" and its subdirectories The patterns are resolved using the fsspec glob. In fsspec>=2023.12.0 this is equivalent to Python's glob.glob, Path.glob, Path.match and fnmatch where ** is unsupported with a prefix/suffix other than a forward slash /. More generally: - '*' matches any character except a forward-slash (to match just the file or directory name) - '**' matches any character including a forward-slash / Hidden files and directories (i.e. whose names start with a dot) are ignored, unless they are explicitly requested. The same applies to special directories that start with a double underscore like "__pycache__". You can still include one if the pattern explicitly mentions it: - to include a hidden file: "*/.hidden.txt" or "*/.*" - to include a hidden directory: ".hidden/*" or ".*/*" - to include a special directory: "__special__/*" or "__*/*" Example:: >>> from datasets.data_files import resolve_pattern >>> base_path = "." >>> resolve_pattern("docs/**/*.py", base_path) [/Users/mariosasko/Desktop/projects/datasets/docs/source/_config.py'] Args: pattern (str): Unix pattern or paths or URLs of the data files to resolve. The paths can be absolute or relative to base_path. Remote filesystems using fsspec are supported, e.g. with the hf:// protocol. base_path (str): Base path to use when resolving relative paths. allowed_extensions (Optional[list], optional): White-list of file extensions to use. Defaults to None (all extensions). For example: allowed_extensions=[".csv", ".json", ".txt", ".parquet"] download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. Returns: List[str]: List of paths or URLs to the local or remote files that match the patterns. """ if is_relative_path(pattern): pattern = xjoin(base_path, pattern) elif is_local_path(pattern): base_path = os.path.splitdrive(pattern)[0] + os.sep else: base_path = "" pattern, storage_options = _prepare_path_and_storage_options(pattern, download_config=download_config) fs, fs_pattern = url_to_fs(pattern, **storage_options) files_to_ignore = set(FILES_TO_IGNORE) - {xbasename(pattern)} protocol = fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0] protocol_prefix = protocol + "://" if protocol != "file" else "" glob_kwargs = {} if protocol == "hf" and config.HF_HUB_VERSION >= version.parse("0.20.0"): # 10 times faster glob with detail=True (ignores costly info like lastCommit) glob_kwargs["expand_info"] = False matched_paths = [ filepath if filepath.startswith(protocol_prefix) else protocol_prefix + filepath for filepath, info in fs.glob(pattern, detail=True, **glob_kwargs).items() if (info["type"] == "file" or (info.get("islink") and os.path.isfile(os.path.realpath(filepath)))) and (xbasename(filepath) not in files_to_ignore) and not _is_inside_unrequested_special_dir(filepath, fs_pattern) and not _is_unrequested_hidden_file_or_is_inside_unrequested_hidden_dir(filepath, fs_pattern) ] # ignore .ipynb and __pycache__, but keep /../ if allowed_extensions is not None: out = [ filepath for filepath in matched_paths if any("." + suffix in allowed_extensions for suffix in xbasename(filepath).split(".")[1:]) ] if len(out) < len(matched_paths): invalid_matched_files = list(set(matched_paths) - set(out)) logger.info( f"Some files matched the pattern '{pattern}' but don't have valid data file extensions: {invalid_matched_files}" ) else: out = matched_paths if not out: error_msg = f"Unable to find '{pattern}'" if allowed_extensions is not None: error_msg += f" with any supported extension {list(allowed_extensions)}" raise FileNotFoundError(error_msg) return out def get_data_patterns(base_path: str, download_config: Optional[DownloadConfig] = None) -> dict[str, list[str]]: """ Get the default pattern from a directory testing all the supported patterns. The first patterns to return a non-empty list of data files is returned. Some examples of supported patterns: Input: my_dataset_repository/ ├── README.md └── dataset.csv Output: {'train': ['**']} Input: my_dataset_repository/ ├── README.md ├── train.csv └── test.csv my_dataset_repository/ ├── README.md └── data/ ├── train.csv └── test.csv my_dataset_repository/ ├── README.md ├── train_0.csv ├── train_1.csv ├── train_2.csv ├── train_3.csv ├── test_0.csv └── test_1.csv Output: {'train': ['**/train[-._ 0-9]*', '**/*[-._ 0-9]train[-._ 0-9]*', '**/training[-._ 0-9]*', '**/*[-._ 0-9]training[-._ 0-9]*'], 'test': ['**/test[-._ 0-9]*', '**/*[-._ 0-9]test[-._ 0-9]*', '**/testing[-._ 0-9]*', '**/*[-._ 0-9]testing[-._ 0-9]*', ...]} Input: my_dataset_repository/ ├── README.md └── data/ ├── train/ │ ├── shard_0.csv │ ├── shard_1.csv │ ├── shard_2.csv │ └── shard_3.csv └── test/ ├── shard_0.csv └── shard_1.csv Output: {'train': ['**/train/**', '**/train[-._ 0-9]*/**', '**/*[-._ 0-9]train/**', '**/*[-._ 0-9]train[-._ 0-9]*/**', ...], 'test': ['**/test/**', '**/test[-._ 0-9]*/**', '**/*[-._ 0-9]test/**', '**/*[-._ 0-9]test[-._ 0-9]*/**', ...]} Input: my_dataset_repository/ ├── README.md └── data/ ├── train-00000-of-00003.csv ├── train-00001-of-00003.csv ├── train-00002-of-00003.csv ├── test-00000-of-00001.csv ├── random-00000-of-00003.csv ├── random-00001-of-00003.csv └── random-00002-of-00003.csv Output: {'train': ['data/train-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*'], 'test': ['data/test-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*'], 'random': ['data/random-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]*.*']} In order, it first tests if SPLIT_PATTERN_SHARDED works, otherwise it tests the patterns in ALL_DEFAULT_PATTERNS. """ resolver = partial(resolve_pattern, base_path=base_path, download_config=download_config) try: return _get_data_files_patterns(resolver) except FileNotFoundError: raise EmptyDatasetError(f"The directory at {base_path} doesn't contain any data files") from None def _get_single_origin_metadata( data_file: str, download_config: Optional[DownloadConfig] = None, ) -> SingleOriginMetadata: data_file, storage_options = _prepare_path_and_storage_options(data_file, download_config=download_config) fs, *_ = url_to_fs(data_file, **storage_options) if isinstance(fs, HfFileSystem): resolved_path = fs.resolve_path(data_file) return resolved_path.repo_id, resolved_path.revision elif data_file.startswith(config.HF_ENDPOINT): hffs = HfFileSystem(endpoint=config.HF_ENDPOINT, token=download_config.token) data_file = "hf://" + data_file[len(config.HF_ENDPOINT) + 1 :].replace("/resolve/", "@", 1) resolved_path = hffs.resolve_path(data_file) return resolved_path.repo_id, resolved_path.revision info = fs.info(data_file) # s3fs uses "ETag", gcsfs uses "etag", and for local we simply check mtime for key in ["ETag", "etag", "mtime"]: if key in info: return (str(info[key]),) return () def _get_origin_metadata( data_files: list[str], download_config: Optional[DownloadConfig] = None, max_workers: Optional[int] = None, ) -> list[SingleOriginMetadata]: max_workers = max_workers if max_workers is not None else config.HF_DATASETS_MULTITHREADING_MAX_WORKERS return thread_map( partial(_get_single_origin_metadata, download_config=download_config), data_files, max_workers=max_workers, tqdm_class=hf_tqdm, desc="Resolving data files", # set `disable=None` rather than `disable=False` by default to disable progress bar when no TTY attached disable=len(data_files) <= 16 or None, ) class DataFilesList(list[str]): """ List of data files (absolute local paths or URLs). It has two construction methods given the user's data files patterns: - ``from_hf_repo``: resolve patterns inside a dataset repository - ``from_local_or_remote``: resolve patterns from a local path Moreover, DataFilesList has an additional attribute ``origin_metadata``. It can store: - the last modified time of local files - ETag of remote files - commit sha of a dataset repository Thanks to this additional attribute, it is possible to hash the list and get a different hash if and only if at least one file changed. This is useful for caching Dataset objects that are obtained from a list of data files. """ def __init__(self, data_files: list[str], origin_metadata: list[SingleOriginMetadata]) -> None: super().__init__(data_files) self.origin_metadata = origin_metadata def __add__(self, other: "DataFilesList") -> "DataFilesList": return DataFilesList([*self, *other], self.origin_metadata + other.origin_metadata) @classmethod def from_hf_repo( cls, patterns: list[str], dataset_info: huggingface_hub.hf_api.DatasetInfo, base_path: Optional[str] = None, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = f"hf://datasets/{dataset_info.id}@{dataset_info.sha}/{base_path or ''}".rstrip("/") return cls.from_patterns( patterns, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config ) @classmethod def from_local_or_remote( cls, patterns: list[str], base_path: Optional[str] = None, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = base_path if base_path is not None else Path().resolve().as_posix() return cls.from_patterns( patterns, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config ) @classmethod def from_patterns( cls, patterns: list[str], base_path: Optional[str] = None, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = base_path if base_path is not None else Path().resolve().as_posix() data_files = [] for pattern in patterns: try: data_files.extend( resolve_pattern( pattern, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) except FileNotFoundError: if not has_magic(pattern): raise origin_metadata = _get_origin_metadata(data_files, download_config=download_config) return cls(data_files, origin_metadata) def filter( self, *, extensions: Optional[list[str]] = None, file_names: Optional[list[str]] = None ) -> "DataFilesList": patterns = [] if extensions: ext_pattern = "|".join(re.escape(ext) for ext in extensions) patterns.append(re.compile(f".*({ext_pattern})(\\..+)?$")) if file_names: fn_pattern = "|".join(re.escape(fn) for fn in file_names) patterns.append(re.compile(rf".*[\/]?({fn_pattern})$")) if patterns: return DataFilesList( [data_file for data_file in self if any(pattern.match(data_file) for pattern in patterns)], origin_metadata=self.origin_metadata, ) else: return DataFilesList(list(self), origin_metadata=self.origin_metadata) class DataFilesDict(dict[str, DataFilesList]): """ Dict of split_name -> list of data files (absolute local paths or URLs). It has two construction methods given the user's data files patterns : - ``from_hf_repo``: resolve patterns inside a dataset repository - ``from_local_or_remote``: resolve patterns from a local path Moreover, each list is a DataFilesList. It is possible to hash the dictionary and get a different hash if and only if at least one file changed. For more info, see [`DataFilesList`]. This is useful for caching Dataset objects that are obtained from a list of data files. Changing the order of the keys of this dictionary also doesn't change its hash. """ @classmethod def from_local_or_remote( cls, patterns: dict[str, Union[list[str], DataFilesList]], base_path: Optional[str] = None, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesList) else DataFilesList.from_local_or_remote( patterns_for_key, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) return out @classmethod def from_hf_repo( cls, patterns: dict[str, Union[list[str], DataFilesList]], dataset_info: huggingface_hub.hf_api.DatasetInfo, base_path: Optional[str] = None, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesList) else DataFilesList.from_hf_repo( patterns_for_key, dataset_info=dataset_info, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) return out @classmethod def from_patterns( cls, patterns: dict[str, Union[list[str], DataFilesList]], base_path: Optional[str] = None, allowed_extensions: Optional[list[str]] = None, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesList) else DataFilesList.from_patterns( patterns_for_key, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) return out def filter( self, *, extensions: Optional[list[str]] = None, file_names: Optional[list[str]] = None ) -> "DataFilesDict": out = type(self)() for key, data_files_list in self.items(): out[key] = data_files_list.filter(extensions=extensions, file_names=file_names) return out class DataFilesPatternsList(list[str]): """ List of data files patterns (absolute local paths or URLs). For each pattern there should also be a list of allowed extensions to keep, or a None ot keep all the files for the pattern. """ def __init__( self, patterns: list[str], allowed_extensions: list[Optional[list[str]]], ): super().__init__(patterns) self.allowed_extensions = allowed_extensions def __add__(self, other): return DataFilesList([*self, *other], self.allowed_extensions + other.allowed_extensions) @classmethod def from_patterns( cls, patterns: list[str], allowed_extensions: Optional[list[str]] = None ) -> "DataFilesPatternsList": return cls(patterns, [allowed_extensions] * len(patterns)) def resolve( self, base_path: str, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesList": base_path = base_path if base_path is not None else Path().resolve().as_posix() data_files = [] for pattern, allowed_extensions in zip(self, self.allowed_extensions): try: data_files.extend( resolve_pattern( pattern, base_path=base_path, allowed_extensions=allowed_extensions, download_config=download_config, ) ) except FileNotFoundError: if not has_magic(pattern): raise origin_metadata = _get_origin_metadata(data_files, download_config=download_config) return DataFilesList(data_files, origin_metadata) def filter_extensions(self, extensions: list[str]) -> "DataFilesPatternsList": return DataFilesPatternsList( self, [allowed_extensions + extensions for allowed_extensions in self.allowed_extensions] ) class DataFilesPatternsDict(dict[str, DataFilesPatternsList]): """ Dict of split_name -> list of data files patterns (absolute local paths or URLs). """ @classmethod def from_patterns( cls, patterns: dict[str, list[str]], allowed_extensions: Optional[list[str]] = None ) -> "DataFilesPatternsDict": out = cls() for key, patterns_for_key in patterns.items(): out[key] = ( patterns_for_key if isinstance(patterns_for_key, DataFilesPatternsList) else DataFilesPatternsList.from_patterns( patterns_for_key, allowed_extensions=allowed_extensions, ) ) return out def resolve( self, base_path: str, download_config: Optional[DownloadConfig] = None, ) -> "DataFilesDict": out = DataFilesDict() for key, data_files_patterns_list in self.items(): out[key] = data_files_patterns_list.resolve(base_path, download_config) return out def filter_extensions(self, extensions: list[str]) -> "DataFilesPatternsDict": out = type(self)() for key, data_files_patterns_list in self.items(): out[key] = data_files_patterns_list.filter_extensions(extensions) return out
datasets/src/datasets/data_files.py/0
{ "file_path": "datasets/src/datasets/data_files.py", "repo_id": "datasets", "token_count": 13454 }
101
import importlib import shutil import warnings from typing import List import fsspec import fsspec.asyn from fsspec.implementations.local import LocalFileSystem from . import compression COMPRESSION_FILESYSTEMS: list[compression.BaseCompressedFileFileSystem] = [ compression.Bz2FileSystem, compression.GzipFileSystem, compression.Lz4FileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(f"A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.") fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool: """ Checks if `fs` is a remote filesystem. Args: fs (`fsspec.spec.AbstractFileSystem`): An abstract super-class for pythonic file-systems, e.g. `fsspec.filesystem(\'file\')` or `s3fs.S3FileSystem`. """ return not isinstance(fs, LocalFileSystem) def rename(fs: fsspec.AbstractFileSystem, src: str, dst: str): """ Renames the file `src` in `fs` to `dst`. """ if not is_remote_filesystem(fs): # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(src), fs._strip_protocol(dst)) else: fs.mv(src, dst, recursive=True)
datasets/src/datasets/filesystems/__init__.py/0
{ "file_path": "datasets/src/datasets/filesystems/__init__.py", "repo_id": "datasets", "token_count": 564 }
102
from typing import Callable, Optional from .. import Features, NamedSplit, Split from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class GeneratorDatasetInputStream(AbstractDatasetInputStream): def __init__( self, generator: Callable, features: Optional[Features] = None, cache_dir: str = None, keep_in_memory: bool = False, streaming: bool = False, gen_kwargs: Optional[dict] = None, num_proc: Optional[int] = None, split: NamedSplit = Split.TRAIN, **kwargs, ): super().__init__( features=features, cache_dir=cache_dir, keep_in_memory=keep_in_memory, streaming=streaming, num_proc=num_proc, **kwargs, ) self.builder = Generator( cache_dir=cache_dir, features=features, generator=generator, gen_kwargs=gen_kwargs, split=split, **kwargs, ) def read(self): # Build iterable dataset if self.streaming: dataset = self.builder.as_streaming_dataset(split=self.builder.config.split) # Build regular (map-style) dataset else: download_config = None download_mode = None verification_mode = None base_path = None self.builder.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, base_path=base_path, num_proc=self.num_proc, ) dataset = self.builder.as_dataset( split=self.builder.config.split, verification_mode=verification_mode, in_memory=self.keep_in_memory ) return dataset
datasets/src/datasets/io/generator.py/0
{ "file_path": "datasets/src/datasets/io/generator.py", "repo_id": "datasets", "token_count": 920 }
103
import glob import json import os import shutil import time from pathlib import Path from typing import Optional, Union import pyarrow as pa import datasets import datasets.config import datasets.data_files from datasets.naming import camelcase_to_snakecase, filenames_for_dataset_split logger = datasets.utils.logging.get_logger(__name__) def _get_modification_time(cached_directory_path): return (Path(cached_directory_path)).stat().st_mtime def _find_hash_in_cache( dataset_name: str, config_name: Optional[str], cache_dir: Optional[str], config_kwargs: dict, custom_features: Optional[datasets.Features], ) -> tuple[str, str, str]: if config_name or config_kwargs or custom_features: config_id = datasets.BuilderConfig(config_name or "default").create_config_id( config_kwargs=config_kwargs, custom_features=custom_features ) else: config_id = None cache_dir = os.path.expanduser(str(cache_dir or datasets.config.HF_DATASETS_CACHE)) namespace_and_dataset_name = dataset_name.split("/") namespace_and_dataset_name[-1] = camelcase_to_snakecase(namespace_and_dataset_name[-1]) cached_relative_path = "___".join(namespace_and_dataset_name) cached_datasets_directory_path_root = os.path.join(cache_dir, cached_relative_path) cached_directory_paths = [ cached_directory_path for cached_directory_path in glob.glob( os.path.join(cached_datasets_directory_path_root, config_id or "*", "*", "*") ) if os.path.isdir(cached_directory_path) and ( config_kwargs or custom_features or json.loads(Path(cached_directory_path, "dataset_info.json").read_text(encoding="utf-8"))["config_name"] == Path(cached_directory_path).parts[-3] # no extra params => config_id == config_name ) ] if not cached_directory_paths: cached_directory_paths = [ cached_directory_path for cached_directory_path in glob.glob(os.path.join(cached_datasets_directory_path_root, "*", "*", "*")) if os.path.isdir(cached_directory_path) ] available_configs = sorted( {Path(cached_directory_path).parts[-3] for cached_directory_path in cached_directory_paths} ) raise ValueError( f"Couldn't find cache for {dataset_name}" + (f" for config '{config_id}'" if config_id else "") + (f"\nAvailable configs in the cache: {available_configs}" if available_configs else "") ) # get most recent cached_directory_path = Path(sorted(cached_directory_paths, key=_get_modification_time)[-1]) version, hash = cached_directory_path.parts[-2:] other_configs = [ Path(_cached_directory_path).parts[-3] for _cached_directory_path in glob.glob(os.path.join(cached_datasets_directory_path_root, "*", version, hash)) if os.path.isdir(_cached_directory_path) and ( config_kwargs or custom_features or json.loads(Path(_cached_directory_path, "dataset_info.json").read_text(encoding="utf-8"))["config_name"] == Path(_cached_directory_path).parts[-3] # no extra params => config_id == config_name ) ] if not config_id and len(other_configs) > 1: raise ValueError( f"There are multiple '{dataset_name}' configurations in the cache: {', '.join(other_configs)}" f"\nPlease specify which configuration to reload from the cache, e.g." f"\n\tload_dataset('{dataset_name}', '{other_configs[0]}')" ) config_name = cached_directory_path.parts[-3] warning_msg = ( f"Found the latest cached dataset configuration '{config_name}' at {cached_directory_path} " f"(last modified on {time.ctime(_get_modification_time(cached_directory_path))})." ) logger.warning(warning_msg) return config_name, version, hash class Cache(datasets.ArrowBasedBuilder): def __init__( self, cache_dir: Optional[str] = None, dataset_name: Optional[str] = None, config_name: Optional[str] = None, version: Optional[str] = "0.0.0", hash: Optional[str] = None, base_path: Optional[str] = None, info: Optional[datasets.DatasetInfo] = None, features: Optional[datasets.Features] = None, token: Optional[Union[bool, str]] = None, repo_id: Optional[str] = None, data_files: Optional[Union[str, list, dict, datasets.data_files.DataFilesDict]] = None, data_dir: Optional[str] = None, storage_options: Optional[dict] = None, writer_batch_size: Optional[int] = None, **config_kwargs, ): if repo_id is None and dataset_name is None: raise ValueError("repo_id or dataset_name is required for the Cache dataset builder") if data_files is not None: config_kwargs["data_files"] = data_files if data_dir is not None: config_kwargs["data_dir"] = data_dir if hash == "auto" and version == "auto": config_name, version, hash = _find_hash_in_cache( dataset_name=repo_id or dataset_name, config_name=config_name, cache_dir=cache_dir, config_kwargs=config_kwargs, custom_features=features, ) elif hash == "auto" or version == "auto": raise NotImplementedError("Pass both hash='auto' and version='auto' instead") super().__init__( cache_dir=cache_dir, dataset_name=dataset_name, config_name=config_name, version=version, hash=hash, base_path=base_path, info=info, token=token, repo_id=repo_id, storage_options=storage_options, writer_batch_size=writer_batch_size, ) def _info(self) -> datasets.DatasetInfo: return datasets.DatasetInfo() def download_and_prepare(self, output_dir: Optional[str] = None, *args, **kwargs): if not os.path.exists(self.cache_dir): raise ValueError(f"Cache directory for {self.dataset_name} doesn't exist at {self.cache_dir}") if output_dir is not None and output_dir != self.cache_dir: shutil.copytree(self.cache_dir, output_dir) def _split_generators(self, dl_manager): # used to stream from cache if isinstance(self.info.splits, datasets.SplitDict): split_infos: list[datasets.SplitInfo] = list(self.info.splits.values()) else: raise ValueError(f"Missing splits info for {self.dataset_name} in cache directory {self.cache_dir}") return [ datasets.SplitGenerator( name=split_info.name, gen_kwargs={ "files": filenames_for_dataset_split( self.cache_dir, dataset_name=self.dataset_name, split=split_info.name, filetype_suffix="arrow", shard_lengths=split_info.shard_lengths, ) }, ) for split_info in split_infos ] def _generate_tables(self, files): # used to stream from cache for file_idx, file in enumerate(files): with open(file, "rb") as f: try: for batch_idx, record_batch in enumerate(pa.ipc.open_stream(f)): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", pa_table except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
datasets/src/datasets/packaged_modules/cache/cache.py/0
{ "file_path": "datasets/src/datasets/packaged_modules/cache/cache.py", "repo_id": "datasets", "token_count": 3782 }
104
import itertools from dataclasses import dataclass from typing import Optional, Union import pyarrow as pa import pyarrow.dataset as ds import pyarrow.parquet as pq import datasets from datasets.table import table_cast logger = datasets.utils.logging.get_logger(__name__) @dataclass class ParquetConfig(datasets.BuilderConfig): """BuilderConfig for Parquet.""" batch_size: Optional[int] = None columns: Optional[list[str]] = None features: Optional[datasets.Features] = None filters: Optional[Union[ds.Expression, list[tuple], list[list[tuple]]]] = None def __post_init__(self): super().__post_init__() class Parquet(datasets.ArrowBasedBuilder): BUILDER_CONFIG_CLASS = ParquetConfig def _info(self): if ( self.config.columns is not None and self.config.features is not None and set(self.config.columns) != set(self.config.features) ): raise ValueError( "The columns and features argument must contain the same columns, but got ", f"{self.config.columns} and {self.config.features}", ) return datasets.DatasetInfo(features=self.config.features) def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") dl_manager.download_config.extract_on_the_fly = True data_files = dl_manager.download_and_extract(self.config.data_files) splits = [] for split_name, files in data_files.items(): if isinstance(files, str): files = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive files = [dl_manager.iter_files(file) for file in files] # Infer features if they are stored in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(files): with open(file, "rb") as f: self.info.features = datasets.Features.from_arrow_schema(pq.read_schema(f)) break splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"files": files})) if self.config.columns is not None and set(self.config.columns) != set(self.info.features): self.info.features = datasets.Features( {col: feat for col, feat in self.info.features.items() if col in self.config.columns} ) return splits def _cast_table(self, pa_table: pa.Table) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example pa_table = table_cast(pa_table, self.info.features.arrow_schema) return pa_table def _generate_tables(self, files): if self.config.features is not None and self.config.columns is not None: if sorted(field.name for field in self.info.features.arrow_schema) != sorted(self.config.columns): raise ValueError( f"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'" ) filter_expr = ( pq.filters_to_expression(self.config.filters) if isinstance(self.config.filters, list) else self.config.filters ) for file_idx, file in enumerate(itertools.chain.from_iterable(files)): with open(file, "rb") as f: parquet_fragment = ds.ParquetFileFormat().make_fragment(f) if parquet_fragment.row_groups: batch_size = self.config.batch_size or parquet_fragment.row_groups[0].num_rows try: for batch_idx, record_batch in enumerate( parquet_fragment.to_batches( batch_size=batch_size, columns=self.config.columns, filter=filter_expr, batch_readahead=0, fragment_readahead=0, ) ): pa_table = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(e)}: {e}") raise
datasets/src/datasets/packaged_modules/parquet/parquet.py/0
{ "file_path": "datasets/src/datasets/packaged_modules/parquet/parquet.py", "repo_id": "datasets", "token_count": 2413 }
105
from .parallel import ParallelBackendConfig, parallel_backend, parallel_map
datasets/src/datasets/parallel/__init__.py/0
{ "file_path": "datasets/src/datasets/parallel/__init__.py", "repo_id": "datasets", "token_count": 19 }
106
from functools import partial from huggingface_hub import hf_hub_url from huggingface_hub.utils import get_session, hf_raise_for_status hf_dataset_url = partial(hf_hub_url, repo_type="dataset") def check_auth(hf_api, repo_id, token=None): headers = hf_api._build_hf_headers(token=token) path = f"{hf_api.endpoint}/api/datasets/{repo_id}/auth-check" r = get_session().get(path, headers=headers) hf_raise_for_status(r)
datasets/src/datasets/utils/hub.py/0
{ "file_path": "datasets/src/datasets/utils/hub.py", "repo_id": "datasets", "token_count": 180 }
107
from collections.abc import Iterable, Iterator class tracked_str(str): origins = {} def set_origin(self, origin: str): if super().__repr__() not in self.origins: self.origins[super().__repr__()] = origin def get_origin(self): return self.origins.get(super().__repr__(), str(self)) def __repr__(self) -> str: if super().__repr__() not in self.origins or self.origins[super().__repr__()] == self: return super().__repr__() else: return f"{str(self)} (origin={self.origins[super().__repr__()]})" class tracked_list(list): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.last_item = None def __iter__(self) -> Iterator: for x in super().__iter__(): self.last_item = x yield x self.last_item = None def __repr__(self) -> str: if self.last_item is None: return super().__repr__() else: return f"{self.__class__.__name__}(current={self.last_item})" class TrackedIterableFromGenerator(Iterable): """Utility class to create an iterable from a generator function, in order to reset the generator when needed.""" def __init__(self, generator, *args): super().__init__() self.generator = generator self.args = args self.last_item = None def __iter__(self): for x in self.generator(*self.args): self.last_item = x yield x self.last_item = None def __repr__(self) -> str: if self.last_item is None: return super().__repr__() else: return f"{self.__class__.__name__}(current={self.last_item})" def __reduce__(self): return (self.__class__, (self.generator, *self.args))
datasets/src/datasets/utils/track.py/0
{ "file_path": "datasets/src/datasets/utils/track.py", "repo_id": "datasets", "token_count": 824 }
108
import shutil import textwrap import numpy as np import pytest from datasets import ClassLabel, Features, Image from datasets.builder import InvalidConfigName from datasets.data_files import DataFilesDict, DataFilesList, get_data_patterns from datasets.download.streaming_download_manager import StreamingDownloadManager from datasets.packaged_modules.imagefolder.imagefolder import ImageFolder, ImageFolderConfig from ..utils import require_pil @pytest.fixture def cache_dir(tmp_path): return str(tmp_path / "imagefolder_cache_dir") @pytest.fixture def data_files_with_labels_no_metadata(tmp_path, image_file): data_dir = tmp_path / "data_files_with_labels_no_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "cat" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "dog" subdir_class_1.mkdir(parents=True, exist_ok=True) image_filename = subdir_class_0 / "image_cat.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = subdir_class_1 / "image_dog.jpg" shutil.copyfile(image_file, image_filename2) data_files_with_labels_no_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) return data_files_with_labels_no_metadata @pytest.fixture def image_files_with_labels_and_duplicated_label_key_in_metadata(tmp_path, image_file): data_dir = tmp_path / "image_files_with_labels_and_label_key_in_metadata" data_dir.mkdir(parents=True, exist_ok=True) subdir_class_0 = data_dir / "cat" subdir_class_0.mkdir(parents=True, exist_ok=True) subdir_class_1 = data_dir / "dog" subdir_class_1.mkdir(parents=True, exist_ok=True) image_filename = subdir_class_0 / "image_cat.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = subdir_class_1 / "image_dog.jpg" shutil.copyfile(image_file, image_filename2) image_metadata_filename = tmp_path / data_dir / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "cat/image_cat.jpg", "caption": "Nice image of a cat", "label": "Cat"} {"file_name": "dog/image_dog.jpg", "caption": "Nice image of a dog", "label": "Dog"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) return str(image_filename), str(image_filename2), str(image_metadata_filename) @pytest.fixture def image_file_with_metadata(tmp_path, image_file): image_filename = tmp_path / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_metadata_filename = tmp_path / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) return str(image_filename), str(image_metadata_filename) @pytest.fixture def image_files_with_metadata_that_misses_one_image(tmp_path, image_file): image_filename = tmp_path / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = tmp_path / "image_rgb2.jpg" shutil.copyfile(image_file, image_filename2) image_metadata_filename = tmp_path / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) return str(image_filename), str(image_filename2), str(image_metadata_filename) @pytest.fixture(params=["jsonl", "csv"]) def data_files_with_one_split_and_metadata(request, tmp_path, image_file): data_dir = tmp_path / "imagefolder_data_dir_with_metadata_one_split" data_dir.mkdir(parents=True, exist_ok=True) subdir = data_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) image_filename = data_dir / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = data_dir / "image_rgb2.jpg" shutil.copyfile(image_file, image_filename2) image_filename3 = subdir / "image_rgb3.jpg" # in subdir shutil.copyfile(image_file, image_filename3) image_metadata_filename = data_dir / f"metadata.{request.param}" image_metadata = ( textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} {"file_name": "image_rgb2.jpg", "caption": "Nice second image"} {"file_name": "subdir/image_rgb3.jpg", "caption": "Nice third image"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,caption image_rgb.jpg,Nice image image_rgb2.jpg,Nice second image subdir/image_rgb3.jpg,Nice third image """ ) ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_one_split_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_one_split_and_metadata) == 1 assert len(data_files_with_one_split_and_metadata["train"]) == 4 return data_files_with_one_split_and_metadata @pytest.fixture(params=["jsonl", "csv"]) def data_files_with_two_splits_and_metadata(request, tmp_path, image_file): data_dir = tmp_path / "imagefolder_data_dir_with_metadata_two_splits" data_dir.mkdir(parents=True, exist_ok=True) train_dir = data_dir / "train" train_dir.mkdir(parents=True, exist_ok=True) test_dir = data_dir / "test" test_dir.mkdir(parents=True, exist_ok=True) image_filename = train_dir / "image_rgb.jpg" # train image shutil.copyfile(image_file, image_filename) image_filename2 = train_dir / "image_rgb2.jpg" # train image shutil.copyfile(image_file, image_filename2) image_filename3 = test_dir / "image_rgb3.jpg" # test image shutil.copyfile(image_file, image_filename3) train_image_metadata_filename = train_dir / f"metadata.{request.param}" image_metadata = ( textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice train image"} {"file_name": "image_rgb2.jpg", "caption": "Nice second train image"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,caption image_rgb.jpg,Nice train image image_rgb2.jpg,Nice second train image """ ) ) with open(train_image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) test_image_metadata_filename = test_dir / f"metadata.{request.param}" image_metadata = ( textwrap.dedent( """\ {"file_name": "image_rgb3.jpg", "caption": "Nice test image"} """ ) if request.param == "jsonl" else textwrap.dedent( """\ file_name,caption image_rgb3.jpg,Nice test image """ ) ) with open(test_image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_two_splits_and_metadata = DataFilesDict.from_patterns( get_data_patterns(str(data_dir)), data_dir.as_posix() ) assert len(data_files_with_two_splits_and_metadata) == 2 assert len(data_files_with_two_splits_and_metadata["train"]) == 3 assert len(data_files_with_two_splits_and_metadata["test"]) == 2 return data_files_with_two_splits_and_metadata @pytest.fixture def data_files_with_zip_archives(tmp_path, image_file): from PIL import Image, ImageOps data_dir = tmp_path / "imagefolder_data_dir_with_zip_archives" data_dir.mkdir(parents=True, exist_ok=True) archive_dir = data_dir / "archive" archive_dir.mkdir(parents=True, exist_ok=True) subdir = archive_dir / "subdir" subdir.mkdir(parents=True, exist_ok=True) image_filename = archive_dir / "image_rgb.jpg" shutil.copyfile(image_file, image_filename) image_filename2 = subdir / "image_rgb2.jpg" # in subdir # make sure they're two different images # Indeed we won't be able to compare the image.filename, since the archive is not extracted in streaming mode ImageOps.flip(Image.open(image_file)).save(image_filename2) image_metadata_filename = archive_dir / "metadata.jsonl" image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} {"file_name": "subdir/image_rgb2.jpg", "caption": "Nice second image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) shutil.make_archive(archive_dir, "zip", archive_dir) shutil.rmtree(str(archive_dir)) data_files_with_zip_archives = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) assert len(data_files_with_zip_archives) == 1 assert len(data_files_with_zip_archives["train"]) == 1 return data_files_with_zip_archives def test_config_raises_when_invalid_name() -> None: with pytest.raises(InvalidConfigName, match="Bad characters"): _ = ImageFolderConfig(name="name-with-*-invalid-character") @pytest.mark.parametrize("data_files", ["str_path", ["str_path"], DataFilesList(["str_path"], [()])]) def test_config_raises_when_invalid_data_files(data_files) -> None: with pytest.raises(ValueError, match="Expected a DataFilesDict"): _ = ImageFolderConfig(name="name", data_files=data_files) @require_pil # check that labels are inferred correctly from dir names def test_generate_examples_with_labels(data_files_with_labels_no_metadata, cache_dir): # there are no metadata.jsonl files in this test case imagefolder = ImageFolder(data_files=data_files_with_labels_no_metadata, cache_dir=cache_dir, drop_labels=False) imagefolder.download_and_prepare() assert imagefolder.info.features == Features({"image": Image(), "label": ClassLabel(names=["cat", "dog"])}) dataset = list(imagefolder.as_dataset()["train"]) label_feature = imagefolder.info.features["label"] assert dataset[0]["label"] == label_feature._str2int["cat"] assert dataset[1]["label"] == label_feature._str2int["dog"] @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_labels(data_files_with_labels_no_metadata, drop_metadata, drop_labels): imagefolder = ImageFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files=data_files_with_labels_no_metadata ) gen_kwargs = imagefolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # removing the labels explicitly requires drop_labels=True assert gen_kwargs["add_labels"] is not bool(drop_labels) assert gen_kwargs["add_metadata"] is False generator = imagefolder._generate_examples(**gen_kwargs) if not drop_labels: assert all( example.keys() == {"image", "label"} and all(val is not None for val in example.values()) for _, example in generator ) else: assert all( example.keys() == {"image"} and all(val is not None for val in example.values()) for _, example in generator ) @require_pil @pytest.mark.parametrize("drop_metadata", [None, True, False]) @pytest.mark.parametrize("drop_labels", [None, True, False]) def test_generate_examples_drop_metadata(image_file_with_metadata, drop_metadata, drop_labels): image_file, image_metadata_file = image_file_with_metadata imagefolder = ImageFolder( drop_metadata=drop_metadata, drop_labels=drop_labels, data_files={"train": [image_file, image_metadata_file]} ) gen_kwargs = imagefolder._split_generators(StreamingDownloadManager())[0].gen_kwargs # since the dataset has metadata, removing the metadata explicitly requires drop_metadata=True assert gen_kwargs["add_metadata"] is not bool(drop_metadata) # since the dataset has metadata, adding the labels explicitly requires drop_labels=False assert gen_kwargs["add_labels"] is False generator = imagefolder._generate_examples(**gen_kwargs) expected_columns = {"image"} if gen_kwargs["add_metadata"]: expected_columns.add("caption") if gen_kwargs["add_labels"]: expected_columns.add("label") result = [example for _, example in generator] assert len(result) == 1 example = result[0] assert example.keys() == expected_columns for column in expected_columns: assert example[column] is not None @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_single_split(streaming, cache_dir, data_files_with_one_split_and_metadata): data_files = data_files_with_one_split_and_metadata imagefolder = ImageFolder(data_files=data_files, cache_dir=cache_dir) imagefolder.download_and_prepare() datasets = imagefolder.as_streaming_dataset() if streaming else imagefolder.as_dataset() for split, data_files in data_files.items(): expected_num_of_images = len(data_files) - 1 # don't count the metadata file assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_images # make sure each sample has its own image and metadata assert len({example["image"].filename for example in dataset}) == expected_num_of_images assert len({example["caption"] for example in dataset}) == expected_num_of_images assert all(example["caption"] is not None for example in dataset) @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_multiple_splits(streaming, cache_dir, data_files_with_two_splits_and_metadata): data_files = data_files_with_two_splits_and_metadata imagefolder = ImageFolder(data_files=data_files, cache_dir=cache_dir) imagefolder.download_and_prepare() datasets = imagefolder.as_streaming_dataset() if streaming else imagefolder.as_dataset() for split, data_files in data_files.items(): expected_num_of_images = len(data_files) - 1 # don't count the metadata file assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_images # make sure each sample has its own image and metadata assert len({example["image"].filename for example in dataset}) == expected_num_of_images assert len({example["caption"] for example in dataset}) == expected_num_of_images assert all(example["caption"] is not None for example in dataset) @require_pil @pytest.mark.parametrize("streaming", [False, True]) def test_data_files_with_metadata_and_archives(streaming, cache_dir, data_files_with_zip_archives): imagefolder = ImageFolder(data_files=data_files_with_zip_archives, cache_dir=cache_dir) imagefolder.download_and_prepare() datasets = imagefolder.as_streaming_dataset() if streaming else imagefolder.as_dataset() for split, data_files in data_files_with_zip_archives.items(): num_of_archives = len(data_files) # the metadata file is inside the archive expected_num_of_images = 2 * num_of_archives assert split in datasets dataset = list(datasets[split]) assert len(dataset) == expected_num_of_images # make sure each sample has its own image and metadata assert len({np.array(example["image"])[0, 0, 0] for example in dataset}) == expected_num_of_images assert len({example["caption"] for example in dataset}) == expected_num_of_images assert all(example["caption"] is not None for example in dataset) @require_pil def test_data_files_with_wrong_metadata_file_name(cache_dir, tmp_path, image_file): data_dir = tmp_path / "data_dir_with_bad_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(image_file, data_dir / "image_rgb.jpg") image_metadata_filename = data_dir / "bad_metadata.jsonl" # bad file image_metadata = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) imagefolder = ImageFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) imagefolder.download_and_prepare() dataset = imagefolder.as_dataset(split="train") # check that there are no metadata, since the metadata file name doesn't have the right name assert "caption" not in dataset.column_names @require_pil def test_data_files_with_custom_image_file_name_column_in_metadata_file(cache_dir, tmp_path, image_file): data_dir = tmp_path / "data_dir_with_custom_file_name_metadata" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(image_file, data_dir / "image_rgb.jpg") image_metadata_filename = data_dir / "metadata.jsonl" image_metadata = textwrap.dedent( # with bad column "bad_file_name" instead of "file_name" """\ {"picture_file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename, "w", encoding="utf-8") as f: f.write(image_metadata) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) imagefolder = ImageFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) imagefolder.download_and_prepare() dataset = imagefolder.as_dataset(split="train") assert "picture" in dataset.features assert "picture_file_name" not in dataset.features @require_pil def test_data_files_with_with_metadata_in_different_formats(cache_dir, tmp_path, image_file): data_dir = tmp_path / "data_dir_with_metadata_in_different_format" data_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(image_file, data_dir / "image_rgb.jpg") image_metadata_filename_jsonl = data_dir / "metadata.jsonl" image_metadata_jsonl = textwrap.dedent( """\ {"file_name": "image_rgb.jpg", "caption": "Nice image"} """ ) with open(image_metadata_filename_jsonl, "w", encoding="utf-8") as f: f.write(image_metadata_jsonl) image_metadata_filename_csv = data_dir / "metadata.csv" image_metadata_csv = textwrap.dedent( """\ file_name,caption image_rgb.jpg,Nice image """ ) with open(image_metadata_filename_csv, "w", encoding="utf-8") as f: f.write(image_metadata_csv) data_files_with_bad_metadata = DataFilesDict.from_patterns(get_data_patterns(str(data_dir)), data_dir.as_posix()) imagefolder = ImageFolder(data_files=data_files_with_bad_metadata, cache_dir=cache_dir) with pytest.raises(ValueError) as exc_info: imagefolder.download_and_prepare() assert "metadata files with different extensions" in str(exc_info.value)
datasets/tests/packaged_modules/test_imagefolder.py/0
{ "file_path": "datasets/tests/packaged_modules/test_imagefolder.py", "repo_id": "datasets", "token_count": 7486 }
109
import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.download.streaming_download_manager import StreamingDownloadManager from datasets.utils.file_utils import hash_url_to_filename, xopen from datasets.utils.py_utils import NestedDataStructure URL = "tmp://file1.txt" CONTENT = '"text": ["foo", "foo"]' HASH = "ce0516943c3a4f9af269cf40fa658d615fa0f00d2dd9ef3f0ac5a3b35be0b719" class MockResponse: status_code = 200 headers = {"Content-Length": "100"} cookies = {} def iter_content(self, **kwargs): return [bytes(CONTENT, "utf-8")] def mock_request(*args, **kwargs): return MockResponse() @pytest.mark.parametrize("urls_type", ["str", "list", "dict", "dict_of_dict"]) def test_download_manager_download(urls_type, tmp_path, tmpfs): url = URL with tmpfs.open(url, "w") as f: f.write(CONTENT) urls_types = {"str": url, "list": [url], "dict": {"train": url}, "dict_of_dict": {"train": {"en": url}}} urls = urls_types[urls_type] dataset_name = "dummy" cache_subdir = "downloads" cache_dir_root = tmp_path download_config = DownloadConfig( cache_dir=os.path.join(cache_dir_root, cache_subdir), use_etag=False, ) dl_manager = DownloadManager(dataset_name=dataset_name, download_config=download_config) downloaded_paths = dl_manager.download(urls) assert isinstance(downloaded_paths, type(urls)) if "urls_type".startswith("list"): assert len(downloaded_paths) == len(urls) elif "urls_type".startswith("dict"): assert downloaded_paths.keys() == urls.keys() if "urls_type" == "dict_of_dict": key = list(urls.keys())[0] assert isinstance(downloaded_paths[key], dict) assert downloaded_paths[key].keys() == urls[key].keys() for downloaded_path, url in zip( NestedDataStructure(downloaded_paths).flatten(), NestedDataStructure(urls).flatten() ): downloaded_path = Path(downloaded_path) parts = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() content = downloaded_path.read_text() assert content == CONTENT metadata_downloaded_path = downloaded_path.with_suffix(".json") assert metadata_downloaded_path.exists() metadata_content = json.loads(metadata_downloaded_path.read_text()) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize("paths_type", [str, list, dict]) @pytest.mark.parametrize("extract_on_the_fly", [False, True]) def test_download_manager_extract(paths_type, xz_file, text_file, extract_on_the_fly): filename = str(xz_file) if issubclass(paths_type, str): paths = filename elif issubclass(paths_type, list): paths = [filename] elif issubclass(paths_type, dict): paths = {"train": filename} dataset_name = "dummy" cache_dir = xz_file.parent extracted_subdir = "extracted" download_config = DownloadConfig( cache_dir=cache_dir, use_etag=False, extract_on_the_fly=extract_on_the_fly, ) dl_manager = DownloadManager(dataset_name=dataset_name, download_config=download_config) extracted_paths = dl_manager.extract(paths) input_paths = paths for extracted_paths in [extracted_paths]: if isinstance(paths, str): extracted_paths = [extracted_paths] input_paths = [paths] elif isinstance(paths, dict): assert "train" in extracted_paths.keys() extracted_paths = extracted_paths.values() input_paths = paths.values() assert extracted_paths for extracted_path, input_path in zip(extracted_paths, input_paths): assert extracted_path == dl_manager.extracted_paths[input_path] if not extract_on_the_fly: extracted_path = Path(extracted_path) parts = extracted_path.parts assert parts[-1] == hash_url_to_filename(input_path, etag=None) assert parts[-2] == extracted_subdir assert extracted_path.exists() extracted_file_content = extracted_path.read_text() expected_file_content = text_file.read_text() assert extracted_file_content == expected_file_content else: assert extracted_path == StreamingDownloadManager( dataset_name=dataset_name, download_config=download_config ).extract(xz_file) assert xopen(extracted_path).read() == text_file.read_text() def test_download_manager_delete_extracted_files(xz_file): dataset_name = "dummy" cache_dir = xz_file.parent extracted_subdir = "extracted" download_config = DownloadConfig( cache_dir=cache_dir, use_etag=False, ) dl_manager = DownloadManager(dataset_name=dataset_name, download_config=download_config) extracted_path = dl_manager.extract(xz_file) assert extracted_path == dl_manager.extracted_paths[xz_file] extracted_path = Path(extracted_path) parts = extracted_path.parts # import pdb; pdb.set_trace() assert parts[-1] == hash_url_to_filename(str(xz_file), etag=None) assert parts[-2] == extracted_subdir assert extracted_path.exists() dl_manager.delete_extracted_files() assert not extracted_path.exists() def _test_jsonl(path, file): assert path.endswith(".jsonl") for num_items, line in enumerate(file, start=1): item = json.loads(line.decode("utf-8")) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("archive_jsonl", ["tar_jsonl_path", "zip_jsonl_path"]) def test_iter_archive_path(archive_jsonl, request): archive_jsonl_path = request.getfixturevalue(archive_jsonl) dl_manager = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(archive_jsonl_path), start=1): _test_jsonl(path, file) assert num_jsonl == 2 @pytest.mark.parametrize("archive_nested_jsonl", ["tar_nested_jsonl_path", "zip_nested_jsonl_path"]) def test_iter_archive_file(archive_nested_jsonl, request): archive_nested_jsonl_path = request.getfixturevalue(archive_nested_jsonl) dl_manager = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(archive_nested_jsonl_path), start=1): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(file), start=1): _test_jsonl(subpath, subfile) assert num_tar == 1 assert num_jsonl == 2 def test_iter_files(data_dir_with_hidden_files): dl_manager = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(data_dir_with_hidden_files), start=1): assert os.path.basename(file) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
datasets/tests/test_download_manager.py/0
{ "file_path": "datasets/tests/test_download_manager.py", "repo_id": "datasets", "token_count": 2945 }
110
from tempfile import NamedTemporaryFile import pytest import requests from datasets.utils.file_utils import fsspec_get, fsspec_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline, require_not_windows @pytest.mark.integration @require_not_windows # fsspec get keeps a file handle on windows that raises PermissionError def test_offline_with_timeout(): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT): with pytest.raises(RequestWouldHangIndefinitelyError): requests.request("GET", "https://huggingface.co") with pytest.raises(requests.exceptions.Timeout): requests.request("GET", "https://huggingface.co", timeout=1.0) with pytest.raises(requests.exceptions.Timeout), NamedTemporaryFile() as temp_file: fsspec_get("hf://dummy", temp_file=temp_file) @pytest.mark.integration @require_not_windows # fsspec get keeps a file handle on windows that raises PermissionError def test_offline_with_connection_error(): with offline(OfflineSimulationMode.CONNECTION_FAILS): with pytest.raises(requests.exceptions.ConnectionError): requests.request("GET", "https://huggingface.co") with pytest.raises(requests.exceptions.ConnectionError), NamedTemporaryFile() as temp_file: fsspec_get("hf://dummy", temp_file=temp_file) def test_offline_with_datasets_offline_mode_enabled(): with offline(OfflineSimulationMode.HF_HUB_OFFLINE_SET_TO_1): with pytest.raises(ConnectionError): fsspec_head("hf://dummy") with pytest.raises(ConnectionError), NamedTemporaryFile() as temp_file: fsspec_get("hf://dummy", temp_file=temp_file)
datasets/tests/test_offline_util.py/0
{ "file_path": "datasets/tests/test_offline_util.py", "repo_id": "datasets", "token_count": 641 }
111
cff-version: 1.2.0 title: 'Diffusers: State-of-the-art diffusion models' message: >- If you use this software, please cite it using the metadata from this file. type: software authors: - given-names: Patrick family-names: von Platen - given-names: Suraj family-names: Patil - given-names: Anton family-names: Lozhkov - given-names: Pedro family-names: Cuenca - given-names: Nathan family-names: Lambert - given-names: Kashif family-names: Rasul - given-names: Mishig family-names: Davaadorj - given-names: Dhruv family-names: Nair - given-names: Sayak family-names: Paul - given-names: Steven family-names: Liu - given-names: William family-names: Berman - given-names: Yiyi family-names: Xu - given-names: Thomas family-names: Wolf repository-code: 'https://github.com/huggingface/diffusers' abstract: >- Diffusers provides pretrained diffusion models across multiple modalities, such as vision and audio, and serves as a modular toolbox for inference and training of diffusion models. keywords: - deep-learning - pytorch - image-generation - hacktoberfest - diffusion - text2image - image2image - score-based-generative-modeling - stable-diffusion - stable-diffusion-diffusers license: Apache-2.0 version: 0.12.1
diffusers/CITATION.cff/0
{ "file_path": "diffusers/CITATION.cff", "repo_id": "diffusers", "token_count": 460 }
112
import argparse import os import sys import gpustat import pandas as pd import psycopg2 import psycopg2.extras from psycopg2.extensions import register_adapter from psycopg2.extras import Json register_adapter(dict, Json) FINAL_CSV_FILENAME = "collated_results.csv" # https://github.com/huggingface/transformers/blob/593e29c5e2a9b17baec010e8dc7c1431fed6e841/benchmark/init_db.sql#L27 BENCHMARKS_TABLE_NAME = "benchmarks" MEASUREMENTS_TABLE_NAME = "model_measurements" def _init_benchmark(conn, branch, commit_id, commit_msg): gpu_stats = gpustat.GPUStatCollection.new_query() metadata = {"gpu_name": gpu_stats[0]["name"]} repository = "huggingface/diffusers" with conn.cursor() as cur: cur.execute( f"INSERT INTO {BENCHMARKS_TABLE_NAME} (repository, branch, commit_id, commit_message, metadata) VALUES (%s, %s, %s, %s, %s) RETURNING benchmark_id", (repository, branch, commit_id, commit_msg, metadata), ) benchmark_id = cur.fetchone()[0] print(f"Initialised benchmark #{benchmark_id}") return benchmark_id def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "branch", type=str, help="The branch name on which the benchmarking is performed.", ) parser.add_argument( "commit_id", type=str, help="The commit hash on which the benchmarking is performed.", ) parser.add_argument( "commit_msg", type=str, help="The commit message associated with the commit, truncated to 70 characters.", ) args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() try: conn = psycopg2.connect( host=os.getenv("PGHOST"), database=os.getenv("PGDATABASE"), user=os.getenv("PGUSER"), password=os.getenv("PGPASSWORD"), ) print("DB connection established successfully.") except Exception as e: print(f"Problem during DB init: {e}") sys.exit(1) try: benchmark_id = _init_benchmark( conn=conn, branch=args.branch, commit_id=args.commit_id, commit_msg=args.commit_msg, ) except Exception as e: print(f"Problem during initializing benchmark: {e}") sys.exit(1) cur = conn.cursor() df = pd.read_csv(FINAL_CSV_FILENAME) # Helper to cast values (or None) given a dtype def _cast_value(val, dtype: str): if pd.isna(val): return None if dtype == "text": return str(val).strip() if dtype == "float": try: return float(val) except ValueError: return None if dtype == "bool": s = str(val).strip().lower() if s in ("true", "t", "yes", "1"): return True if s in ("false", "f", "no", "0"): return False if val in (1, 1.0): return True if val in (0, 0.0): return False return None return val try: rows_to_insert = [] for _, row in df.iterrows(): scenario = _cast_value(row.get("scenario"), "text") model_cls = _cast_value(row.get("model_cls"), "text") num_params_B = _cast_value(row.get("num_params_B"), "float") flops_G = _cast_value(row.get("flops_G"), "float") time_plain_s = _cast_value(row.get("time_plain_s"), "float") mem_plain_GB = _cast_value(row.get("mem_plain_GB"), "float") time_compile_s = _cast_value(row.get("time_compile_s"), "float") mem_compile_GB = _cast_value(row.get("mem_compile_GB"), "float") fullgraph = _cast_value(row.get("fullgraph"), "bool") mode = _cast_value(row.get("mode"), "text") # If "github_sha" column exists in the CSV, cast it; else default to None if "github_sha" in df.columns: github_sha = _cast_value(row.get("github_sha"), "text") else: github_sha = None measurements = { "scenario": scenario, "model_cls": model_cls, "num_params_B": num_params_B, "flops_G": flops_G, "time_plain_s": time_plain_s, "mem_plain_GB": mem_plain_GB, "time_compile_s": time_compile_s, "mem_compile_GB": mem_compile_GB, "fullgraph": fullgraph, "mode": mode, "github_sha": github_sha, } rows_to_insert.append((benchmark_id, measurements)) # Batch-insert all rows insert_sql = f""" INSERT INTO {MEASUREMENTS_TABLE_NAME} ( benchmark_id, measurements ) VALUES (%s, %s); """ psycopg2.extras.execute_batch(cur, insert_sql, rows_to_insert) conn.commit() cur.close() conn.close() except Exception as e: print(f"Exception: {e}") sys.exit(1)
diffusers/benchmarks/populate_into_db.py/0
{ "file_path": "diffusers/benchmarks/populate_into_db.py", "repo_id": "diffusers", "token_count": 2569 }
113
- title: Get started sections: - local: index title: Diffusers - local: installation title: Installation - local: quicktour title: Quickstart - local: stable_diffusion title: Basic performance - title: DiffusionPipeline isExpanded: false sections: - local: using-diffusers/loading title: Load pipelines - local: tutorials/autopipeline title: AutoPipeline - local: using-diffusers/custom_pipeline_overview title: Community pipelines and components - local: using-diffusers/callback title: Pipeline callbacks - local: using-diffusers/reusing_seeds title: Reproducible pipelines - local: using-diffusers/schedulers title: Load schedulers and models - local: using-diffusers/scheduler_features title: Scheduler features - local: using-diffusers/other-formats title: Model files and layouts - local: using-diffusers/push_to_hub title: Push files to the Hub - title: Adapters isExpanded: false sections: - local: tutorials/using_peft_for_inference title: LoRA - local: using-diffusers/ip_adapter title: IP-Adapter - local: using-diffusers/controlnet title: ControlNet - local: using-diffusers/t2i_adapter title: T2I-Adapter - local: using-diffusers/dreambooth title: DreamBooth - local: using-diffusers/textual_inversion_inference title: Textual inversion - title: Inference isExpanded: false sections: - local: using-diffusers/weighted_prompts title: Prompt techniques - local: using-diffusers/create_a_server title: Create a server - local: using-diffusers/batched_inference title: Batch inference - local: training/distributed_inference title: Distributed inference - local: using-diffusers/scheduler_features title: Scheduler features - local: using-diffusers/callback title: Pipeline callbacks - local: using-diffusers/reusing_seeds title: Reproducible pipelines - local: using-diffusers/image_quality title: Controlling image quality - title: Inference optimization isExpanded: false sections: - local: optimization/fp16 title: Accelerate inference - local: optimization/cache title: Caching - local: optimization/memory title: Reduce memory usage - local: optimization/speed-memory-optims title: Compile and offloading quantized models - title: Community optimizations sections: - local: optimization/pruna title: Pruna - local: optimization/xformers title: xFormers - local: optimization/tome title: Token merging - local: optimization/deepcache title: DeepCache - local: optimization/tgate title: TGATE - local: optimization/xdit title: xDiT - local: optimization/para_attn title: ParaAttention - title: Hybrid Inference isExpanded: false sections: - local: hybrid_inference/overview title: Overview - local: hybrid_inference/vae_decode title: VAE Decode - local: hybrid_inference/vae_encode title: VAE Encode - local: hybrid_inference/api_reference title: API Reference - title: Modular Diffusers isExpanded: false sections: - local: modular_diffusers/overview title: Overview - local: modular_diffusers/quickstart title: Quickstart - local: modular_diffusers/modular_diffusers_states title: States - local: modular_diffusers/pipeline_block title: ModularPipelineBlocks - local: modular_diffusers/sequential_pipeline_blocks title: SequentialPipelineBlocks - local: modular_diffusers/loop_sequential_pipeline_blocks title: LoopSequentialPipelineBlocks - local: modular_diffusers/auto_pipeline_blocks title: AutoPipelineBlocks - local: modular_diffusers/modular_pipeline title: ModularPipeline - local: modular_diffusers/components_manager title: ComponentsManager - local: modular_diffusers/guiders title: Guiders - title: Training isExpanded: false sections: - local: training/overview title: Overview - local: training/create_dataset title: Create a dataset for training - local: training/adapt_a_model title: Adapt a model to a new task - local: tutorials/basic_training title: Train a diffusion model - title: Models sections: - local: training/unconditional_training title: Unconditional image generation - local: training/text2image title: Text-to-image - local: training/sdxl title: Stable Diffusion XL - local: training/kandinsky title: Kandinsky 2.2 - local: training/wuerstchen title: Wuerstchen - local: training/controlnet title: ControlNet - local: training/t2i_adapters title: T2I-Adapters - local: training/instructpix2pix title: InstructPix2Pix - local: training/cogvideox title: CogVideoX - title: Methods sections: - local: training/text_inversion title: Textual Inversion - local: training/dreambooth title: DreamBooth - local: training/lora title: LoRA - local: training/custom_diffusion title: Custom Diffusion - local: training/lcm_distill title: Latent Consistency Distillation - local: training/ddpo title: Reinforcement learning training with DDPO - title: Quantization isExpanded: false sections: - local: quantization/overview title: Getting started - local: quantization/bitsandbytes title: bitsandbytes - local: quantization/gguf title: gguf - local: quantization/torchao title: torchao - local: quantization/quanto title: quanto - title: Model accelerators and hardware isExpanded: false sections: - local: using-diffusers/stable_diffusion_jax_how_to title: JAX/Flax - local: optimization/onnx title: ONNX - local: optimization/open_vino title: OpenVINO - local: optimization/coreml title: Core ML - local: optimization/mps title: Metal Performance Shaders (MPS) - local: optimization/habana title: Intel Gaudi - local: optimization/neuron title: AWS Neuron - title: Specific pipeline examples isExpanded: false sections: - local: using-diffusers/consisid title: ConsisID - local: using-diffusers/sdxl title: Stable Diffusion XL - local: using-diffusers/sdxl_turbo title: SDXL Turbo - local: using-diffusers/kandinsky title: Kandinsky - local: using-diffusers/omnigen title: OmniGen - local: using-diffusers/pag title: PAG - local: using-diffusers/inference_with_lcm title: Latent Consistency Model - local: using-diffusers/shap-e title: Shap-E - local: using-diffusers/diffedit title: DiffEdit - local: using-diffusers/inference_with_tcd_lora title: Trajectory Consistency Distillation-LoRA - local: using-diffusers/svd title: Stable Video Diffusion - local: using-diffusers/marigold_usage title: Marigold Computer Vision - title: Resources isExpanded: false sections: - title: Task recipes sections: - local: using-diffusers/unconditional_image_generation title: Unconditional image generation - local: using-diffusers/conditional_image_generation title: Text-to-image - local: using-diffusers/img2img title: Image-to-image - local: using-diffusers/inpaint title: Inpainting - local: advanced_inference/outpaint title: Outpainting - local: using-diffusers/text-img2vid title: Video generation - local: using-diffusers/depth2img title: Depth-to-image - local: using-diffusers/write_own_pipeline title: Understanding pipelines, models and schedulers - local: community_projects title: Projects built with Diffusers - local: conceptual/philosophy title: Philosophy - local: using-diffusers/controlling_generation title: Controlled generation - local: conceptual/contribution title: How to contribute? - local: conceptual/ethical_guidelines title: Diffusers' Ethical Guidelines - local: conceptual/evaluation title: Evaluating Diffusion Models - title: API isExpanded: false sections: - title: Main Classes sections: - local: api/configuration title: Configuration - local: api/logging title: Logging - local: api/outputs title: Outputs - local: api/quantization title: Quantization - title: Modular sections: - local: api/modular_diffusers/pipeline title: Pipeline - local: api/modular_diffusers/pipeline_blocks title: Blocks - local: api/modular_diffusers/pipeline_states title: States - local: api/modular_diffusers/pipeline_components title: Components and configs - local: api/modular_diffusers/guiders title: Guiders - title: Loaders sections: - local: api/loaders/ip_adapter title: IP-Adapter - local: api/loaders/lora title: LoRA - local: api/loaders/single_file title: Single files - local: api/loaders/textual_inversion title: Textual Inversion - local: api/loaders/unet title: UNet - local: api/loaders/transformer_sd3 title: SD3Transformer2D - local: api/loaders/peft title: PEFT - title: Models sections: - local: api/models/overview title: Overview - local: api/models/auto_model title: AutoModel - title: ControlNets sections: - local: api/models/controlnet title: ControlNetModel - local: api/models/controlnet_union title: ControlNetUnionModel - local: api/models/controlnet_flux title: FluxControlNetModel - local: api/models/controlnet_hunyuandit title: HunyuanDiT2DControlNetModel - local: api/models/controlnet_sana title: SanaControlNetModel - local: api/models/controlnet_sd3 title: SD3ControlNetModel - local: api/models/controlnet_sparsectrl title: SparseControlNetModel - title: Transformers sections: - local: api/models/allegro_transformer3d title: AllegroTransformer3DModel - local: api/models/aura_flow_transformer2d title: AuraFlowTransformer2DModel - local: api/models/bria_transformer title: BriaTransformer2DModel - local: api/models/chroma_transformer title: ChromaTransformer2DModel - local: api/models/cogvideox_transformer3d title: CogVideoXTransformer3DModel - local: api/models/cogview3plus_transformer2d title: CogView3PlusTransformer2DModel - local: api/models/cogview4_transformer2d title: CogView4Transformer2DModel - local: api/models/consisid_transformer3d title: ConsisIDTransformer3DModel - local: api/models/cosmos_transformer3d title: CosmosTransformer3DModel - local: api/models/dit_transformer2d title: DiTTransformer2DModel - local: api/models/easyanimate_transformer3d title: EasyAnimateTransformer3DModel - local: api/models/flux_transformer title: FluxTransformer2DModel - local: api/models/hidream_image_transformer title: HiDreamImageTransformer2DModel - local: api/models/hunyuan_transformer2d title: HunyuanDiT2DModel - local: api/models/hunyuan_video_transformer_3d title: HunyuanVideoTransformer3DModel - local: api/models/latte_transformer3d title: LatteTransformer3DModel - local: api/models/ltx_video_transformer3d title: LTXVideoTransformer3DModel - local: api/models/lumina2_transformer2d title: Lumina2Transformer2DModel - local: api/models/lumina_nextdit2d title: LuminaNextDiT2DModel - local: api/models/mochi_transformer3d title: MochiTransformer3DModel - local: api/models/omnigen_transformer title: OmniGenTransformer2DModel - local: api/models/pixart_transformer2d title: PixArtTransformer2DModel - local: api/models/prior_transformer title: PriorTransformer - local: api/models/qwenimage_transformer2d title: QwenImageTransformer2DModel - local: api/models/sana_transformer2d title: SanaTransformer2DModel - local: api/models/sd3_transformer2d title: SD3Transformer2DModel - local: api/models/skyreels_v2_transformer_3d title: SkyReelsV2Transformer3DModel - local: api/models/stable_audio_transformer title: StableAudioDiTModel - local: api/models/transformer2d title: Transformer2DModel - local: api/models/transformer_temporal title: TransformerTemporalModel - local: api/models/wan_transformer_3d title: WanTransformer3DModel - title: UNets sections: - local: api/models/stable_cascade_unet title: StableCascadeUNet - local: api/models/unet title: UNet1DModel - local: api/models/unet2d-cond title: UNet2DConditionModel - local: api/models/unet2d title: UNet2DModel - local: api/models/unet3d-cond title: UNet3DConditionModel - local: api/models/unet-motion title: UNetMotionModel - local: api/models/uvit2d title: UViT2DModel - title: VAEs sections: - local: api/models/asymmetricautoencoderkl title: AsymmetricAutoencoderKL - local: api/models/autoencoder_dc title: AutoencoderDC - local: api/models/autoencoderkl title: AutoencoderKL - local: api/models/autoencoderkl_allegro title: AutoencoderKLAllegro - local: api/models/autoencoderkl_cogvideox title: AutoencoderKLCogVideoX - local: api/models/autoencoderkl_cosmos title: AutoencoderKLCosmos - local: api/models/autoencoder_kl_hunyuan_video title: AutoencoderKLHunyuanVideo - local: api/models/autoencoderkl_ltx_video title: AutoencoderKLLTXVideo - local: api/models/autoencoderkl_magvit title: AutoencoderKLMagvit - local: api/models/autoencoderkl_mochi title: AutoencoderKLMochi - local: api/models/autoencoderkl_qwenimage title: AutoencoderKLQwenImage - local: api/models/autoencoder_kl_wan title: AutoencoderKLWan - local: api/models/consistency_decoder_vae title: ConsistencyDecoderVAE - local: api/models/autoencoder_oobleck title: Oobleck AutoEncoder - local: api/models/autoencoder_tiny title: Tiny AutoEncoder - local: api/models/vq title: VQModel - title: Pipelines sections: - local: api/pipelines/overview title: Overview - local: api/pipelines/allegro title: Allegro - local: api/pipelines/amused title: aMUSEd - local: api/pipelines/animatediff title: AnimateDiff - local: api/pipelines/attend_and_excite title: Attend-and-Excite - local: api/pipelines/audioldm title: AudioLDM - local: api/pipelines/audioldm2 title: AudioLDM 2 - local: api/pipelines/aura_flow title: AuraFlow - local: api/pipelines/auto_pipeline title: AutoPipeline - local: api/pipelines/blip_diffusion title: BLIP-Diffusion - local: api/pipelines/bria_3_2 title: Bria 3.2 - local: api/pipelines/chroma title: Chroma - local: api/pipelines/cogvideox title: CogVideoX - local: api/pipelines/cogview3 title: CogView3 - local: api/pipelines/cogview4 title: CogView4 - local: api/pipelines/consisid title: ConsisID - local: api/pipelines/consistency_models title: Consistency Models - local: api/pipelines/controlnet title: ControlNet - local: api/pipelines/controlnet_flux title: ControlNet with Flux.1 - local: api/pipelines/controlnet_hunyuandit title: ControlNet with Hunyuan-DiT - local: api/pipelines/controlnet_sd3 title: ControlNet with Stable Diffusion 3 - local: api/pipelines/controlnet_sdxl title: ControlNet with Stable Diffusion XL - local: api/pipelines/controlnet_sana title: ControlNet-Sana - local: api/pipelines/controlnetxs title: ControlNet-XS - local: api/pipelines/controlnetxs_sdxl title: ControlNet-XS with Stable Diffusion XL - local: api/pipelines/controlnet_union title: ControlNetUnion - local: api/pipelines/cosmos title: Cosmos - local: api/pipelines/dance_diffusion title: Dance Diffusion - local: api/pipelines/ddim title: DDIM - local: api/pipelines/ddpm title: DDPM - local: api/pipelines/deepfloyd_if title: DeepFloyd IF - local: api/pipelines/diffedit title: DiffEdit - local: api/pipelines/dit title: DiT - local: api/pipelines/easyanimate title: EasyAnimate - local: api/pipelines/flux title: Flux - local: api/pipelines/control_flux_inpaint title: FluxControlInpaint - local: api/pipelines/framepack title: Framepack - local: api/pipelines/hidream title: HiDream-I1 - local: api/pipelines/hunyuandit title: Hunyuan-DiT - local: api/pipelines/hunyuan_video title: HunyuanVideo - local: api/pipelines/i2vgenxl title: I2VGen-XL - local: api/pipelines/pix2pix title: InstructPix2Pix - local: api/pipelines/kandinsky title: Kandinsky 2.1 - local: api/pipelines/kandinsky_v22 title: Kandinsky 2.2 - local: api/pipelines/kandinsky3 title: Kandinsky 3 - local: api/pipelines/kolors title: Kolors - local: api/pipelines/latent_consistency_models title: Latent Consistency Models - local: api/pipelines/latent_diffusion title: Latent Diffusion - local: api/pipelines/latte title: Latte - local: api/pipelines/ledits_pp title: LEDITS++ - local: api/pipelines/ltx_video title: LTXVideo - local: api/pipelines/lumina2 title: Lumina 2.0 - local: api/pipelines/lumina title: Lumina-T2X - local: api/pipelines/marigold title: Marigold - local: api/pipelines/mochi title: Mochi - local: api/pipelines/panorama title: MultiDiffusion - local: api/pipelines/musicldm title: MusicLDM - local: api/pipelines/omnigen title: OmniGen - local: api/pipelines/pag title: PAG - local: api/pipelines/paint_by_example title: Paint by Example - local: api/pipelines/pia title: Personalized Image Animator (PIA) - local: api/pipelines/pixart title: PixArt-α - local: api/pipelines/pixart_sigma title: PixArt-Σ - local: api/pipelines/qwenimage title: QwenImage - local: api/pipelines/sana title: Sana - local: api/pipelines/sana_sprint title: Sana Sprint - local: api/pipelines/self_attention_guidance title: Self-Attention Guidance - local: api/pipelines/semantic_stable_diffusion title: Semantic Guidance - local: api/pipelines/shap_e title: Shap-E - local: api/pipelines/skyreels_v2 title: SkyReels-V2 - local: api/pipelines/stable_audio title: Stable Audio - local: api/pipelines/stable_cascade title: Stable Cascade - title: Stable Diffusion sections: - local: api/pipelines/stable_diffusion/overview title: Overview - local: api/pipelines/stable_diffusion/depth2img title: Depth-to-image - local: api/pipelines/stable_diffusion/gligen title: GLIGEN (Grounded Language-to-Image Generation) - local: api/pipelines/stable_diffusion/image_variation title: Image variation - local: api/pipelines/stable_diffusion/img2img title: Image-to-image - local: api/pipelines/stable_diffusion/svd title: Image-to-video - local: api/pipelines/stable_diffusion/inpaint title: Inpainting - local: api/pipelines/stable_diffusion/k_diffusion title: K-Diffusion - local: api/pipelines/stable_diffusion/latent_upscale title: Latent upscaler - local: api/pipelines/stable_diffusion/ldm3d_diffusion title: LDM3D Text-to-(RGB, Depth), Text-to-(RGB-pano, Depth-pano), LDM3D Upscaler - local: api/pipelines/stable_diffusion/stable_diffusion_safe title: Safe Stable Diffusion - local: api/pipelines/stable_diffusion/sdxl_turbo title: SDXL Turbo - local: api/pipelines/stable_diffusion/stable_diffusion_2 title: Stable Diffusion 2 - local: api/pipelines/stable_diffusion/stable_diffusion_3 title: Stable Diffusion 3 - local: api/pipelines/stable_diffusion/stable_diffusion_xl title: Stable Diffusion XL - local: api/pipelines/stable_diffusion/upscale title: Super-resolution - local: api/pipelines/stable_diffusion/adapter title: T2I-Adapter - local: api/pipelines/stable_diffusion/text2img title: Text-to-image - local: api/pipelines/stable_unclip title: Stable unCLIP - local: api/pipelines/text_to_video title: Text-to-video - local: api/pipelines/text_to_video_zero title: Text2Video-Zero - local: api/pipelines/unclip title: unCLIP - local: api/pipelines/unidiffuser title: UniDiffuser - local: api/pipelines/value_guided_sampling title: Value-guided sampling - local: api/pipelines/visualcloze title: VisualCloze - local: api/pipelines/wan title: Wan - local: api/pipelines/wuerstchen title: Wuerstchen - title: Schedulers sections: - local: api/schedulers/overview title: Overview - local: api/schedulers/cm_stochastic_iterative title: CMStochasticIterativeScheduler - local: api/schedulers/ddim_cogvideox title: CogVideoXDDIMScheduler - local: api/schedulers/multistep_dpm_solver_cogvideox title: CogVideoXDPMScheduler - local: api/schedulers/consistency_decoder title: ConsistencyDecoderScheduler - local: api/schedulers/cosine_dpm title: CosineDPMSolverMultistepScheduler - local: api/schedulers/ddim_inverse title: DDIMInverseScheduler - local: api/schedulers/ddim title: DDIMScheduler - local: api/schedulers/ddpm title: DDPMScheduler - local: api/schedulers/deis title: DEISMultistepScheduler - local: api/schedulers/multistep_dpm_solver_inverse title: DPMSolverMultistepInverse - local: api/schedulers/multistep_dpm_solver title: DPMSolverMultistepScheduler - local: api/schedulers/dpm_sde title: DPMSolverSDEScheduler - local: api/schedulers/singlestep_dpm_solver title: DPMSolverSinglestepScheduler - local: api/schedulers/edm_multistep_dpm_solver title: EDMDPMSolverMultistepScheduler - local: api/schedulers/edm_euler title: EDMEulerScheduler - local: api/schedulers/euler_ancestral title: EulerAncestralDiscreteScheduler - local: api/schedulers/euler title: EulerDiscreteScheduler - local: api/schedulers/flow_match_euler_discrete title: FlowMatchEulerDiscreteScheduler - local: api/schedulers/flow_match_heun_discrete title: FlowMatchHeunDiscreteScheduler - local: api/schedulers/heun title: HeunDiscreteScheduler - local: api/schedulers/ipndm title: IPNDMScheduler - local: api/schedulers/stochastic_karras_ve title: KarrasVeScheduler - local: api/schedulers/dpm_discrete_ancestral title: KDPM2AncestralDiscreteScheduler - local: api/schedulers/dpm_discrete title: KDPM2DiscreteScheduler - local: api/schedulers/lcm title: LCMScheduler - local: api/schedulers/lms_discrete title: LMSDiscreteScheduler - local: api/schedulers/pndm title: PNDMScheduler - local: api/schedulers/repaint title: RePaintScheduler - local: api/schedulers/score_sde_ve title: ScoreSdeVeScheduler - local: api/schedulers/score_sde_vp title: ScoreSdeVpScheduler - local: api/schedulers/tcd title: TCDScheduler - local: api/schedulers/unipc title: UniPCMultistepScheduler - local: api/schedulers/vq_diffusion title: VQDiffusionScheduler - title: Internal classes sections: - local: api/internal_classes_overview title: Overview - local: api/attnprocessor title: Attention Processor - local: api/activations title: Custom activation functions - local: api/cache title: Caching methods - local: api/normalization title: Custom normalization layers - local: api/utilities title: Utilities - local: api/image_processor title: VAE Image Processor - local: api/video_processor title: Video Processor
diffusers/docs/source/en/_toctree.yml/0
{ "file_path": "diffusers/docs/source/en/_toctree.yml", "repo_id": "diffusers", "token_count": 10125 }
114
<!-- Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # AutoencoderKLQwenImage The model can be loaded with the following code snippet. ```python from diffusers import AutoencoderKLQwenImage vae = AutoencoderKLQwenImage.from_pretrained("Qwen/QwenImage-20B", subfolder="vae") ``` ## AutoencoderKLQwenImage [[autodoc]] AutoencoderKLQwenImage - decode - encode - all ## AutoencoderKLOutput [[autodoc]] models.autoencoders.autoencoder_kl.AutoencoderKLOutput ## DecoderOutput [[autodoc]] models.autoencoders.vae.DecoderOutput
diffusers/docs/source/en/api/models/autoencoderkl_qwenimage.md/0
{ "file_path": "diffusers/docs/source/en/api/models/autoencoderkl_qwenimage.md", "repo_id": "diffusers", "token_count": 329 }
115
# Pipeline ## ModularPipeline [[autodoc]] diffusers.modular_pipelines.modular_pipeline.ModularPipeline
diffusers/docs/source/en/api/modular_diffusers/pipeline.md/0
{ "file_path": "diffusers/docs/source/en/api/modular_diffusers/pipeline.md", "repo_id": "diffusers", "token_count": 40 }
116
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Chroma <div class="flex flex-wrap space-x-1"> <img alt="LoRA" src="https://img.shields.io/badge/LoRA-d8b4fe?style=flat"/> <img alt="MPS" src="https://img.shields.io/badge/MPS-000000?style=flat&logo=apple&logoColor=white%22"> </div> Chroma is a text to image generation model based on Flux. Original model checkpoints for Chroma can be found [here](https://huggingface.co/lodestones/Chroma). <Tip> Chroma can use all the same optimizations as Flux. </Tip> ## Inference The Diffusers version of Chroma is based on the [`unlocked-v37`](https://huggingface.co/lodestones/Chroma/blob/main/chroma-unlocked-v37.safetensors) version of the original model, which is available in the [Chroma repository](https://huggingface.co/lodestones/Chroma). ```python import torch from diffusers import ChromaPipeline pipe = ChromaPipeline.from_pretrained("lodestones/Chroma", torch_dtype=torch.bfloat16) pipe.enable_model_cpu_offload() prompt = [ "A high-fashion close-up portrait of a blonde woman in clear sunglasses. The image uses a bold teal and red color split for dramatic lighting. The background is a simple teal-green. The photo is sharp and well-composed, and is designed for viewing with anaglyph 3D glasses for optimal effect. It looks professionally done." ] negative_prompt = ["low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors"] image = pipe( prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator("cpu").manual_seed(433), num_inference_steps=40, guidance_scale=3.0, num_images_per_prompt=1, ).images[0] image.save("chroma.png") ``` ## Loading from a single file To use updated model checkpoints that are not in the Diffusers format, you can use the `ChromaTransformer2DModel` class to load the model from a single file in the original format. This is also useful when trying to load finetunes or quantized versions of the models that have been published by the community. The following example demonstrates how to run Chroma from a single file. Then run the following example ```python import torch from diffusers import ChromaTransformer2DModel, ChromaPipeline model_id = "lodestones/Chroma" dtype = torch.bfloat16 transformer = ChromaTransformer2DModel.from_single_file("https://huggingface.co/lodestones/Chroma/blob/main/chroma-unlocked-v37.safetensors", torch_dtype=dtype) pipe = ChromaPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=dtype) pipe.enable_model_cpu_offload() prompt = [ "A high-fashion close-up portrait of a blonde woman in clear sunglasses. The image uses a bold teal and red color split for dramatic lighting. The background is a simple teal-green. The photo is sharp and well-composed, and is designed for viewing with anaglyph 3D glasses for optimal effect. It looks professionally done." ] negative_prompt = ["low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors"] image = pipe( prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator("cpu").manual_seed(433), num_inference_steps=40, guidance_scale=3.0, ).images[0] image.save("chroma-single-file.png") ``` ## ChromaPipeline [[autodoc]] ChromaPipeline - all - __call__ ## ChromaImg2ImgPipeline [[autodoc]] ChromaImg2ImgPipeline - all - __call__
diffusers/docs/source/en/api/pipelines/chroma.md/0
{ "file_path": "diffusers/docs/source/en/api/pipelines/chroma.md", "repo_id": "diffusers", "token_count": 1254 }
117
<!-- Copyright 2025 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. --> # Cosmos [Cosmos World Foundation Model Platform for Physical AI](https://huggingface.co/papers/2501.03575) by NVIDIA. *Physical AI needs to be trained digitally first. It needs a digital twin of itself, the policy model, and a digital twin of the world, the world model. In this paper, we present the Cosmos World Foundation Model Platform to help developers build customized world models for their Physical AI setups. We position a world foundation model as a general-purpose world model that can be fine-tuned into customized world models for downstream applications. Our platform covers a video curation pipeline, pre-trained world foundation models, examples of post-training of pre-trained world foundation models, and video tokenizers. To help Physical AI builders solve the most critical problems of our society, we make our platform open-source and our models open-weight with permissive licenses available via https://github.com/NVIDIA/Cosmos.* <Tip> Make sure to check out the Schedulers [guide](../../using-diffusers/schedulers) to learn how to explore the tradeoff between scheduler speed and quality, and see the [reuse components across pipelines](../../using-diffusers/loading#reuse-a-pipeline) section to learn how to efficiently load the same components into multiple pipelines. </Tip> ## Loading original format checkpoints Original format checkpoints that have not been converted to diffusers-expected format can be loaded using the `from_single_file` method. ```python import torch from diffusers import Cosmos2TextToImagePipeline, CosmosTransformer3DModel model_id = "nvidia/Cosmos-Predict2-2B-Text2Image" transformer = CosmosTransformer3DModel.from_single_file( "https://huggingface.co/nvidia/Cosmos-Predict2-2B-Text2Image/blob/main/model.pt", torch_dtype=torch.bfloat16, ).to("cuda") pipe = Cosmos2TextToImagePipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.bfloat16) pipe.to("cuda") prompt = "A close-up shot captures a vibrant yellow scrubber vigorously working on a grimy plate, its bristles moving in circular motions to lift stubborn grease and food residue. The dish, once covered in remnants of a hearty meal, gradually reveals its original glossy surface. Suds form and bubble around the scrubber, creating a satisfying visual of cleanliness in progress. The sound of scrubbing fills the air, accompanied by the gentle clinking of the dish against the sink. As the scrubber continues its task, the dish transforms, gleaming under the bright kitchen lights, symbolizing the triumph of cleanliness over mess." negative_prompt = "The video captures a series of frames showing ugly scenes, static with no motion, motion blur, over-saturation, shaky footage, low resolution, grainy texture, pixelated images, poorly lit areas, underexposed and overexposed scenes, poor color balance, washed out colors, choppy sequences, jerky movements, low frame rate, artifacting, color banding, unnatural transitions, outdated special effects, fake elements, unconvincing visuals, poorly edited content, jump cuts, visual noise, and flickering. Overall, the video is of poor quality." output = pipe( prompt=prompt, negative_prompt=negative_prompt, generator=torch.Generator().manual_seed(1) ).images[0] output.save("output.png") ``` ## CosmosTextToWorldPipeline [[autodoc]] CosmosTextToWorldPipeline - all - __call__ ## CosmosVideoToWorldPipeline [[autodoc]] CosmosVideoToWorldPipeline - all - __call__ ## Cosmos2TextToImagePipeline [[autodoc]] Cosmos2TextToImagePipeline - all - __call__ ## Cosmos2VideoToWorldPipeline [[autodoc]] Cosmos2VideoToWorldPipeline - all - __call__ ## CosmosPipelineOutput [[autodoc]] pipelines.cosmos.pipeline_output.CosmosPipelineOutput ## CosmosImagePipelineOutput [[autodoc]] pipelines.cosmos.pipeline_output.CosmosImagePipelineOutput
diffusers/docs/source/en/api/pipelines/cosmos.md/0
{ "file_path": "diffusers/docs/source/en/api/pipelines/cosmos.md", "repo_id": "diffusers", "token_count": 1189 }
118
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Kandinsky 2.2 Kandinsky 2.2 is created by [Arseniy Shakhmatov](https://github.com/cene555), [Anton Razzhigaev](https://github.com/razzant), [Aleksandr Nikolich](https://github.com/AlexWortega), [Vladimir Arkhipkin](https://github.com/oriBetelgeuse), [Igor Pavlov](https://github.com/boomb0om), [Andrey Kuznetsov](https://github.com/kuznetsoffandrey), and [Denis Dimitrov](https://github.com/denndimitrov). The description from it's GitHub page is: *Kandinsky 2.2 brings substantial improvements upon its predecessor, Kandinsky 2.1, by introducing a new, more powerful image encoder - CLIP-ViT-G and the ControlNet support. The switch to CLIP-ViT-G as the image encoder significantly increases the model's capability to generate more aesthetic pictures and better understand text, thus enhancing the model's overall performance. The addition of the ControlNet mechanism allows the model to effectively control the process of generating images. This leads to more accurate and visually appealing outputs and opens new possibilities for text-guided image manipulation.* The original codebase can be found at [ai-forever/Kandinsky-2](https://github.com/ai-forever/Kandinsky-2). <Tip> Check out the [Kandinsky Community](https://huggingface.co/kandinsky-community) organization on the Hub for the official model checkpoints for tasks like text-to-image, image-to-image, and inpainting. </Tip> <Tip> Make sure to check out the schedulers [guide](../../using-diffusers/schedulers) to learn how to explore the tradeoff between scheduler speed and quality, and see the [reuse components across pipelines](../../using-diffusers/loading#reuse-a-pipeline) section to learn how to efficiently load the same components into multiple pipelines. </Tip> ## KandinskyV22PriorPipeline [[autodoc]] KandinskyV22PriorPipeline - all - __call__ - interpolate ## KandinskyV22Pipeline [[autodoc]] KandinskyV22Pipeline - all - __call__ ## KandinskyV22CombinedPipeline [[autodoc]] KandinskyV22CombinedPipeline - all - __call__ ## KandinskyV22ControlnetPipeline [[autodoc]] KandinskyV22ControlnetPipeline - all - __call__ ## KandinskyV22PriorEmb2EmbPipeline [[autodoc]] KandinskyV22PriorEmb2EmbPipeline - all - __call__ - interpolate ## KandinskyV22Img2ImgPipeline [[autodoc]] KandinskyV22Img2ImgPipeline - all - __call__ ## KandinskyV22Img2ImgCombinedPipeline [[autodoc]] KandinskyV22Img2ImgCombinedPipeline - all - __call__ ## KandinskyV22ControlnetImg2ImgPipeline [[autodoc]] KandinskyV22ControlnetImg2ImgPipeline - all - __call__ ## KandinskyV22InpaintPipeline [[autodoc]] KandinskyV22InpaintPipeline - all - __call__ ## KandinskyV22InpaintCombinedPipeline [[autodoc]] KandinskyV22InpaintCombinedPipeline - all - __call__
diffusers/docs/source/en/api/pipelines/kandinsky_v22.md/0
{ "file_path": "diffusers/docs/source/en/api/pipelines/kandinsky_v22.md", "repo_id": "diffusers", "token_count": 1046 }
119
<!--Copyright 2025 The GLIGEN Authors and 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> > [!WARNING] > This pipeline is deprecated but it can still be used. However, we won't test the pipeline anymore and won't accept any changes to it. If you run into any issues, reinstall the last Diffusers version that supported this model. # GLIGEN (Grounded Language-to-Image Generation) The GLIGEN model was created by researchers and engineers from [University of Wisconsin-Madison, Columbia University, and Microsoft](https://github.com/gligen/GLIGEN). The [`StableDiffusionGLIGENPipeline`] and [`StableDiffusionGLIGENTextImagePipeline`] can generate photorealistic images conditioned on grounding inputs. Along with text and bounding boxes with [`StableDiffusionGLIGENPipeline`], if input images are given, [`StableDiffusionGLIGENTextImagePipeline`] can insert objects described by text at the region defined by bounding boxes. Otherwise, it'll generate an image described by the caption/prompt and insert objects described by text at the region defined by bounding boxes. It's trained on COCO2014D and COCO2014CD datasets, and the model uses a frozen CLIP ViT-L/14 text encoder to condition itself on grounding inputs. The abstract from the [paper](https://huggingface.co/papers/2301.07093) is: *Large-scale text-to-image diffusion models have made amazing advances. However, the status quo is to use text input alone, which can impede controllability. In this work, we propose GLIGEN, Grounded-Language-to-Image Generation, a novel approach that builds upon and extends the functionality of existing pre-trained text-to-image diffusion models by enabling them to also be conditioned on grounding inputs. To preserve the vast concept knowledge of the pre-trained model, we freeze all of its weights and inject the grounding information into new trainable layers via a gated mechanism. Our model achieves open-world grounded text2img generation with caption and bounding box condition inputs, and the grounding ability generalizes well to novel spatial configurations and concepts. GLIGEN’s zeroshot performance on COCO and LVIS outperforms existing supervised layout-to-image baselines by a large margin.* <Tip> Make sure to check out the Stable Diffusion [Tips](https://huggingface.co/docs/diffusers/en/api/pipelines/stable_diffusion/overview#tips) section to learn how to explore the tradeoff between scheduler speed and quality and how to reuse pipeline components efficiently! If you want to use one of the official checkpoints for a task, explore the [gligen](https://huggingface.co/gligen) Hub organizations! </Tip> [`StableDiffusionGLIGENPipeline`] was contributed by [Nikhil Gajendrakumar](https://github.com/nikhil-masterful) and [`StableDiffusionGLIGENTextImagePipeline`] was contributed by [Nguyễn Công Tú Anh](https://github.com/tuanh123789). ## StableDiffusionGLIGENPipeline [[autodoc]] StableDiffusionGLIGENPipeline - all - __call__ - enable_vae_slicing - disable_vae_slicing - enable_vae_tiling - disable_vae_tiling - enable_model_cpu_offload - prepare_latents - enable_fuser ## StableDiffusionGLIGENTextImagePipeline [[autodoc]] StableDiffusionGLIGENTextImagePipeline - all - __call__ - enable_vae_slicing - disable_vae_slicing - enable_vae_tiling - disable_vae_tiling - enable_model_cpu_offload - prepare_latents - enable_fuser ## StableDiffusionPipelineOutput [[autodoc]] pipelines.stable_diffusion.StableDiffusionPipelineOutput
diffusers/docs/source/en/api/pipelines/stable_diffusion/gligen.md/0
{ "file_path": "diffusers/docs/source/en/api/pipelines/stable_diffusion/gligen.md", "repo_id": "diffusers", "token_count": 1106 }
120
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # DDPMScheduler [Denoising Diffusion Probabilistic Models](https://huggingface.co/papers/2006.11239) (DDPM) by Jonathan Ho, Ajay Jain and Pieter Abbeel proposes a diffusion based model of the same name. In the context of the 🤗 Diffusers library, DDPM refers to the discrete denoising scheduler from the paper as well as the pipeline. The abstract from the paper is: *We present high quality image synthesis results using diffusion probabilistic models, a class of latent variable models inspired by considerations from nonequilibrium thermodynamics. Our best results are obtained by training on a weighted variational bound designed according to a novel connection between diffusion probabilistic models and denoising score matching with Langevin dynamics, and our models naturally admit a progressive lossy decompression scheme that can be interpreted as a generalization of autoregressive decoding. On the unconditional CIFAR10 dataset, we obtain an Inception score of 9.46 and a state-of-the-art FID score of 3.17. On 256x256 LSUN, we obtain sample quality similar to ProgressiveGAN. Our implementation is available at [this https URL](https://github.com/hojonathanho/diffusion).* ## DDPMScheduler [[autodoc]] DDPMScheduler ## DDPMSchedulerOutput [[autodoc]] schedulers.scheduling_ddpm.DDPMSchedulerOutput
diffusers/docs/source/en/api/schedulers/ddpm.md/0
{ "file_path": "diffusers/docs/source/en/api/schedulers/ddpm.md", "repo_id": "diffusers", "token_count": 470 }
121
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # 🧨 Diffusers’ Ethical Guidelines ## Preamble [Diffusers](https://huggingface.co/docs/diffusers/index) provides pre-trained diffusion models and serves as a modular toolbox for inference and training. Given its real case applications in the world and potential negative impacts on society, we think it is important to provide the project with ethical guidelines to guide the development, users’ contributions, and usage of the Diffusers library. The risks associated with using this technology are still being examined, but to name a few: copyrights issues for artists; deep-fake exploitation; sexual content generation in inappropriate contexts; non-consensual impersonation; harmful social biases perpetuating the oppression of marginalized groups. We will keep tracking risks and adapt the following guidelines based on the community's responsiveness and valuable feedback. ## Scope The Diffusers community will apply the following ethical guidelines to the project’s development and help coordinate how the community will integrate the contributions, especially concerning sensitive topics related to ethical concerns. ## Ethical guidelines The following ethical guidelines apply generally, but we will primarily implement them when dealing with ethically sensitive issues while making a technical choice. Furthermore, we commit to adapting those ethical principles over time following emerging harms related to the state of the art of the technology in question. - **Transparency**: we are committed to being transparent in managing PRs, explaining our choices to users, and making technical decisions. - **Consistency**: we are committed to guaranteeing our users the same level of attention in project management, keeping it technically stable and consistent. - **Simplicity**: with a desire to make it easy to use and exploit the Diffusers library, we are committed to keeping the project’s goals lean and coherent. - **Accessibility**: the Diffusers project helps lower the entry bar for contributors who can help run it even without technical expertise. Doing so makes research artifacts more accessible to the community. - **Reproducibility**: we aim to be transparent about the reproducibility of upstream code, models, and datasets when made available through the Diffusers library. - **Responsibility**: as a community and through teamwork, we hold a collective responsibility to our users by anticipating and mitigating this technology's potential risks and dangers. ## Examples of implementations: Safety features and Mechanisms The team works daily to make the technical and non-technical tools available to deal with the potential ethical and social risks associated with diffusion technology. Moreover, the community's input is invaluable in ensuring these features' implementation and raising awareness with us. - [**Community tab**](https://huggingface.co/docs/hub/repositories-pull-requests-discussions): it enables the community to discuss and better collaborate on a project. - **Bias exploration and evaluation**: the Hugging Face team provides a [space](https://huggingface.co/spaces/society-ethics/DiffusionBiasExplorer) to demonstrate the biases in Stable Diffusion interactively. In this sense, we support and encourage bias explorers and evaluations. - **Encouraging safety in deployment** - [**Safe Stable Diffusion**](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_safe): It mitigates the well-known issue that models, like Stable Diffusion, that are trained on unfiltered, web-crawled datasets tend to suffer from inappropriate degeneration. Related paper: [Safe Latent Diffusion: Mitigating Inappropriate Degeneration in Diffusion Models](https://huggingface.co/papers/2211.05105). - [**Safety Checker**](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py): It checks and compares the class probability of a set of hard-coded harmful concepts in the embedding space against an image after it has been generated. The harmful concepts are intentionally hidden to prevent reverse engineering of the checker. - **Staged released on the Hub**: in particularly sensitive situations, access to some repositories should be restricted. This staged release is an intermediary step that allows the repository’s authors to have more control over its use. - **Licensing**: [OpenRAILs](https://huggingface.co/blog/open_rail), a new type of licensing, allow us to ensure free access while having a set of restrictions that ensure more responsible use.
diffusers/docs/source/en/conceptual/ethical_guidelines.md/0
{ "file_path": "diffusers/docs/source/en/conceptual/ethical_guidelines.md", "repo_id": "diffusers", "token_count": 1156 }
122
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # ModularPipeline [`ModularPipeline`] converts [`~modular_pipelines.ModularPipelineBlocks`]'s into an executable pipeline that loads models and performs the computation steps defined in the block. It is the main interface for running a pipeline and it is very similar to the [`DiffusionPipeline`] API. The main difference is to include an expected `output` argument in the pipeline. <hfoptions id="example"> <hfoption id="text-to-image"> ```py import torch from diffusers.modular_pipelines import SequentialPipelineBlocks from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS) modular_repo_id = "YiYiXu/modular-loader-t2i-0704" pipeline = blocks.init_pipeline(modular_repo_id) pipeline.load_default_components(torch_dtype=torch.float16) pipeline.to("cuda") image = pipeline(prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", output="images")[0] image.save("modular_t2i_out.png") ``` </hfoption> <hfoption id="image-to-image"> ```py import torch from diffusers.modular_pipelines import SequentialPipelineBlocks from diffusers.modular_pipelines.stable_diffusion_xl import IMAGE2IMAGE_BLOCKS blocks = SequentialPipelineBlocks.from_blocks_dict(IMAGE2IMAGE_BLOCKS) modular_repo_id = "YiYiXu/modular-loader-t2i-0704" pipeline = blocks.init_pipeline(modular_repo_id) pipeline.load_default_components(torch_dtype=torch.float16) pipeline.to("cuda") url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png" init_image = load_image(url) prompt = "a dog catching a frisbee in the jungle" image = pipeline(prompt=prompt, image=init_image, strength=0.8, output="images")[0] image.save("modular_i2i_out.png") ``` </hfoption> <hfoption id="inpainting"> ```py import torch from diffusers.modular_pipelines import SequentialPipelineBlocks from diffusers.modular_pipelines.stable_diffusion_xl import INPAINT_BLOCKS from diffusers.utils import load_image blocks = SequentialPipelineBlocks.from_blocks_dict(INPAINT_BLOCKS) modular_repo_id = "YiYiXu/modular-loader-t2i-0704" pipeline = blocks.init_pipeline(modular_repo_id) pipeline.load_default_components(torch_dtype=torch.float16) pipeline.to("cuda") img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png" mask_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-inpaint-mask.png" init_image = load_image(img_url) mask_image = load_image(mask_url) prompt = "A deep sea diver floating" image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.85, output="images")[0] image.save("moduar_inpaint_out.png") ``` </hfoption> </hfoptions> This guide will show you how to create a [`ModularPipeline`] and manage the components in it. ## Adding blocks Blocks are [`InsertableDict`] objects that can be inserted at specific positions, providing a flexible way to mix-and-match blocks. Use [`~modular_pipelines.modular_pipeline_utils.InsertableDict.insert`] on either the block class or `sub_blocks` attribute to add a block. ```py # BLOCKS is dict of block classes, you need to add class to it BLOCKS.insert("block_name", BlockClass, index) # sub_blocks attribute contains instance, add a block instance to the attribute t2i_blocks.sub_blocks.insert("block_name", block_instance, index) ``` Use [`~modular_pipelines.modular_pipeline_utils.InsertableDict.pop`] on either the block class or `sub_blocks` attribute to remove a block. ```py # remove a block class from preset BLOCKS.pop("text_encoder") # split out a block instance on its own text_encoder_block = t2i_blocks.sub_blocks.pop("text_encoder") ``` Swap blocks by setting the existing block to the new block. ```py # Replace block class in preset BLOCKS["prepare_latents"] = CustomPrepareLatents # Replace in sub_blocks attribute using an block instance t2i_blocks.sub_blocks["prepare_latents"] = CustomPrepareLatents() ``` ## Creating a pipeline There are two ways to create a [`ModularPipeline`]. Assemble and create a pipeline from [`ModularPipelineBlocks`] or load an existing pipeline with [`~ModularPipeline.from_pretrained`]. You should also initialize a [`ComponentsManager`] to handle device placement and memory and component management. > [!TIP] > Refer to the [ComponentsManager](./components_manager) doc for more details about how it can help manage components across different workflows. <hfoptions id="create"> <hfoption id="ModularPipelineBlocks"> Use the [`~ModularPipelineBlocks.init_pipeline`] method to create a [`ModularPipeline`] from the component and configuration specifications. This method loads the *specifications* from a `modular_model_index.json` file, but it doesn't load the *models* yet. ```py from diffusers import ComponentsManager from diffusers.modular_pipelines import SequentialPipelineBlocks from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS t2i_blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS) modular_repo_id = "YiYiXu/modular-loader-t2i-0704" components = ComponentsManager() t2i_pipeline = t2i_blocks.init_pipeline(modular_repo_id, components_manager=components) ``` </hfoption> <hfoption id="from_pretrained"> The [`~ModularPipeline.from_pretrained`] method creates a [`ModularPipeline`] from a modular repository on the Hub. ```py from diffusers import ModularPipeline, ComponentsManager components = ComponentsManager() pipeline = ModularPipeline.from_pretrained("YiYiXu/modular-loader-t2i-0704", components_manager=components) ``` Add the `trust_remote_code` argument to load a custom [`ModularPipeline`]. ```py from diffusers import ModularPipeline, ComponentsManager components = ComponentsManager() modular_repo_id = "YiYiXu/modular-diffdiff-0704" diffdiff_pipeline = ModularPipeline.from_pretrained(modular_repo_id, trust_remote_code=True, components_manager=components) ``` </hfoption> </hfoptions> ## Loading components A [`ModularPipeline`] doesn't automatically instantiate with components. It only loads the configuration and component specifications. You can load all components with [`~ModularPipeline.load_default_components`] or only load specific components with [`~ModularPipeline.load_components`]. <hfoptions id="load"> <hfoption id="load_default_components"> ```py import torch t2i_pipeline.load_default_components(torch_dtype=torch.float16) t2i_pipeline.to("cuda") ``` </hfoption> <hfoption id="load_components"> The example below only loads the UNet and VAE. ```py import torch t2i_pipeline.load_components(names=["unet", "vae"], torch_dtype=torch.float16) ``` </hfoption> </hfoptions> Print the pipeline to inspect the loaded pretrained components. ```py t2i_pipeline ``` This should match the `modular_model_index.json` file from the modular repository a pipeline is initialized from. If a pipeline doesn't need a component, it won't be included even if it exists in the modular repository. To modify where components are loaded from, edit the `modular_model_index.json` file in the repository and change it to your desired loading path. The example below loads a UNet from a different repository. ```json # original "unet": [ null, null, { "repo": "stabilityai/stable-diffusion-xl-base-1.0", "subfolder": "unet", "variant": "fp16" } ] # modified "unet": [ null, null, { "repo": "RunDiffusion/Juggernaut-XL-v9", "subfolder": "unet", "variant": "fp16" } ] ``` ### Component loading status The pipeline properties below provide more information about which components are loaded. Use `component_names` to return all expected components. ```py t2i_pipeline.component_names ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'guider', 'scheduler', 'unet', 'vae', 'image_processor'] ``` Use `null_component_names` to return components that aren't loaded yet. Load these components with [`~ModularPipeline.from_pretrained`]. ```py t2i_pipeline.null_component_names ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'scheduler'] ``` Use `pretrained_component_names` to return components that will be loaded from pretrained models. ```py t2i_pipeline.pretrained_component_names ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'scheduler', 'unet', 'vae'] ``` Use `config_component_names` to return components that are created with the default config (not loaded from a modular repository). Components from a config aren't included because they are already initialized during pipeline creation. This is why they aren't listed in `null_component_names`. ```py t2i_pipeline.config_component_names ['guider', 'image_processor'] ``` ## Updating components Components may be updated depending on whether it is a *pretrained component* or a *config component*. > [!WARNING] > A component may change from pretrained to config when updating a component. The component type is initially defined in a block's `expected_components` field. A pretrained component is updated with [`ComponentSpec`] whereas a config component is updated by eihter passing the object directly or with [`ComponentSpec`]. The [`ComponentSpec`] shows `default_creation_method="from_pretrained"` for a pretrained component shows `default_creation_method="from_config` for a config component. To update a pretrained component, create a [`ComponentSpec`] with the name of the component and where to load it from. Use the [`~ComponentSpec.load`] method to load the component. ```py from diffusers import ComponentSpec, UNet2DConditionModel unet_spec = ComponentSpec(name="unet",type_hint=UNet2DConditionModel, repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", variant="fp16") unet = unet_spec.load(torch_dtype=torch.float16) ``` The [`~ModularPipeline.update_components`] method replaces the component with a new one. ```py t2i_pipeline.update_components(unet=unet2) ``` When a component is updated, the loading specifications are also updated in the pipeline config. ### Component extraction and modification When you use [`~ComponentSpec.load`], the new component maintains its loading specifications. This makes it possible to extract the specification and recreate the component. ```py spec = ComponentSpec.from_component("unet", unet2) spec ComponentSpec(name='unet', type_hint=<class 'diffusers.models.unets.unet_2d_condition.UNet2DConditionModel'>, description=None, config=None, repo='stabilityai/stable-diffusion-xl-base-1.0', subfolder='unet', variant='fp16', revision=None, default_creation_method='from_pretrained') unet2_recreated = spec.load(torch_dtype=torch.float16) ``` The [`~ModularPipeline.get_component_spec`] method gets a copy of the current component specification to modify or update. ```py unet_spec = t2i_pipeline.get_component_spec("unet") unet_spec ComponentSpec( name='unet', type_hint=<class 'diffusers.models.unets.unet_2d_condition.UNet2DConditionModel'>, repo='RunDiffusion/Juggernaut-XL-v9', subfolder='unet', variant='fp16', default_creation_method='from_pretrained' ) # modify to load from a different repository unet_spec.repo = "stabilityai/stable-diffusion-xl-base-1.0" # load component with modified spec unet = unet_spec.load(torch_dtype=torch.float16) ``` ## Modular repository A repository is required if the pipeline blocks use *pretrained components*. The repository supplies loading specifications and metadata. [`ModularPipeline`] specifically requires *modular repositories* (see [example repository](https://huggingface.co/YiYiXu/modular-diffdiff)) which are more flexible than a typical repository. It contains a `modular_model_index.json` file containing the following 3 elements. - `library` and `class` shows which library the component was loaded from and it's class. If `null`, the component hasn't been loaded yet. - `loading_specs_dict` contains the information required to load the component such as the repository and subfolder it is loaded from. Unlike standard repositories, a modular repository can fetch components from different repositories based on the `loading_specs_dict`. Components don't need to exist in the same repository. A modular repository may contain custom code for loading a [`ModularPipeline`]. This allows you to use specialized blocks that aren't native to Diffusers. ``` modular-diffdiff-0704/ ├── block.py # Custom pipeline blocks implementation ├── config.json # Pipeline configuration and auto_map └── modular_model_index.json # Component loading specifications ``` The [config.json](https://huggingface.co/YiYiXu/modular-diffdiff-0704/blob/main/config.json) file contains an `auto_map` key that points to where a custom block is defined in `block.py`. ```json { "_class_name": "DiffDiffBlocks", "auto_map": { "ModularPipelineBlocks": "block.DiffDiffBlocks" } } ```
diffusers/docs/source/en/modular_diffusers/modular_pipeline.md/0
{ "file_path": "diffusers/docs/source/en/modular_diffusers/modular_pipeline.md", "repo_id": "diffusers", "token_count": 4393 }
123
# Pruna [Pruna](https://github.com/PrunaAI/pruna) is a model optimization framework that offers various optimization methods - quantization, pruning, caching, compilation - for accelerating inference and reducing memory usage. A general overview of the optimization methods are shown below. | Technique | Description | Speed | Memory | Quality | |--------------|-----------------------------------------------------------------------------------------------|:-----:|:------:|:-------:| | `batcher` | Groups multiple inputs together to be processed simultaneously, improving computational efficiency and reducing processing time. | ✅ | ❌ | ➖ | | `cacher` | Stores intermediate results of computations to speed up subsequent operations. | ✅ | ➖ | ➖ | | `compiler` | Optimises the model with instructions for specific hardware. | ✅ | ➖ | ➖ | | `distiller` | Trains a smaller, simpler model to mimic a larger, more complex model. | ✅ | ✅ | ❌ | | `quantizer` | Reduces the precision of weights and activations, lowering memory requirements. | ✅ | ✅ | ❌ | | `pruner` | Removes less important or redundant connections and neurons, resulting in a sparser, more efficient network. | ✅ | ✅ | ❌ | | `recoverer` | Restores the performance of a model after compression. | ➖ | ➖ | ✅ | | `factorizer` | Factorization batches several small matrix multiplications into one large fused operation. | ✅ | ➖ | ➖ | | `enhancer` | Enhances the model output by applying post-processing algorithms such as denoising or upscaling. | ❌ | - | ✅ | ✅ (improves), ➖ (approx. the same), ❌ (worsens) Explore the full range of optimization methods in the [Pruna documentation](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/configure.html#configure-algorithms). ## Installation Install Pruna with the following command. ```bash pip install pruna ``` ## Optimize Diffusers models A broad range of optimization algorithms are supported for Diffusers models as shown below. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/PrunaAI/documentation-images/resolve/main/diffusers/diffusers_combinations.png" alt="Overview of the supported optimization algorithms for diffusers models"> </div> The example below optimizes [black-forest-labs/FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) with a combination of factorizer, compiler, and cacher algorithms. This combination accelerates inference by up to 4.2x and cuts peak GPU memory usage from 34.7GB to 28.0GB, all while maintaining virtually the same output quality. > [!TIP] > Refer to the [Pruna optimization](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/configure.html) docs to learn more about the optimization techniques used in this example. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/PrunaAI/documentation-images/resolve/main/diffusers/flux_combination.png" alt="Optimization techniques used for FLUX.1-dev showing the combination of factorizer, compiler, and cacher algorithms"> </div> Start by defining a `SmashConfig` with the optimization algorithms to use. To optimize the model, wrap the pipeline and the `SmashConfig` with `smash` and then use the pipeline as normal for inference. ```python import torch from diffusers import FluxPipeline from pruna import PrunaModel, SmashConfig, smash # load the model # Try segmind/Segmind-Vega or black-forest-labs/FLUX.1-schnell with a small GPU memory pipe = FluxPipeline.from_pretrained( "black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16 ).to("cuda") # define the configuration smash_config = SmashConfig() smash_config["factorizer"] = "qkv_diffusers" smash_config["compiler"] = "torch_compile" smash_config["torch_compile_target"] = "module_list" smash_config["cacher"] = "fora" smash_config["fora_interval"] = 2 # for the best results in terms of speed you can add these configs # however they will increase your warmup time from 1.5 min to 10 min # smash_config["torch_compile_mode"] = "max-autotune-no-cudagraphs" # smash_config["quantizer"] = "torchao" # smash_config["torchao_quant_type"] = "fp8dq" # smash_config["torchao_excluded_modules"] = "norm+embedding" # optimize the model smashed_pipe = smash(pipe, smash_config) # run the model smashed_pipe("a knitted purple prune").images[0] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/PrunaAI/documentation-images/resolve/main/diffusers/flux_smashed_comparison.png"> </div> After optimization, we can share and load the optimized model using the Hugging Face Hub. ```python # save the model smashed_pipe.save_to_hub("<username>/FLUX.1-dev-smashed") # load the model smashed_pipe = PrunaModel.from_hub("<username>/FLUX.1-dev-smashed") ``` ## Evaluate and benchmark Diffusers models Pruna provides the [EvaluationAgent](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/evaluate.html) to evaluate the quality of your optimized models. We can metrics we care about, such as total time and throughput, and the dataset to evaluate on. We can define a model and pass it to the `EvaluationAgent`. <hfoptions id="eval"> <hfoption id="optimized model"> We can load and evaluate an optimized model by using the `EvaluationAgent` and pass it to the `Task`. ```python import torch from diffusers import FluxPipeline from pruna import PrunaModel from pruna.data.pruna_datamodule import PrunaDataModule from pruna.evaluation.evaluation_agent import EvaluationAgent from pruna.evaluation.metrics import ( ThroughputMetric, TorchMetricWrapper, TotalTimeMetric, ) from pruna.evaluation.task import Task # define the device device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" # load the model # Try PrunaAI/Segmind-Vega-smashed or PrunaAI/FLUX.1-dev-smashed with a small GPU memory smashed_pipe = PrunaModel.from_hub("PrunaAI/FLUX.1-dev-smashed") # Define the metrics metrics = [ TotalTimeMetric(n_iterations=20, n_warmup_iterations=5), ThroughputMetric(n_iterations=20, n_warmup_iterations=5), TorchMetricWrapper("clip"), ] # Define the datamodule datamodule = PrunaDataModule.from_string("LAION256") datamodule.limit_datasets(10) # Define the task and evaluation agent task = Task(metrics, datamodule=datamodule, device=device) eval_agent = EvaluationAgent(task) # Evaluate smashed model and offload it to CPU smashed_pipe.move_to_device(device) smashed_pipe_results = eval_agent.evaluate(smashed_pipe) smashed_pipe.move_to_device("cpu") ``` </hfoption> <hfoption id="standalone model"> Instead of comparing the optimized model to the base model, you can also evaluate the standalone `diffusers` model. This is useful if you want to evaluate the performance of the model without the optimization. We can do so by using the `PrunaModel` wrapper and run the `EvaluationAgent` on it. ```python import torch from diffusers import FluxPipeline from pruna import PrunaModel # load the model # Try PrunaAI/Segmind-Vega-smashed or PrunaAI/FLUX.1-dev-smashed with a small GPU memory pipe = FluxPipeline.from_pretrained( "black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16 ).to("cpu") wrapped_pipe = PrunaModel(model=pipe) ``` </hfoption> </hfoptions> Now that you have seen how to optimize and evaluate your models, you can start using Pruna to optimize your own models. Luckily, we have many examples to help you get started. > [!TIP] > For more details about benchmarking Flux, check out the [Announcing FLUX-Juiced: The Fastest Image Generation Endpoint (2.6 times faster)!](https://huggingface.co/blog/PrunaAI/flux-fastest-image-generation-endpoint) blog post and the [InferBench](https://huggingface.co/spaces/PrunaAI/InferBench) Space. ## Reference - [Pruna](https://github.com/pruna-ai/pruna) - [Pruna optimization](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/configure.html#configure-algorithms) - [Pruna evaluation](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/evaluate.html) - [Pruna tutorials](https://docs.pruna.ai/en/stable/docs_pruna/tutorials/index.html)
diffusers/docs/source/en/optimization/pruna.md/0
{ "file_path": "diffusers/docs/source/en/optimization/pruna.md", "repo_id": "diffusers", "token_count": 2873 }
124
# Create a dataset for training There are many datasets on the [Hub](https://huggingface.co/datasets?task_categories=task_categories:text-to-image&sort=downloads) to train a model on, but if you can't find one you're interested in or want to use your own, you can create a dataset with the 🤗 [Datasets](https://huggingface.co/docs/datasets) library. The dataset structure depends on the task you want to train your model on. The most basic dataset structure is a directory of images for tasks like unconditional image generation. Another dataset structure may be a directory of images and a text file containing their corresponding text captions for tasks like text-to-image generation. This guide will show you two ways to create a dataset to finetune on: - provide a folder of images to the `--train_data_dir` argument - upload a dataset to the Hub and pass the dataset repository id to the `--dataset_name` argument <Tip> 💡 Learn more about how to create an image dataset for training in the [Create an image dataset](https://huggingface.co/docs/datasets/image_dataset) guide. </Tip> ## Provide a dataset as a folder For unconditional generation, you can provide your own dataset as a folder of images. The training script uses the [`ImageFolder`](https://huggingface.co/docs/datasets/en/image_dataset#imagefolder) builder from 🤗 Datasets to automatically build a dataset from the folder. Your directory structure should look like: ```bash data_dir/xxx.png data_dir/xxy.png data_dir/[...]/xxz.png ``` Pass the path to the dataset directory to the `--train_data_dir` argument, and then you can start training: ```bash accelerate launch train_unconditional.py \ --train_data_dir <path-to-train-directory> \ <other-arguments> ``` ## Upload your data to the Hub <Tip> 💡 For more details and context about creating and uploading a dataset to the Hub, take a look at the [Image search with 🤗 Datasets](https://huggingface.co/blog/image-search-datasets) post. </Tip> Start by creating a dataset with the [`ImageFolder`](https://huggingface.co/docs/datasets/image_load#imagefolder) feature, which creates an `image` column containing the PIL-encoded images. You can use the `data_dir` or `data_files` parameters to specify the location of the dataset. The `data_files` parameter supports mapping specific files to dataset splits like `train` or `test`: ```python from datasets import load_dataset # example 1: local folder dataset = load_dataset("imagefolder", data_dir="path_to_your_folder") # example 2: local files (supported formats are tar, gzip, zip, xz, rar, zstd) dataset = load_dataset("imagefolder", data_files="path_to_zip_file") # example 3: remote files (supported formats are tar, gzip, zip, xz, rar, zstd) dataset = load_dataset( "imagefolder", data_files="https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip", ) # example 4: providing several splits dataset = load_dataset( "imagefolder", data_files={"train": ["path/to/file1", "path/to/file2"], "test": ["path/to/file3", "path/to/file4"]} ) ``` Then use the [`~datasets.Dataset.push_to_hub`] method to upload the dataset to the Hub: ```python # assuming you have ran the hf auth login command in a terminal dataset.push_to_hub("name_of_your_dataset") # if you want to push to a private repo, simply pass private=True: dataset.push_to_hub("name_of_your_dataset", private=True) ``` Now the dataset is available for training by passing the dataset name to the `--dataset_name` argument: ```bash accelerate launch --mixed_precision="fp16" train_text_to_image.py \ --pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-v1-5" \ --dataset_name="name_of_your_dataset" \ <other-arguments> ``` ## Next steps Now that you've created a dataset, you can plug it into the `train_data_dir` (if your dataset is local) or `dataset_name` (if your dataset is on the Hub) arguments of a training script. For your next steps, feel free to try and use your dataset to train a model for [unconditional generation](unconditional_training) or [text-to-image generation](text2image)!
diffusers/docs/source/en/training/create_dataset.md/0
{ "file_path": "diffusers/docs/source/en/training/create_dataset.md", "repo_id": "diffusers", "token_count": 1309 }
125
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # AutoPipeline Diffusers provides many pipelines for basic tasks like generating images, videos, audio, and inpainting. On top of these, there are specialized pipelines for adapters and features like upscaling, super-resolution, and more. Different pipeline classes can even use the same checkpoint because they share the same pretrained model! With so many different pipelines, it can be overwhelming to know which pipeline class to use. The [AutoPipeline](../api/pipelines/auto_pipeline) class is designed to simplify the variety of pipelines in Diffusers. It is a generic *task-first* pipeline that lets you focus on a task ([`AutoPipelineForText2Image`], [`AutoPipelineForImage2Image`], and [`AutoPipelineForInpainting`]) without needing to know the specific pipeline class. The [AutoPipeline](../api/pipelines/auto_pipeline) automatically detects the correct pipeline class to use. For example, let's use the [dreamlike-art/dreamlike-photoreal-2.0](https://hf.co/dreamlike-art/dreamlike-photoreal-2.0) checkpoint. Under the hood, [AutoPipeline](../api/pipelines/auto_pipeline): 1. Detects a `"stable-diffusion"` class from the [model_index.json](https://hf.co/dreamlike-art/dreamlike-photoreal-2.0/blob/main/model_index.json) file. 2. Depending on the task you're interested in, it loads the [`StableDiffusionPipeline`], [`StableDiffusionImg2ImgPipeline`], or [`StableDiffusionInpaintPipeline`]. Any parameter (`strength`, `num_inference_steps`, etc.) you would pass to these specific pipelines can also be passed to the [AutoPipeline](../api/pipelines/auto_pipeline). <hfoptions id="autopipeline"> <hfoption id="text-to-image"> ```py from diffusers import AutoPipelineForText2Image import torch pipe_txt2img = AutoPipelineForText2Image.from_pretrained( "dreamlike-art/dreamlike-photoreal-2.0", torch_dtype=torch.float16, use_safetensors=True ).to("cuda") prompt = "cinematic photo of Godzilla eating sushi with a cat in a izakaya, 35mm photograph, film, professional, 4k, highly detailed" generator = torch.Generator(device="cpu").manual_seed(37) image = pipe_txt2img(prompt, generator=generator).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-text2img.png"/> </div> </hfoption> <hfoption id="image-to-image"> ```py from diffusers import AutoPipelineForImage2Image from diffusers.utils import load_image import torch pipe_img2img = AutoPipelineForImage2Image.from_pretrained( "dreamlike-art/dreamlike-photoreal-2.0", torch_dtype=torch.float16, use_safetensors=True ).to("cuda") init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-text2img.png") prompt = "cinematic photo of Godzilla eating burgers with a cat in a fast food restaurant, 35mm photograph, film, professional, 4k, highly detailed" generator = torch.Generator(device="cpu").manual_seed(53) image = pipe_img2img(prompt, image=init_image, generator=generator).images[0] image ``` Notice how the [dreamlike-art/dreamlike-photoreal-2.0](https://hf.co/dreamlike-art/dreamlike-photoreal-2.0) checkpoint is used for both text-to-image and image-to-image tasks? To save memory and avoid loading the checkpoint twice, use the [`~DiffusionPipeline.from_pipe`] method. ```py pipe_img2img = AutoPipelineForImage2Image.from_pipe(pipe_txt2img).to("cuda") image = pipeline(prompt, image=init_image, generator=generator).images[0] image ``` You can learn more about the [`~DiffusionPipeline.from_pipe`] method in the [Reuse a pipeline](../using-diffusers/loading#reuse-a-pipeline) guide. <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-img2img.png"/> </div> </hfoption> <hfoption id="inpainting"> ```py from diffusers import AutoPipelineForInpainting from diffusers.utils import load_image import torch pipeline = AutoPipelineForInpainting.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, use_safetensors=True ).to("cuda") init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-img2img.png") mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-mask.png") prompt = "cinematic photo of a owl, 35mm photograph, film, professional, 4k, highly detailed" generator = torch.Generator(device="cpu").manual_seed(38) image = pipeline(prompt, image=init_image, mask_image=mask_image, generator=generator, strength=0.4).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-inpaint.png"/> </div> </hfoption> </hfoptions> ## Unsupported checkpoints The [AutoPipeline](../api/pipelines/auto_pipeline) supports [Stable Diffusion](../api/pipelines/stable_diffusion/overview), [Stable Diffusion XL](../api/pipelines/stable_diffusion/stable_diffusion_xl), [ControlNet](../api/pipelines/controlnet), [Kandinsky 2.1](../api/pipelines/kandinsky.md), [Kandinsky 2.2](../api/pipelines/kandinsky_v22), and [DeepFloyd IF](../api/pipelines/deepfloyd_if) checkpoints. If you try to load an unsupported checkpoint, you'll get an error. ```py from diffusers import AutoPipelineForImage2Image import torch pipeline = AutoPipelineForImage2Image.from_pretrained( "openai/shap-e-img2img", torch_dtype=torch.float16, use_safetensors=True ) "ValueError: AutoPipeline can't find a pipeline linked to ShapEImg2ImgPipeline for None" ```
diffusers/docs/source/en/tutorials/autopipeline.md/0
{ "file_path": "diffusers/docs/source/en/tutorials/autopipeline.md", "repo_id": "diffusers", "token_count": 2061 }
126
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Latent Consistency Model [[open-in-colab]] [Latent Consistency Models (LCMs)](https://hf.co/papers/2310.04378) enable fast high-quality image generation by directly predicting the reverse diffusion process in the latent rather than pixel space. In other words, LCMs try to predict the noiseless image from the noisy image in contrast to typical diffusion models that iteratively remove noise from the noisy image. By avoiding the iterative sampling process, LCMs are able to generate high-quality images in 2-4 steps instead of 20-30 steps. LCMs are distilled from pretrained models which requires ~32 hours of A100 compute. To speed this up, [LCM-LoRAs](https://hf.co/papers/2311.05556) train a [LoRA adapter](https://huggingface.co/docs/peft/conceptual_guides/adapter#low-rank-adaptation-lora) which have much fewer parameters to train compared to the full model. The LCM-LoRA can be plugged into a diffusion model once it has been trained. This guide will show you how to use LCMs and LCM-LoRAs for fast inference on tasks and how to use them with other adapters like ControlNet or T2I-Adapter. > [!TIP] > LCMs and LCM-LoRAs are available for Stable Diffusion v1.5, Stable Diffusion XL, and the SSD-1B model. You can find their checkpoints on the [Latent Consistency](https://hf.co/collections/latent-consistency/latent-consistency-models-weights-654ce61a95edd6dffccef6a8) Collections. ## Text-to-image <hfoptions id="lcm-text2img"> <hfoption id="LCM"> To use LCMs, you need to load the LCM checkpoint for your supported model into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Then you can use the pipeline as usual, and pass a text prompt to generate an image in just 4 steps. A couple of notes to keep in mind when using LCMs are: * Typically, batch size is doubled inside the pipeline for classifier-free guidance. But LCM applies guidance with guidance embeddings and doesn't need to double the batch size, which leads to faster inference. The downside is that negative prompts don't work with LCM because they don't have any effect on the denoising process. * The ideal range for `guidance_scale` is [3., 13.] because that is what the UNet was trained with. However, disabling `guidance_scale` with a value of 1.0 is also effective in most cases. ```python from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler import torch unet = UNet2DConditionModel.from_pretrained( "latent-consistency/lcm-sdxl", torch_dtype=torch.float16, variant="fp16", ) pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", unet=unet, torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k" generator = torch.manual_seed(0) image = pipe( prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=8.0 ).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_full_sdxl_t2i.png"/> </div> </hfoption> <hfoption id="LCM-LoRA"> To use LCM-LoRAs, you need to replace the scheduler with the [`LCMScheduler`] and load the LCM-LoRA weights with the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method. Then you can use the pipeline as usual, and pass a text prompt to generate an image in just 4 steps. A couple of notes to keep in mind when using LCM-LoRAs are: * Typically, batch size is doubled inside the pipeline for classifier-free guidance. But LCM applies guidance with guidance embeddings and doesn't need to double the batch size, which leads to faster inference. The downside is that negative prompts don't work with LCM because they don't have any effect on the denoising process. * You could use guidance with LCM-LoRAs, but it is very sensitive to high `guidance_scale` values and can lead to artifacts in the generated image. The best values we've found are between [1.0, 2.0]. * Replace [stabilityai/stable-diffusion-xl-base-1.0](https://hf.co/stabilityai/stable-diffusion-xl-base-1.0) with any finetuned model. For example, try using the [animagine-xl](https://huggingface.co/Linaqruf/animagine-xl) checkpoint to generate anime images with SDXL. ```py import torch from diffusers import DiffusionPipeline, LCMScheduler pipe = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", variant="fp16", torch_dtype=torch.float16 ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl") prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k" generator = torch.manual_seed(42) image = pipe( prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=1.0 ).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_sdxl_t2i.png"/> </div> </hfoption> </hfoptions> ## Image-to-image <hfoptions id="lcm-img2img"> <hfoption id="LCM"> To use LCMs for image-to-image, you need to load the LCM checkpoint for your supported model into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Then you can use the pipeline as usual, and pass a text prompt and initial image to generate an image in just 4 steps. > [!TIP] > Experiment with different values for `num_inference_steps`, `strength`, and `guidance_scale` to get the best results. ```python import torch from diffusers import AutoPipelineForImage2Image, UNet2DConditionModel, LCMScheduler from diffusers.utils import load_image unet = UNet2DConditionModel.from_pretrained( "SimianLuo/LCM_Dreamshaper_v7", subfolder="unet", torch_dtype=torch.float16, ) pipe = AutoPipelineForImage2Image.from_pretrained( "Lykon/dreamshaper-7", unet=unet, torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png") prompt = "Astronauts in a jungle, cold color palette, muted colors, detailed, 8k" generator = torch.manual_seed(0) image = pipe( prompt, image=init_image, num_inference_steps=4, guidance_scale=7.5, strength=0.5, generator=generator ).images[0] image ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-img2img.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption> </div> </div> </hfoption> <hfoption id="LCM-LoRA"> To use LCM-LoRAs for image-to-image, you need to replace the scheduler with the [`LCMScheduler`] and load the LCM-LoRA weights with the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method. Then you can use the pipeline as usual, and pass a text prompt and initial image to generate an image in just 4 steps. > [!TIP] > Experiment with different values for `num_inference_steps`, `strength`, and `guidance_scale` to get the best results. ```py import torch from diffusers import AutoPipelineForImage2Image, LCMScheduler from diffusers.utils import make_image_grid, load_image pipe = AutoPipelineForImage2Image.from_pretrained( "Lykon/dreamshaper-7", torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png") prompt = "Astronauts in a jungle, cold color palette, muted colors, detailed, 8k" generator = torch.manual_seed(0) image = pipe( prompt, image=init_image, num_inference_steps=4, guidance_scale=1, strength=0.6, generator=generator ).images[0] image ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-img2img.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption> </div> </div> </hfoption> </hfoptions> ## Inpainting To use LCM-LoRAs for inpainting, you need to replace the scheduler with the [`LCMScheduler`] and load the LCM-LoRA weights with the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method. Then you can use the pipeline as usual, and pass a text prompt, initial image, and mask image to generate an image in just 4 steps. ```py import torch from diffusers import AutoPipelineForInpainting, LCMScheduler from diffusers.utils import load_image, make_image_grid pipe = AutoPipelineForInpainting.from_pretrained( "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png") mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png") prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k" generator = torch.manual_seed(0) image = pipe( prompt=prompt, image=init_image, mask_image=mask_image, generator=generator, num_inference_steps=4, guidance_scale=4, ).images[0] image ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-inpaint.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption> </div> </div> ## Adapters LCMs are compatible with adapters like LoRA, ControlNet, T2I-Adapter, and AnimateDiff. You can bring the speed of LCMs to these adapters to generate images in a certain style or condition the model on another input like a canny image. ### LoRA [LoRA](../using-diffusers/loading_adapters#lora) adapters can be rapidly finetuned to learn a new style from just a few images and plugged into a pretrained model to generate images in that style. <hfoptions id="lcm-lora"> <hfoption id="LCM"> Load the LCM checkpoint for your supported model into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Then you can use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LoRA weights into the LCM and generate a styled image in a few steps. ```python from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler import torch unet = UNet2DConditionModel.from_pretrained( "latent-consistency/lcm-sdxl", torch_dtype=torch.float16, variant="fp16", ) pipe = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", unet=unet, torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("TheLastBen/Papercut_SDXL", weight_name="papercut.safetensors", adapter_name="papercut") prompt = "papercut, a cute fox" generator = torch.manual_seed(0) image = pipe( prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=8.0 ).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_full_sdx_lora_mix.png"/> </div> </hfoption> <hfoption id="LCM-LoRA"> Replace the scheduler with the [`LCMScheduler`]. Then you can use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LCM-LoRA weights and the style LoRA you want to use. Combine both LoRA adapters with the [`~loaders.UNet2DConditionLoadersMixin.set_adapters`] method and generate a styled image in a few steps. ```py import torch from diffusers import DiffusionPipeline, LCMScheduler pipe = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", variant="fp16", torch_dtype=torch.float16 ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl", adapter_name="lcm") pipe.load_lora_weights("TheLastBen/Papercut_SDXL", weight_name="papercut.safetensors", adapter_name="papercut") pipe.set_adapters(["lcm", "papercut"], adapter_weights=[1.0, 0.8]) prompt = "papercut, a cute fox" generator = torch.manual_seed(0) image = pipe(prompt, num_inference_steps=4, guidance_scale=1, generator=generator).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_sdx_lora_mix.png"/> </div> </hfoption> </hfoptions> ### ControlNet [ControlNet](./controlnet) are adapters that can be trained on a variety of inputs like canny edge, pose estimation, or depth. The ControlNet can be inserted into the pipeline to provide additional conditioning and control to the model for more accurate generation. You can find additional ControlNet models trained on other inputs in [lllyasviel's](https://hf.co/lllyasviel) repository. <hfoptions id="lcm-controlnet"> <hfoption id="LCM"> Load a ControlNet model trained on canny images and pass it to the [`ControlNetModel`]. Then you can load a LCM model into [`StableDiffusionControlNetPipeline`] and replace the scheduler with the [`LCMScheduler`]. Now pass the canny image to the pipeline and generate an image. > [!TIP] > Experiment with different values for `num_inference_steps`, `controlnet_conditioning_scale`, `cross_attention_kwargs`, and `guidance_scale` to get the best results. ```python import torch import cv2 import numpy as np from PIL import Image from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, LCMScheduler from diffusers.utils import load_image, make_image_grid image = load_image( "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png" ).resize((512, 512)) image = np.array(image) low_threshold = 100 high_threshold = 200 image = cv2.Canny(image, low_threshold, high_threshold) image = image[:, :, None] image = np.concatenate([image, image, image], axis=2) canny_image = Image.fromarray(image) controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16) pipe = StableDiffusionControlNetPipeline.from_pretrained( "SimianLuo/LCM_Dreamshaper_v7", controlnet=controlnet, torch_dtype=torch.float16, safety_checker=None, ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) generator = torch.manual_seed(0) image = pipe( "the mona lisa", image=canny_image, num_inference_steps=4, generator=generator, ).images[0] make_image_grid([canny_image, image], rows=1, cols=2) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_full_sdv1-5_controlnet.png"/> </div> </hfoption> <hfoption id="LCM-LoRA"> Load a ControlNet model trained on canny images and pass it to the [`ControlNetModel`]. Then you can load a Stable Diffusion v1.5 model into [`StableDiffusionControlNetPipeline`] and replace the scheduler with the [`LCMScheduler`]. Use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LCM-LoRA weights, and pass the canny image to the pipeline and generate an image. > [!TIP] > Experiment with different values for `num_inference_steps`, `controlnet_conditioning_scale`, `cross_attention_kwargs`, and `guidance_scale` to get the best results. ```py import torch import cv2 import numpy as np from PIL import Image from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, LCMScheduler from diffusers.utils import load_image image = load_image( "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png" ).resize((512, 512)) image = np.array(image) low_threshold = 100 high_threshold = 200 image = cv2.Canny(image, low_threshold, high_threshold) image = image[:, :, None] image = np.concatenate([image, image, image], axis=2) canny_image = Image.fromarray(image) controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16) pipe = StableDiffusionControlNetPipeline.from_pretrained( "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, safety_checker=None, variant="fp16" ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") generator = torch.manual_seed(0) image = pipe( "the mona lisa", image=canny_image, num_inference_steps=4, guidance_scale=1.5, controlnet_conditioning_scale=0.8, cross_attention_kwargs={"scale": 1}, generator=generator, ).images[0] image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_sdv1-5_controlnet.png"/> </div> </hfoption> </hfoptions> ### T2I-Adapter [T2I-Adapter](./t2i_adapter) is an even more lightweight adapter than ControlNet, that provides an additional input to condition a pretrained model with. It is faster than ControlNet but the results may be slightly worse. You can find additional T2I-Adapter checkpoints trained on other inputs in [TencentArc's](https://hf.co/TencentARC) repository. <hfoptions id="lcm-t2i"> <hfoption id="LCM"> Load a T2IAdapter trained on canny images and pass it to the [`StableDiffusionXLAdapterPipeline`]. Then load a LCM checkpoint into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Now pass the canny image to the pipeline and generate an image. ```python import torch import cv2 import numpy as np from PIL import Image from diffusers import StableDiffusionXLAdapterPipeline, UNet2DConditionModel, T2IAdapter, LCMScheduler from diffusers.utils import load_image, make_image_grid # detect the canny map in low resolution to avoid high-frequency details image = load_image( "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png" ).resize((384, 384)) image = np.array(image) low_threshold = 100 high_threshold = 200 image = cv2.Canny(image, low_threshold, high_threshold) image = image[:, :, None] image = np.concatenate([image, image, image], axis=2) canny_image = Image.fromarray(image).resize((1024, 1216)) adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16, variant="fp16").to("cuda") unet = UNet2DConditionModel.from_pretrained( "latent-consistency/lcm-sdxl", torch_dtype=torch.float16, variant="fp16", ) pipe = StableDiffusionXLAdapterPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", unet=unet, adapter=adapter, torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) prompt = "the mona lisa, 4k picture, high quality" negative_prompt = "extra digit, fewer digits, cropped, worst quality, low quality, glitch, deformed, mutated, ugly, disfigured" generator = torch.manual_seed(0) image = pipe( prompt=prompt, negative_prompt=negative_prompt, image=canny_image, num_inference_steps=4, guidance_scale=5, adapter_conditioning_scale=0.8, adapter_conditioning_factor=1, generator=generator, ).images[0] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-t2i.png"/> </div> </hfoption> <hfoption id="LCM-LoRA"> Load a T2IAdapter trained on canny images and pass it to the [`StableDiffusionXLAdapterPipeline`]. Replace the scheduler with the [`LCMScheduler`], and use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LCM-LoRA weights. Pass the canny image to the pipeline and generate an image. ```py import torch import cv2 import numpy as np from PIL import Image from diffusers import StableDiffusionXLAdapterPipeline, UNet2DConditionModel, T2IAdapter, LCMScheduler from diffusers.utils import load_image, make_image_grid # detect the canny map in low resolution to avoid high-frequency details image = load_image( "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png" ).resize((384, 384)) image = np.array(image) low_threshold = 100 high_threshold = 200 image = cv2.Canny(image, low_threshold, high_threshold) image = image[:, :, None] image = np.concatenate([image, image, image], axis=2) canny_image = Image.fromarray(image).resize((1024, 1024)) adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16, variant="fp16").to("cuda") pipe = StableDiffusionXLAdapterPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", adapter=adapter, torch_dtype=torch.float16, variant="fp16", ).to("cuda") pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl") prompt = "the mona lisa, 4k picture, high quality" negative_prompt = "extra digit, fewer digits, cropped, worst quality, low quality, glitch, deformed, mutated, ugly, disfigured" generator = torch.manual_seed(0) image = pipe( prompt=prompt, negative_prompt=negative_prompt, image=canny_image, num_inference_steps=4, guidance_scale=1.5, adapter_conditioning_scale=0.8, adapter_conditioning_factor=1, generator=generator, ).images[0] ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-t2i.png"/> </div> </hfoption> </hfoptions> ### AnimateDiff [AnimateDiff](../api/pipelines/animatediff) is an adapter that adds motion to an image. It can be used with most Stable Diffusion models, effectively turning them into "video generation" models. Generating good results with a video model usually requires generating multiple frames (16-24), which can be very slow with a regular Stable Diffusion model. LCM-LoRA can speed up this process by only taking 4-8 steps for each frame. Load a [`AnimateDiffPipeline`] and pass a [`MotionAdapter`] to it. Then replace the scheduler with the [`LCMScheduler`], and combine both LoRA adapters with the [`~loaders.UNet2DConditionLoadersMixin.set_adapters`] method. Now you can pass a prompt to the pipeline and generate an animated image. ```py import torch from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler, LCMScheduler from diffusers.utils import export_to_gif adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5") pipe = AnimateDiffPipeline.from_pretrained( "frankjoshua/toonyou_beta6", motion_adapter=adapter, ).to("cuda") # set scheduler pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) # load LCM-LoRA pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5", adapter_name="lcm") pipe.load_lora_weights("guoyww/animatediff-motion-lora-zoom-in", weight_name="diffusion_pytorch_model.safetensors", adapter_name="motion-lora") pipe.set_adapters(["lcm", "motion-lora"], adapter_weights=[0.55, 1.2]) prompt = "best quality, masterpiece, 1girl, looking at viewer, blurry background, upper body, contemporary, dress" generator = torch.manual_seed(0) frames = pipe( prompt=prompt, num_inference_steps=5, guidance_scale=1.25, cross_attention_kwargs={"scale": 1}, num_frames=24, generator=generator ).frames[0] export_to_gif(frames, "animation.gif") ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-animatediff.gif"/> </div>
diffusers/docs/source/en/using-diffusers/inference_with_lcm.md/0
{ "file_path": "diffusers/docs/source/en/using-diffusers/inference_with_lcm.md", "repo_id": "diffusers", "token_count": 9014 }
127
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Shap-E [[open-in-colab]] Shap-E is a conditional model for generating 3D assets which could be used for video game development, interior design, and architecture. It is trained on a large dataset of 3D assets, and post-processed to render more views of each object and produce 16K instead of 4K point clouds. The Shap-E model is trained in two steps: 1. an encoder accepts the point clouds and rendered views of a 3D asset and outputs the parameters of implicit functions that represent the asset 2. a diffusion model is trained on the latents produced by the encoder to generate either neural radiance fields (NeRFs) or a textured 3D mesh, making it easier to render and use the 3D asset in downstream applications This guide will show you how to use Shap-E to start generating your own 3D assets! Before you begin, make sure you have the following libraries installed: ```py # uncomment to install the necessary libraries in Colab #!pip install -q diffusers transformers accelerate trimesh ``` ## Text-to-3D To generate a gif of a 3D object, pass a text prompt to the [`ShapEPipeline`]. The pipeline generates a list of image frames which are used to create the 3D object. ```py import torch from diffusers import ShapEPipeline device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16, variant="fp16") pipe = pipe.to(device) guidance_scale = 15.0 prompt = ["A firecracker", "A birthday cupcake"] images = pipe( prompt, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, ).images ``` 이제 [`~utils.export_to_gif`] 함수를 사용해 이미지 프레임 리스트를 3D 오브젝트의 gif로 변환합니다. ```py from diffusers.utils import export_to_gif export_to_gif(images[0], "firecracker_3d.gif") export_to_gif(images[1], "cake_3d.gif") ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/firecracker_out.gif"/> <figcaption class="mt-2 text-center text-sm text-gray-500">prompt = "A firecracker"</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/cake_out.gif"/> <figcaption class="mt-2 text-center text-sm text-gray-500">prompt = "A birthday cupcake"</figcaption> </div> </div> ## Image-to-3D To generate a 3D object from another image, use the [`ShapEImg2ImgPipeline`]. You can use an existing image or generate an entirely new one. Let's use the [Kandinsky 2.1](../api/pipelines/kandinsky) model to generate a new image. ```py from diffusers import DiffusionPipeline import torch prior_pipeline = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda") pipeline = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16, use_safetensors=True).to("cuda") prompt = "A cheeseburger, white background" image_embeds, negative_image_embeds = prior_pipeline(prompt, guidance_scale=1.0).to_tuple() image = pipeline( prompt, image_embeds=image_embeds, negative_image_embeds=negative_image_embeds, ).images[0] image.save("burger.png") ``` Pass the cheeseburger to the [`ShapEImg2ImgPipeline`] to generate a 3D representation of it. ```py from PIL import Image from diffusers import ShapEImg2ImgPipeline from diffusers.utils import export_to_gif pipe = ShapEImg2ImgPipeline.from_pretrained("openai/shap-e-img2img", torch_dtype=torch.float16, variant="fp16").to("cuda") guidance_scale = 3.0 image = Image.open("burger.png").resize((256, 256)) images = pipe( image, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, ).images gif_path = export_to_gif(images[0], "burger_3d.gif") ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/burger_in.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">cheeseburger</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/burger_out.gif"/> <figcaption class="mt-2 text-center text-sm text-gray-500">3D cheeseburger</figcaption> </div> </div> ## Generate mesh Shap-E is a flexible model that can also generate textured mesh outputs to be rendered for downstream applications. In this example, you'll convert the output into a `glb` file because the 🤗 Datasets library supports mesh visualization of `glb` files which can be rendered by the [Dataset viewer](https://huggingface.co/docs/hub/datasets-viewer#dataset-preview). You can generate mesh outputs for both the [`ShapEPipeline`] and [`ShapEImg2ImgPipeline`] by specifying the `output_type` parameter as `"mesh"`: ```py import torch from diffusers import ShapEPipeline device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16, variant="fp16") pipe = pipe.to(device) guidance_scale = 15.0 prompt = "A birthday cupcake" images = pipe(prompt, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, output_type="mesh").images ``` Use the [`~utils.export_to_ply`] function to save the mesh output as a `ply` file: <Tip> You can optionally save the mesh output as an `obj` file with the [`~utils.export_to_obj`] function. The ability to save the mesh output in a variety of formats makes it more flexible for downstream usage! </Tip> ```py from diffusers.utils import export_to_ply ply_path = export_to_ply(images[0], "3d_cake.ply") print(f"Saved to folder: {ply_path}") ``` Then you can convert the `ply` file to a `glb` file with the trimesh library: ```py import trimesh mesh = trimesh.load("3d_cake.ply") mesh_export = mesh.export("3d_cake.glb", file_type="glb") ``` By default, the mesh output is focused from the bottom viewpoint but you can change the default viewpoint by applying a rotation transform: ```py import trimesh import numpy as np mesh = trimesh.load("3d_cake.ply") rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0]) mesh = mesh.apply_transform(rot) mesh_export = mesh.export("3d_cake.glb", file_type="glb") ``` Upload the mesh file to your dataset repository to visualize it with the Dataset viewer! <div class="flex justify-center"> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/3D-cake.gif"/> </div>
diffusers/docs/source/en/using-diffusers/shap-e.md/0
{ "file_path": "diffusers/docs/source/en/using-diffusers/shap-e.md", "repo_id": "diffusers", "token_count": 2540 }
128
- sections: - local: index title: 🧨 Diffusers - local: quicktour title: "훑어보기" - local: stable_diffusion title: Stable Diffusion - local: installation title: 설치 title: 시작하기 - sections: - local: tutorials/tutorial_overview title: 개요 - local: using-diffusers/write_own_pipeline title: 모델과 스케줄러 이해하기 - local: in_translation # tutorials/autopipeline title: (번역중) AutoPipeline - local: tutorials/basic_training title: Diffusion 모델 학습하기 - local: in_translation # tutorials/using_peft_for_inference title: (번역중) 추론을 위한 LoRAs 불러오기 - local: in_translation # tutorials/fast_diffusion title: (번역중) Text-to-image diffusion 모델 추론 가속화하기 - local: in_translation # tutorials/inference_with_big_models title: (번역중) 큰 모델로 작업하기 title: 튜토리얼 - sections: - local: using-diffusers/loading title: 파이프라인 불러오기 - local: using-diffusers/custom_pipeline_overview title: 커뮤니티 파이프라인과 컴포넌트 불러오기 - local: using-diffusers/schedulers title: 스케줄러와 모델 불러오기 - local: using-diffusers/other-formats title: 모델 파일과 레이아웃 - local: using-diffusers/loading_adapters title: 어댑터 불러오기 - local: using-diffusers/push_to_hub title: 파일들을 Hub로 푸시하기 title: 파이프라인과 어댑터 불러오기 - sections: - local: using-diffusers/unconditional_image_generation title: Unconditional 이미지 생성 - local: using-diffusers/conditional_image_generation title: Text-to-image - local: using-diffusers/img2img title: Image-to-image - local: using-diffusers/inpaint title: 인페인팅 - local: in_translation # using-diffusers/text-img2vid title: (번역중) Text 또는 image-to-video - local: using-diffusers/depth2img title: Depth-to-image title: 생성 태스크 - sections: - local: in_translation # using-diffusers/overview_techniques title: (번역중) 개요 - local: training/distributed_inference title: 여러 GPU를 사용한 분산 추론 - local: in_translation # using-diffusers/merge_loras title: (번역중) LoRA 병합 - local: in_translation # using-diffusers/scheduler_features title: (번역중) 스케줄러 기능 - local: in_translation # using-diffusers/callback title: (번역중) 파이프라인 콜백 - local: in_translation # using-diffusers/reusing_seeds title: (번역중) 재현 가능한 파이프라인 - local: in_translation # using-diffusers/image_quality title: (번역중) 이미지 퀄리티 조절하기 - local: using-diffusers/weighted_prompts title: 프롬프트 기술 title: 추론 테크닉 - sections: - local: in_translation # advanced_inference/outpaint title: (번역중) Outpainting title: 추론 심화 - sections: - local: in_translation # using-diffusers/sdxl title: (번역중) Stable Diffusion XL - local: using-diffusers/sdxl_turbo title: SDXL Turbo - local: using-diffusers/kandinsky title: Kandinsky - local: in_translation # using-diffusers/ip_adapter title: (번역중) IP-Adapter - local: in_translation # using-diffusers/pag title: (번역중) PAG - local: in_translation # using-diffusers/controlnet title: (번역중) ControlNet - local: in_translation # using-diffusers/t2i_adapter title: (번역중) T2I-Adapter - local: in_translation # using-diffusers/inference_with_lcm title: (번역중) Latent Consistency Model - local: using-diffusers/textual_inversion_inference title: Textual inversion - local: using-diffusers/shap-e title: Shap-E - local: using-diffusers/diffedit title: DiffEdit - local: in_translation # using-diffusers/inference_with_tcd_lora title: (번역중) Trajectory Consistency Distillation-LoRA - local: using-diffusers/svd title: Stable Video Diffusion - local: in_translation # using-diffusers/marigold_usage title: (번역중) Marigold 컴퓨터 비전 title: 특정 파이프라인 예시 - sections: - local: training/overview title: 개요 - local: training/create_dataset title: 학습을 위한 데이터셋 생성하기 - local: training/adapt_a_model title: 새로운 태스크에 모델 적용하기 - isExpanded: false sections: - local: training/unconditional_training title: Unconditional 이미지 생성 - local: training/text2image title: Text-to-image - local: in_translation # training/sdxl title: (번역중) Stable Diffusion XL - local: in_translation # training/kandinsky title: (번역중) Kandinsky 2.2 - local: in_translation # training/wuerstchen title: (번역중) Wuerstchen - local: training/controlnet title: ControlNet - local: in_translation # training/t2i_adapters title: (번역중) T2I-Adapters - local: training/instructpix2pix title: InstructPix2Pix title: 모델 - isExpanded: false sections: - local: training/text_inversion title: Textual Inversion - local: training/dreambooth title: DreamBooth - local: training/lora title: LoRA - local: training/custom_diffusion title: Custom Diffusion - local: in_translation # training/lcm_distill title: (번역중) Latent Consistency Distillation - local: in_translation # training/ddpo title: (번역중) DDPO 강화학습 훈련 title: 메서드 title: 학습 - sections: - local: optimization/fp16 title: 추론 스피드업 - local: in_translation # optimization/memory title: (번역중) 메모리 사용량 줄이기 - local: optimization/torch2.0 title: PyTorch 2.0 - local: optimization/xformers title: xFormers - local: optimization/tome title: Token merging - local: in_translation # optimization/deepcache title: (번역중) DeepCache - local: in_translation # optimization/tgate title: (번역중) TGATE - sections: - local: using-diffusers/stable_diffusion_jax_how_to title: JAX/Flax - local: optimization/onnx title: ONNX - local: optimization/open_vino title: OpenVINO - local: optimization/coreml title: Core ML title: 최적화된 모델 형식 - sections: - local: optimization/mps title: Metal Performance Shaders (MPS) - local: optimization/habana title: Intel Gaudi title: 최적화된 하드웨어 title: 추론 가속화와 메모리 줄이기 - sections: - local: conceptual/philosophy title: 철학 - local: using-diffusers/controlling_generation title: 제어된 생성 - local: conceptual/contribution title: 어떻게 기여하나요? - local: conceptual/ethical_guidelines title: Diffusers의 윤리적 가이드라인 - local: conceptual/evaluation title: Diffusion Models 평가하기 title: 개념 가이드 - sections: - sections: - sections: - local: api/pipelines/stable_diffusion/stable_diffusion_xl title: Stable Diffusion XL title: Stable Diffusion title: Pipelines title: API
diffusers/docs/source/ko/_toctree.yml/0
{ "file_path": "diffusers/docs/source/ko/_toctree.yml", "repo_id": "diffusers", "token_count": 3467 }
129
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Diffusers에서의 PyTorch 2.0 가속화 지원 `0.13.0` 버전부터 Diffusers는 [PyTorch 2.0](https://pytorch.org/get-started/pytorch-2.0/)에서의 최신 최적화를 지원합니다. 이는 다음을 포함됩니다. 1. momory-efficient attention을 사용한 가속화된 트랜스포머 지원 - `xformers`같은 추가적인 dependencies 필요 없음 2. 추가 성능 향상을 위한 개별 모델에 대한 컴파일 기능 [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) 지원 ## 설치 가속화된 어텐션 구현과 및 `torch.compile()`을 사용하기 위해, pip에서 최신 버전의 PyTorch 2.0을 설치되어 있고 diffusers 0.13.0. 버전 이상인지 확인하세요. 아래 설명된 바와 같이, PyTorch 2.0이 활성화되어 있을 때 diffusers는 최적화된 어텐션 프로세서([`AttnProcessor2_0`](https://github.com/huggingface/diffusers/blob/1a5797c6d4491a879ea5285c4efc377664e0332d/src/diffusers/models/attention_processor.py#L798))를 사용합니다. ```bash pip install --upgrade torch diffusers ``` ## 가속화된 트랜스포머와 `torch.compile` 사용하기. 1. **가속화된 트랜스포머 구현** PyTorch 2.0에는 [`torch.nn.functional.scaled_dot_product_attention`](https://pytorch.org/docs/master/generated/torch.nn.functional.scaled_dot_product_attention) 함수를 통해 최적화된 memory-efficient attention의 구현이 포함되어 있습니다. 이는 입력 및 GPU 유형에 따라 여러 최적화를 자동으로 활성화합니다. 이는 [xFormers](https://github.com/facebookresearch/xformers)의 `memory_efficient_attention`과 유사하지만 기본적으로 PyTorch에 내장되어 있습니다. 이러한 최적화는 PyTorch 2.0이 설치되어 있고 `torch.nn.functional.scaled_dot_product_attention`을 사용할 수 있는 경우 Diffusers에서 기본적으로 활성화됩니다. 이를 사용하려면 `torch 2.0`을 설치하고 파이프라인을 사용하기만 하면 됩니다. 예를 들어: ```Python import torch from diffusers import DiffusionPipeline pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16) pipe = pipe.to("cuda") prompt = "a photo of an astronaut riding a horse on mars" image = pipe(prompt).images[0] ``` 이를 명시적으로 활성화하려면(필수는 아님) 아래와 같이 수행할 수 있습니다. ```diff import torch from diffusers import DiffusionPipeline + from diffusers.models.attention_processor import AttnProcessor2_0 pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda") + pipe.unet.set_attn_processor(AttnProcessor2_0()) prompt = "a photo of an astronaut riding a horse on mars" image = pipe(prompt).images[0] ``` 이 실행 과정은 `xFormers`만큼 빠르고 메모리적으로 효율적이어야 합니다. 자세한 내용은 [벤치마크](#benchmark)에서 확인하세요. 파이프라인을 보다 deterministic으로 만들거나 파인 튜닝된 모델을 [Core ML](https://huggingface.co/docs/diffusers/v0.16.0/en/optimization/coreml#how-to-run-stable-diffusion-with-core-ml)과 같은 다른 형식으로 변환해야 하는 경우 바닐라 어텐션 프로세서 ([`AttnProcessor`](https://github.com/huggingface/diffusers/blob/1a5797c6d4491a879ea5285c4efc377664e0332d/src/diffusers/models/attention_processor.py#L402))로 되돌릴 수 있습니다. 일반 어텐션 프로세서를 사용하려면 [`~diffusers.UNet2DConditionModel.set_default_attn_processor`] 함수를 사용할 수 있습니다: ```Python import torch from diffusers import DiffusionPipeline from diffusers.models.attention_processor import AttnProcessor pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda") pipe.unet.set_default_attn_processor() prompt = "a photo of an astronaut riding a horse on mars" image = pipe(prompt).images[0] ``` 2. **torch.compile** 추가적인 속도 향상을 위해 새로운 `torch.compile` 기능을 사용할 수 있습니다. 파이프라인의 UNet은 일반적으로 계산 비용이 가장 크기 때문에 나머지 하위 모델(텍스트 인코더와 VAE)은 그대로 두고 `unet`을 `torch.compile`로 래핑합니다. 자세한 내용과 다른 옵션은 [torch 컴파일 문서](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)를 참조하세요. ```python pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) images = pipe(prompt, num_inference_steps=steps, num_images_per_prompt=batch_size).images ``` GPU 유형에 따라 `compile()`은 가속화된 트랜스포머 최적화를 통해 **5% - 300%**의 _추가 성능 향상_을 얻을 수 있습니다. 그러나 컴파일은 Ampere(A100, 3090), Ada(4090) 및 Hopper(H100)와 같은 최신 GPU 아키텍처에서 더 많은 성능 향상을 가져올 수 있음을 참고하세요. 컴파일은 완료하는 데 약간의 시간이 걸리므로, 파이프라인을 한 번 준비한 다음 동일한 유형의 추론 작업을 여러 번 수행해야 하는 상황에 가장 적합합니다. 다른 이미지 크기에서 컴파일된 파이프라인을 호출하면 시간적 비용이 많이 들 수 있는 컴파일 작업이 다시 트리거됩니다. ## 벤치마크 PyTorch 2.0의 효율적인 어텐션 구현과 `torch.compile`을 사용하여 가장 많이 사용되는 5개의 파이프라인에 대해 다양한 GPU와 배치 크기에 걸쳐 포괄적인 벤치마크를 수행했습니다. 여기서는 [`torch.compile()`이 최적으로 활용되도록 하는](https://github.com/huggingface/diffusers/pull/3313) `diffusers 0.17.0.dev0`을 사용했습니다. ### 벤치마킹 코드 #### Stable Diffusion text-to-image ```python from diffusers import DiffusionPipeline import torch path = "stable-diffusion-v1-5/stable-diffusion-v1-5" run_compile = True # Set True / False pipe = DiffusionPipeline.from_pretrained(path, torch_dtype=torch.float16) pipe = pipe.to("cuda") pipe.unet.to(memory_format=torch.channels_last) if run_compile: print("Run torch compile") pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) prompt = "ghibli style, a fantasy landscape with castles" for _ in range(3): images = pipe(prompt=prompt).images ``` #### Stable Diffusion image-to-image ```python from diffusers import StableDiffusionImg2ImgPipeline import requests import torch from PIL import Image from io import BytesIO url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg" response = requests.get(url) init_image = Image.open(BytesIO(response.content)).convert("RGB") init_image = init_image.resize((512, 512)) path = "stable-diffusion-v1-5/stable-diffusion-v1-5" run_compile = True # Set True / False pipe = StableDiffusionImg2ImgPipeline.from_pretrained(path, torch_dtype=torch.float16) pipe = pipe.to("cuda") pipe.unet.to(memory_format=torch.channels_last) if run_compile: print("Run torch compile") pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) prompt = "ghibli style, a fantasy landscape with castles" for _ in range(3): image = pipe(prompt=prompt, image=init_image).images[0] ``` #### Stable Diffusion - inpainting ```python from diffusers import StableDiffusionInpaintPipeline import requests import torch from PIL import Image from io import BytesIO url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg" def download_image(url): response = requests.get(url) return Image.open(BytesIO(response.content)).convert("RGB") img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" init_image = download_image(img_url).resize((512, 512)) mask_image = download_image(mask_url).resize((512, 512)) path = "runwayml/stable-diffusion-inpainting" run_compile = True # Set True / False pipe = StableDiffusionInpaintPipeline.from_pretrained(path, torch_dtype=torch.float16) pipe = pipe.to("cuda") pipe.unet.to(memory_format=torch.channels_last) if run_compile: print("Run torch compile") pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) prompt = "ghibli style, a fantasy landscape with castles" for _ in range(3): image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] ``` #### ControlNet ```python from diffusers import StableDiffusionControlNetPipeline, ControlNetModel import requests import torch from PIL import Image from io import BytesIO url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg" response = requests.get(url) init_image = Image.open(BytesIO(response.content)).convert("RGB") init_image = init_image.resize((512, 512)) path = "stable-diffusion-v1-5/stable-diffusion-v1-5" run_compile = True # Set True / False controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16) pipe = StableDiffusionControlNetPipeline.from_pretrained( path, controlnet=controlnet, torch_dtype=torch.float16 ) pipe = pipe.to("cuda") pipe.unet.to(memory_format=torch.channels_last) pipe.controlnet.to(memory_format=torch.channels_last) if run_compile: print("Run torch compile") pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) pipe.controlnet = torch.compile(pipe.controlnet, mode="reduce-overhead", fullgraph=True) prompt = "ghibli style, a fantasy landscape with castles" for _ in range(3): image = pipe(prompt=prompt, image=init_image).images[0] ``` #### IF text-to-image + upscaling ```python from diffusers import DiffusionPipeline import torch run_compile = True # Set True / False pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-M-v1.0", variant="fp16", text_encoder=None, torch_dtype=torch.float16) pipe.to("cuda") pipe_2 = DiffusionPipeline.from_pretrained("DeepFloyd/IF-II-M-v1.0", variant="fp16", text_encoder=None, torch_dtype=torch.float16) pipe_2.to("cuda") pipe_3 = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-x4-upscaler", torch_dtype=torch.float16) pipe_3.to("cuda") pipe.unet.to(memory_format=torch.channels_last) pipe_2.unet.to(memory_format=torch.channels_last) pipe_3.unet.to(memory_format=torch.channels_last) if run_compile: pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) pipe_2.unet = torch.compile(pipe_2.unet, mode="reduce-overhead", fullgraph=True) pipe_3.unet = torch.compile(pipe_3.unet, mode="reduce-overhead", fullgraph=True) prompt = "the blue hulk" prompt_embeds = torch.randn((1, 2, 4096), dtype=torch.float16) neg_prompt_embeds = torch.randn((1, 2, 4096), dtype=torch.float16) for _ in range(3): image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=neg_prompt_embeds, output_type="pt").images image_2 = pipe_2(image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=neg_prompt_embeds, output_type="pt").images image_3 = pipe_3(prompt=prompt, image=image, noise_level=100).images ``` PyTorch 2.0 및 `torch.compile()`로 얻을 수 있는 가능한 속도 향상에 대해, [Stable Diffusion text-to-image pipeline](StableDiffusionPipeline)에 대한 상대적인 속도 향상을 보여주는 차트를 5개의 서로 다른 GPU 제품군(배치 크기 4)에 대해 나타냅니다: ![t2i_speedup](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/pt2_benchmarks/t2i_speedup.png) To give you an even better idea of how this speed-up holds for the other pipelines presented above, consider the following plot that shows the benchmarking numbers from an A100 across three different batch sizes (with PyTorch 2.0 nightly and `torch.compile()`): 이 속도 향상이 위에 제시된 다른 파이프라인에 대해서도 어떻게 유지되는지 더 잘 이해하기 위해, 세 가지의 다른 배치 크기에 걸쳐 A100의 벤치마킹(PyTorch 2.0 nightly 및 `torch.compile() 사용) 수치를 보여주는 차트를 보입니다: ![a100_numbers](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/pt2_benchmarks/a100_numbers.png) _(위 차트의 벤치마크 메트릭은 **초당 iteration 수(iterations/second)**입니다)_ 그러나 투명성을 위해 모든 벤치마킹 수치를 공개합니다! 다음 표들에서는, **_초당 처리되는 iteration_** 수 측면에서의 결과를 보여줍니다. ### A100 (batch size: 1) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 21.66 | 23.13 | 44.03 | 49.74 | | SD - img2img | 21.81 | 22.40 | 43.92 | 46.32 | | SD - inpaint | 22.24 | 23.23 | 43.76 | 49.25 | | SD - controlnet | 15.02 | 15.82 | 32.13 | 36.08 | | IF | 20.21 / <br>13.84 / <br>24.00 | 20.12 / <br>13.70 / <br>24.03 | ❌ | 97.34 / <br>27.23 / <br>111.66 | ### A100 (batch size: 4) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 11.6 | 13.12 | 14.62 | 17.27 | | SD - img2img | 11.47 | 13.06 | 14.66 | 17.25 | | SD - inpaint | 11.67 | 13.31 | 14.88 | 17.48 | | SD - controlnet | 8.28 | 9.38 | 10.51 | 12.41 | | IF | 25.02 | 18.04 | ❌ | 48.47 | ### A100 (batch size: 16) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 3.04 | 3.6 | 3.83 | 4.68 | | SD - img2img | 2.98 | 3.58 | 3.83 | 4.67 | | SD - inpaint | 3.04 | 3.66 | 3.9 | 4.76 | | SD - controlnet | 2.15 | 2.58 | 2.74 | 3.35 | | IF | 8.78 | 9.82 | ❌ | 16.77 | ### V100 (batch size: 1) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 18.99 | 19.14 | 20.95 | 22.17 | | SD - img2img | 18.56 | 19.18 | 20.95 | 22.11 | | SD - inpaint | 19.14 | 19.06 | 21.08 | 22.20 | | SD - controlnet | 13.48 | 13.93 | 15.18 | 15.88 | | IF | 20.01 / <br>9.08 / <br>23.34 | 19.79 / <br>8.98 / <br>24.10 | ❌ | 55.75 / <br>11.57 / <br>57.67 | ### V100 (batch size: 4) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 5.96 | 5.89 | 6.83 | 6.86 | | SD - img2img | 5.90 | 5.91 | 6.81 | 6.82 | | SD - inpaint | 5.99 | 6.03 | 6.93 | 6.95 | | SD - controlnet | 4.26 | 4.29 | 4.92 | 4.93 | | IF | 15.41 | 14.76 | ❌ | 22.95 | ### V100 (batch size: 16) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 1.66 | 1.66 | 1.92 | 1.90 | | SD - img2img | 1.65 | 1.65 | 1.91 | 1.89 | | SD - inpaint | 1.69 | 1.69 | 1.95 | 1.93 | | SD - controlnet | 1.19 | 1.19 | OOM after warmup | 1.36 | | IF | 5.43 | 5.29 | ❌ | 7.06 | ### T4 (batch size: 1) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 6.9 | 6.95 | 7.3 | 7.56 | | SD - img2img | 6.84 | 6.99 | 7.04 | 7.55 | | SD - inpaint | 6.91 | 6.7 | 7.01 | 7.37 | | SD - controlnet | 4.89 | 4.86 | 5.35 | 5.48 | | IF | 17.42 / <br>2.47 / <br>18.52 | 16.96 / <br>2.45 / <br>18.69 | ❌ | 24.63 / <br>2.47 / <br>23.39 | ### T4 (batch size: 4) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 1.79 | 1.79 | 2.03 | 1.99 | | SD - img2img | 1.77 | 1.77 | 2.05 | 2.04 | | SD - inpaint | 1.81 | 1.82 | 2.09 | 2.09 | | SD - controlnet | 1.34 | 1.27 | 1.47 | 1.46 | | IF | 5.79 | 5.61 | ❌ | 7.39 | ### T4 (batch size: 16) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 2.34s | 2.30s | OOM after 2nd iteration | 1.99s | | SD - img2img | 2.35s | 2.31s | OOM after warmup | 2.00s | | SD - inpaint | 2.30s | 2.26s | OOM after 2nd iteration | 1.95s | | SD - controlnet | OOM after 2nd iteration | OOM after 2nd iteration | OOM after warmup | OOM after warmup | | IF * | 1.44 | 1.44 | ❌ | 1.94 | ### RTX 3090 (batch size: 1) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 22.56 | 22.84 | 23.84 | 25.69 | | SD - img2img | 22.25 | 22.61 | 24.1 | 25.83 | | SD - inpaint | 22.22 | 22.54 | 24.26 | 26.02 | | SD - controlnet | 16.03 | 16.33 | 17.38 | 18.56 | | IF | 27.08 / <br>9.07 / <br>31.23 | 26.75 / <br>8.92 / <br>31.47 | ❌ | 68.08 / <br>11.16 / <br>65.29 | ### RTX 3090 (batch size: 4) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 6.46 | 6.35 | 7.29 | 7.3 | | SD - img2img | 6.33 | 6.27 | 7.31 | 7.26 | | SD - inpaint | 6.47 | 6.4 | 7.44 | 7.39 | | SD - controlnet | 4.59 | 4.54 | 5.27 | 5.26 | | IF | 16.81 | 16.62 | ❌ | 21.57 | ### RTX 3090 (batch size: 16) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 1.7 | 1.69 | 1.93 | 1.91 | | SD - img2img | 1.68 | 1.67 | 1.93 | 1.9 | | SD - inpaint | 1.72 | 1.71 | 1.97 | 1.94 | | SD - controlnet | 1.23 | 1.22 | 1.4 | 1.38 | | IF | 5.01 | 5.00 | ❌ | 6.33 | ### RTX 4090 (batch size: 1) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 40.5 | 41.89 | 44.65 | 49.81 | | SD - img2img | 40.39 | 41.95 | 44.46 | 49.8 | | SD - inpaint | 40.51 | 41.88 | 44.58 | 49.72 | | SD - controlnet | 29.27 | 30.29 | 32.26 | 36.03 | | IF | 69.71 / <br>18.78 / <br>85.49 | 69.13 / <br>18.80 / <br>85.56 | ❌ | 124.60 / <br>26.37 / <br>138.79 | ### RTX 4090 (batch size: 4) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 12.62 | 12.84 | 15.32 | 15.59 | | SD - img2img | 12.61 | 12,.79 | 15.35 | 15.66 | | SD - inpaint | 12.65 | 12.81 | 15.3 | 15.58 | | SD - controlnet | 9.1 | 9.25 | 11.03 | 11.22 | | IF | 31.88 | 31.14 | ❌ | 43.92 | ### RTX 4090 (batch size: 16) | **Pipeline** | **torch 2.0 - <br>no compile** | **torch nightly - <br>no compile** | **torch 2.0 - <br>compile** | **torch nightly - <br>compile** | |:---:|:---:|:---:|:---:|:---:| | SD - txt2img | 3.17 | 3.2 | 3.84 | 3.85 | | SD - img2img | 3.16 | 3.2 | 3.84 | 3.85 | | SD - inpaint | 3.17 | 3.2 | 3.85 | 3.85 | | SD - controlnet | 2.23 | 2.3 | 2.7 | 2.75 | | IF | 9.26 | 9.2 | ❌ | 13.31 | ## 참고 * Follow [this PR](https://github.com/huggingface/diffusers/pull/3313) for more details on the environment used for conducting the benchmarks. * For the IF pipeline and batch sizes > 1, we only used a batch size of >1 in the first IF pipeline for text-to-image generation and NOT for upscaling. So, that means the two upscaling pipelines received a batch size of 1. *Thanks to [Horace He](https://github.com/Chillee) from the PyTorch team for their support in improving our support of `torch.compile()` in Diffusers.* * 벤치마크 수행에 사용된 환경에 대한 자세한 내용은 [이 PR](https://github.com/huggingface/diffusers/pull/3313)을 참조하세요. * IF 파이프라인와 배치 크기 > 1의 경우 첫 번째 IF 파이프라인에서 text-to-image 생성을 위한 배치 크기 > 1만 사용했으며 업스케일링에는 사용하지 않았습니다. 즉, 두 개의 업스케일링 파이프라인이 배치 크기 1임을 의미합니다. *Diffusers에서 `torch.compile()` 지원을 개선하는 데 도움을 준 PyTorch 팀의 [Horace He](https://github.com/Chillee)에게 감사드립니다.*
diffusers/docs/source/ko/optimization/torch2.0.md/0
{ "file_path": "diffusers/docs/source/ko/optimization/torch2.0.md", "repo_id": "diffusers", "token_count": 10806 }
130
<!--Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> [[open-in-colab]] # Diffusion 모델을 학습하기 Unconditional 이미지 생성은 학습에 사용된 데이터셋과 유사한 이미지를 생성하는 diffusion 모델에서 인기 있는 어플리케이션입니다. 일반적으로, 가장 좋은 결과는 특정 데이터셋에 사전 훈련된 모델을 파인튜닝하는 것으로 얻을 수 있습니다. 이 [허브](https://huggingface.co/search/full-text?q=unconditional-image-generation&type=model)에서 이러한 많은 체크포인트를 찾을 수 있지만, 만약 마음에 드는 체크포인트를 찾지 못했다면, 언제든지 스스로 학습할 수 있습니다! 이 튜토리얼은 나만의 🦋 나비 🦋를 생성하기 위해 [Smithsonian Butterflies](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) 데이터셋의 하위 집합에서 [`UNet2DModel`] 모델을 학습하는 방법을 가르쳐줄 것입니다. <Tip> 💡 이 학습 튜토리얼은 [Training with 🧨 Diffusers](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) 노트북 기반으로 합니다. Diffusion 모델의 작동 방식 및 자세한 내용은 노트북을 확인하세요! </Tip> 시작 전에, 🤗 Datasets을 불러오고 전처리하기 위해 데이터셋이 설치되어 있는지 다수 GPU에서 학습을 간소화하기 위해 🤗 Accelerate 가 설치되어 있는지 확인하세요. 그 후 학습 메트릭을 시각화하기 위해 [TensorBoard](https://www.tensorflow.org/tensorboard)를 또한 설치하세요. (또한 학습 추적을 위해 [Weights & Biases](https://docs.wandb.ai/)를 사용할 수 있습니다.) ```bash !pip install diffusers[training] ``` 커뮤니티에 모델을 공유할 것을 권장하며, 이를 위해서 Hugging Face 계정에 로그인을 해야 합니다. (계정이 없다면 [여기](https://hf.co/join)에서 만들 수 있습니다.) 노트북에서 로그인할 수 있으며 메시지가 표시되면 토큰을 입력할 수 있습니다. ```py >>> from huggingface_hub import notebook_login >>> notebook_login() ``` 또는 터미널로 로그인할 수 있습니다: ```bash hf auth login ``` 모델 체크포인트가 상당히 크기 때문에 [Git-LFS](https://git-lfs.com/)에서 대용량 파일의 버전 관리를 할 수 있습니다. ```bash !sudo apt -qq install git-lfs !git config --global credential.helper store ``` ## 학습 구성 편의를 위해 학습 파라미터들을 포함한 `TrainingConfig` 클래스를 생성합니다 (자유롭게 조정 가능): ```py >>> from dataclasses import dataclass >>> @dataclass ... class TrainingConfig: ... image_size = 128 # 생성되는 이미지 해상도 ... train_batch_size = 16 ... eval_batch_size = 16 # 평가 동안에 샘플링할 이미지 수 ... num_epochs = 50 ... gradient_accumulation_steps = 1 ... learning_rate = 1e-4 ... lr_warmup_steps = 500 ... save_image_epochs = 10 ... save_model_epochs = 30 ... mixed_precision = "fp16" # `no`는 float32, 자동 혼합 정밀도를 위한 `fp16` ... output_dir = "ddpm-butterflies-128" # 로컬 및 HF Hub에 저장되는 모델명 ... push_to_hub = True # 저장된 모델을 HF Hub에 업로드할지 여부 ... hub_private_repo = None ... overwrite_output_dir = True # 노트북을 다시 실행할 때 이전 모델에 덮어씌울지 ... seed = 0 >>> config = TrainingConfig() ``` ## 데이터셋 불러오기 🤗 Datasets 라이브러리와 [Smithsonian Butterflies](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) 데이터셋을 쉽게 불러올 수 있습니다. ```py >>> from datasets import load_dataset >>> config.dataset_name = "huggan/smithsonian_butterflies_subset" >>> dataset = load_dataset(config.dataset_name, split="train") ``` 💡[HugGan Community Event](https://huggingface.co/huggan) 에서 추가의 데이터셋을 찾거나 로컬의 [`ImageFolder`](https://huggingface.co/docs/datasets/image_dataset#imagefolder)를 만듦으로써 나만의 데이터셋을 사용할 수 있습니다. HugGan Community Event 에 가져온 데이터셋의 경우 리포지토리의 id로 `config.dataset_name` 을 설정하고, 나만의 이미지를 사용하는 경우 `imagefolder` 를 설정합니다. 🤗 Datasets은 [`~datasets.Image`] 기능을 사용해 자동으로 이미지 데이터를 디코딩하고 [`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html)로 불러옵니다. 이를 시각화 해보면: ```py >>> import matplotlib.pyplot as plt >>> fig, axs = plt.subplots(1, 4, figsize=(16, 4)) >>> for i, image in enumerate(dataset[:4]["image"]): ... axs[i].imshow(image) ... axs[i].set_axis_off() >>> fig.show() ``` ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_ds.png) 이미지는 모두 다른 사이즈이기 때문에, 우선 전처리가 필요합니다: - `Resize` 는 `config.image_size` 에 정의된 이미지 사이즈로 변경합니다. - `RandomHorizontalFlip` 은 랜덤적으로 이미지를 미러링하여 데이터셋을 보강합니다. - `Normalize` 는 모델이 예상하는 [-1, 1] 범위로 픽셀 값을 재조정 하는데 중요합니다. ```py >>> from torchvision import transforms >>> preprocess = transforms.Compose( ... [ ... transforms.Resize((config.image_size, config.image_size)), ... transforms.RandomHorizontalFlip(), ... transforms.ToTensor(), ... transforms.Normalize([0.5], [0.5]), ... ] ... ) ``` 학습 도중에 `preprocess` 함수를 적용하려면 🤗 Datasets의 [`~datasets.Dataset.set_transform`] 방법이 사용됩니다. ```py >>> def transform(examples): ... images = [preprocess(image.convert("RGB")) for image in examples["image"]] ... return {"images": images} >>> dataset.set_transform(transform) ``` 이미지의 크기가 조정되었는지 확인하기 위해 이미지를 다시 시각화해보세요. 이제 [DataLoader](https://pytorch.org/docs/stable/data#torch.utils.data.DataLoader)에 데이터셋을 포함해 학습할 준비가 되었습니다! ```py >>> import torch >>> train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True) ``` ## UNet2DModel 생성하기 🧨 Diffusers에 사전학습된 모델들은 모델 클래스에서 원하는 파라미터로 쉽게 생성할 수 있습니다. 예를 들어, [`UNet2DModel`]를 생성하려면: ```py >>> from diffusers import UNet2DModel >>> model = UNet2DModel( ... sample_size=config.image_size, # 타겟 이미지 해상도 ... in_channels=3, # 입력 채널 수, RGB 이미지에서 3 ... out_channels=3, # 출력 채널 수 ... layers_per_block=2, # UNet 블럭당 몇 개의 ResNet 레이어가 사용되는지 ... block_out_channels=(128, 128, 256, 256, 512, 512), # 각 UNet 블럭을 위한 출력 채널 수 ... down_block_types=( ... "DownBlock2D", # 일반적인 ResNet 다운샘플링 블럭 ... "DownBlock2D", ... "DownBlock2D", ... "DownBlock2D", ... "AttnDownBlock2D", # spatial self-attention이 포함된 일반적인 ResNet 다운샘플링 블럭 ... "DownBlock2D", ... ), ... up_block_types=( ... "UpBlock2D", # 일반적인 ResNet 업샘플링 블럭 ... "AttnUpBlock2D", # spatial self-attention이 포함된 일반적인 ResNet 업샘플링 블럭 ... "UpBlock2D", ... "UpBlock2D", ... "UpBlock2D", ... "UpBlock2D", ... ), ... ) ``` 샘플의 이미지 크기와 모델 출력 크기가 맞는지 빠르게 확인하기 위한 좋은 아이디어가 있습니다: ```py >>> sample_image = dataset[0]["images"].unsqueeze(0) >>> print("Input shape:", sample_image.shape) Input shape: torch.Size([1, 3, 128, 128]) >>> print("Output shape:", model(sample_image, timestep=0).sample.shape) Output shape: torch.Size([1, 3, 128, 128]) ``` 훌륭해요! 다음, 이미지에 약간의 노이즈를 더하기 위해 스케줄러가 필요합니다. ## 스케줄러 생성하기 스케줄러는 모델을 학습 또는 추론에 사용하는지에 따라 다르게 작동합니다. 추론시에, 스케줄러는 노이즈로부터 이미지를 생성합니다. 학습시 스케줄러는 diffusion 과정에서의 특정 포인트로부터 모델의 출력 또는 샘플을 가져와 *노이즈 스케줄* 과 *업데이트 규칙*에 따라 이미지에 노이즈를 적용합니다. `DDPMScheduler`를 보면 이전으로부터 `sample_image`에 랜덤한 노이즈를 더하는 `add_noise` 메서드를 사용합니다: ```py >>> import torch >>> from PIL import Image >>> from diffusers import DDPMScheduler >>> noise_scheduler = DDPMScheduler(num_train_timesteps=1000) >>> noise = torch.randn(sample_image.shape) >>> timesteps = torch.LongTensor([50]) >>> noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps) >>> Image.fromarray(((noisy_image.permute(0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0]) ``` ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/noisy_butterfly.png) 모델의 학습 목적은 이미지에 더해진 노이즈를 예측하는 것입니다. 이 단계에서 손실은 다음과 같이 계산될 수 있습니다: ```py >>> import torch.nn.functional as F >>> noise_pred = model(noisy_image, timesteps).sample >>> loss = F.mse_loss(noise_pred, noise) ``` ## 모델 학습하기 지금까지, 모델 학습을 시작하기 위해 많은 부분을 갖추었으며 이제 남은 것은 모든 것을 조합하는 것입니다. 우선 옵티마이저(optimizer)와 학습률 스케줄러(learning rate scheduler)가 필요할 것입니다: ```py >>> from diffusers.optimization import get_cosine_schedule_with_warmup >>> optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate) >>> lr_scheduler = get_cosine_schedule_with_warmup( ... optimizer=optimizer, ... num_warmup_steps=config.lr_warmup_steps, ... num_training_steps=(len(train_dataloader) * config.num_epochs), ... ) ``` 그 후, 모델을 평가하는 방법이 필요합니다. 평가를 위해, `DDPMPipeline`을 사용해 배치의 이미지 샘플들을 생성하고 그리드 형태로 저장할 수 있습니다: ```py >>> from diffusers import DDPMPipeline >>> import math >>> import os >>> def make_grid(images, rows, cols): ... w, h = images[0].size ... grid = Image.new("RGB", size=(cols * w, rows * h)) ... for i, image in enumerate(images): ... grid.paste(image, box=(i % cols * w, i // cols * h)) ... return grid >>> def evaluate(config, epoch, pipeline): ... # 랜덤한 노이즈로 부터 이미지를 추출합니다.(이는 역전파 diffusion 과정입니다.) ... # 기본 파이프라인 출력 형태는 `List[PIL.Image]` 입니다. ... images = pipeline( ... batch_size=config.eval_batch_size, ... generator=torch.manual_seed(config.seed), ... ).images ... # 이미지들을 그리드로 만들어줍니다. ... image_grid = make_grid(images, rows=4, cols=4) ... # 이미지들을 저장합니다. ... test_dir = os.path.join(config.output_dir, "samples") ... os.makedirs(test_dir, exist_ok=True) ... image_grid.save(f"{test_dir}/{epoch:04d}.png") ``` TensorBoard에 로깅, 그래디언트 누적 및 혼합 정밀도 학습을 쉽게 수행하기 위해 🤗 Accelerate를 학습 루프에 함께 앞서 말한 모든 구성 정보들을 묶어 진행할 수 있습니다. 허브에 모델을 업로드 하기 위해 리포지토리 이름 및 정보를 가져오기 위한 함수를 작성하고 허브에 업로드할 수 있습니다. 💡아래의 학습 루프는 어렵고 길어 보일 수 있지만, 나중에 한 줄의 코드로 학습을 한다면 그만한 가치가 있을 것입니다! 만약 기다리지 못하고 이미지를 생성하고 싶다면, 아래 코드를 자유롭게 붙여넣고 작동시키면 됩니다. 🤗 ```py >>> from accelerate import Accelerator >>> from huggingface_hub import create_repo, upload_folder >>> from tqdm.auto import tqdm >>> from pathlib import Path >>> import os >>> def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler): ... # Initialize accelerator and tensorboard logging ... accelerator = Accelerator( ... mixed_precision=config.mixed_precision, ... gradient_accumulation_steps=config.gradient_accumulation_steps, ... log_with="tensorboard", ... project_dir=os.path.join(config.output_dir, "logs"), ... ) ... if accelerator.is_main_process: ... if config.output_dir is not None: ... os.makedirs(config.output_dir, exist_ok=True) ... if config.push_to_hub: ... repo_id = create_repo( ... repo_id=config.hub_model_id or Path(config.output_dir).name, exist_ok=True ... ).repo_id ... accelerator.init_trackers("train_example") ... # 모든 것이 준비되었습니다. ... # 기억해야 할 특정한 순서는 없으며 준비한 방법에 제공한 것과 동일한 순서로 객체의 압축을 풀면 됩니다. ... model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( ... model, optimizer, train_dataloader, lr_scheduler ... ) ... global_step = 0 ... # 이제 모델을 학습합니다. ... for epoch in range(config.num_epochs): ... progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process) ... progress_bar.set_description(f"Epoch {epoch}") ... for step, batch in enumerate(train_dataloader): ... clean_images = batch["images"] ... # 이미지에 더할 노이즈를 샘플링합니다. ... noise = torch.randn(clean_images.shape, device=clean_images.device) ... bs = clean_images.shape[0] ... # 각 이미지를 위한 랜덤한 타임스텝(timestep)을 샘플링합니다. ... timesteps = torch.randint( ... 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device, ... dtype=torch.int64 ... ) ... # 각 타임스텝의 노이즈 크기에 따라 깨끗한 이미지에 노이즈를 추가합니다. ... # (이는 foward diffusion 과정입니다.) ... noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) ... with accelerator.accumulate(model): ... # 노이즈를 반복적으로 예측합니다. ... noise_pred = model(noisy_images, timesteps, return_dict=False)[0] ... loss = F.mse_loss(noise_pred, noise) ... accelerator.backward(loss) ... accelerator.clip_grad_norm_(model.parameters(), 1.0) ... optimizer.step() ... lr_scheduler.step() ... optimizer.zero_grad() ... progress_bar.update(1) ... logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step} ... progress_bar.set_postfix(**logs) ... accelerator.log(logs, step=global_step) ... global_step += 1 ... # 각 에포크가 끝난 후 evaluate()와 몇 가지 데모 이미지를 선택적으로 샘플링하고 모델을 저장합니다. ... if accelerator.is_main_process: ... pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler) ... if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1: ... evaluate(config, epoch, pipeline) ... if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1: ... if config.push_to_hub: ... upload_folder( ... repo_id=repo_id, ... folder_path=config.output_dir, ... commit_message=f"Epoch {epoch}", ... ignore_patterns=["step_*", "epoch_*"], ... ) ... else: ... pipeline.save_pretrained(config.output_dir) ``` 휴, 코드가 꽤 많았네요! 하지만 🤗 Accelerate의 [`~accelerate.notebook_launcher`] 함수와 학습을 시작할 준비가 되었습니다. 함수에 학습 루프, 모든 학습 인수, 학습에 사용할 프로세스 수(사용 가능한 GPU의 수를 변경할 수 있음)를 전달합니다: ```py >>> from accelerate import notebook_launcher >>> args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler) >>> notebook_launcher(train_loop, args, num_processes=1) ``` 한번 학습이 완료되면, diffusion 모델로 생성된 최종 🦋이미지🦋를 확인해보길 바랍니다! ```py >>> import glob >>> sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png")) >>> Image.open(sample_images[-1]) ``` ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_final.png) ## 다음 단계 Unconditional 이미지 생성은 학습될 수 있는 작업 중 하나의 예시입니다. 다른 작업과 학습 방법은 [🧨 Diffusers 학습 예시](../training/overview) 페이지에서 확인할 수 있습니다. 다음은 학습할 수 있는 몇 가지 예시입니다: - [Textual Inversion](../training/text_inversion), 특정 시각적 개념을 학습시켜 생성된 이미지에 통합시키는 알고리즘입니다. - [DreamBooth](../training/dreambooth), 주제에 대한 몇 가지 입력 이미지들이 주어지면 주제에 대한 개인화된 이미지를 생성하기 위한 기술입니다. - [Guide](../training/text2image) 데이터셋에 Stable Diffusion 모델을 파인튜닝하는 방법입니다. - [Guide](../training/lora) LoRA를 사용해 매우 큰 모델을 빠르게 파인튜닝하기 위한 메모리 효율적인 기술입니다.
diffusers/docs/source/ko/tutorials/basic_training.md/0
{ "file_path": "diffusers/docs/source/ko/tutorials/basic_training.md", "repo_id": "diffusers", "token_count": 11282 }
131
<!--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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Shap-E [[open-in-colab]] Shap-E는 비디오 게임 개발, 인테리어 디자인, 건축에 사용할 수 있는 3D 에셋을 생성하기 위한 conditional 모델입니다. 대규모 3D 에셋 데이터셋을 학습되었고, 각 오브젝트의 더 많은 뷰를 렌더링하고 4K point cloud 대신 16K를 생성하도록 후처리합니다. Shap-E 모델은 두 단계로 학습됩니다: 1. 인코더가 3D 에셋의 포인트 클라우드와 렌더링된 뷰를 받아들이고 에셋을 나타내는 implicit functions의 파라미터를 출력합니다. 2. 인코더가 생성한 latents를 바탕으로 diffusion 모델을 훈련하여 neural radiance fields(NeRF) 또는 textured 3D 메시를 생성하여 다운스트림 애플리케이션에서 3D 에셋을 더 쉽게 렌더링하고 사용할 수 있도록 합니다. 이 가이드에서는 Shap-E를 사용하여 나만의 3D 에셋을 생성하는 방법을 보입니다! 시작하기 전에 다음 라이브러리가 설치되어 있는지 확인하세요: ```py # Colab에서 필요한 라이브러리를 설치하기 위해 주석을 제외하세요 #!pip install -q diffusers transformers accelerate trimesh ``` ## Text-to-3D 3D 객체의 gif를 생성하려면 텍스트 프롬프트를 [`ShapEPipeline`]에 전달합니다. 파이프라인은 3D 객체를 생성하는 데 사용되는 이미지 프레임 리스트를 생성합니다. ```py import torch from diffusers import ShapEPipeline device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16, variant="fp16") pipe = pipe.to(device) guidance_scale = 15.0 prompt = ["A firecracker", "A birthday cupcake"] images = pipe( prompt, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, ).images ``` 이제 [`~utils.export_to_gif`] 함수를 사용하여 이미지 프레임 리스트를 3D 객체의 gif로 변환합니다. ```py from diffusers.utils import export_to_gif export_to_gif(images[0], "firecracker_3d.gif") export_to_gif(images[1], "cake_3d.gif") ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/firecracker_out.gif"/> <figcaption class="mt-2 text-center text-sm text-gray-500">prompt = "A firecracker"</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/cake_out.gif"/> <figcaption class="mt-2 text-center text-sm text-gray-500">prompt = "A birthday cupcake"</figcaption> </div> </div> ## Image-to-3D 다른 이미지로부터 3D 개체를 생성하려면 [`ShapEImg2ImgPipeline`]을 사용합니다. 기존 이미지를 사용하거나 완전히 새로운 이미지를 생성할 수 있습니다. [Kandinsky 2.1](../api/pipelines/kandinsky) 모델을 사용하여 새 이미지를 생성해 보겠습니다. ```py from diffusers import DiffusionPipeline import torch prior_pipeline = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16, use_safetensors=True).to("cuda") pipeline = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16, use_safetensors=True).to("cuda") prompt = "A cheeseburger, white background" image_embeds, negative_image_embeds = prior_pipeline(prompt, guidance_scale=1.0).to_tuple() image = pipeline( prompt, image_embeds=image_embeds, negative_image_embeds=negative_image_embeds, ).images[0] image.save("burger.png") ``` 치즈버거를 [`ShapEImg2ImgPipeline`]에 전달하여 3D representation을 생성합니다. ```py from PIL import Image from diffusers import ShapEImg2ImgPipeline from diffusers.utils import export_to_gif pipe = ShapEImg2ImgPipeline.from_pretrained("openai/shap-e-img2img", torch_dtype=torch.float16, variant="fp16").to("cuda") guidance_scale = 3.0 image = Image.open("burger.png").resize((256, 256)) images = pipe( image, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, ).images gif_path = export_to_gif(images[0], "burger_3d.gif") ``` <div class="flex gap-4"> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/burger_in.png"/> <figcaption class="mt-2 text-center text-sm text-gray-500">cheeseburger</figcaption> </div> <div> <img class="rounded-xl" src="https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/shap_e/burger_out.gif"/> <figcaption class="mt-2 text-center text-sm text-gray-500">3D cheeseburger</figcaption> </div> </div> ## 메시 생성하기 Shap-E는 다운스트림 애플리케이션에 렌더링할 textured 메시 출력을 생성할 수도 있는 유연한 모델입니다. 이 예제에서는 🤗 Datasets 라이브러리에서 [Dataset viewer](https://huggingface.co/docs/hub/datasets-viewer#dataset-preview)를 사용해 메시 시각화를 지원하는 `glb` 파일로 변환합니다. `output_type` 매개변수를 `"mesh"`로 지정함으로써 [`ShapEPipeline`]과 [`ShapEImg2ImgPipeline`] 모두에 대한 메시 출력을 생성할 수 있습니다: ```py import torch from diffusers import ShapEPipeline device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16, variant="fp16") pipe = pipe.to(device) guidance_scale = 15.0 prompt = "A birthday cupcake" images = pipe(prompt, guidance_scale=guidance_scale, num_inference_steps=64, frame_size=256, output_type="mesh").images ``` 메시 출력을 `ply` 파일로 저장하려면 [`~utils.export_to_ply`] 함수를 사용합니다: <Tip> 선택적으로 [`~utils.export_to_obj`] 함수를 사용하여 메시 출력을 `obj` 파일로 저장할 수 있습니다. 다양한 형식으로 메시 출력을 저장할 수 있어 다운스트림에서 더욱 유연하게 사용할 수 있습니다! </Tip> ```py from diffusers.utils import export_to_ply ply_path = export_to_ply(images[0], "3d_cake.ply") print(f"Saved to folder: {ply_path}") ``` 그 다음 trimesh 라이브러리를 사용하여 `ply` 파일을 `glb` 파일로 변환할 수 있습니다: ```py import trimesh mesh = trimesh.load("3d_cake.ply") mesh_export = mesh.export("3d_cake.glb", file_type="glb") ``` 기본적으로 메시 출력은 아래쪽 시점에 초점이 맞춰져 있지만 회전 변환을 적용하여 기본 시점을 변경할 수 있습니다: ```py import trimesh import numpy as np mesh = trimesh.load("3d_cake.ply") rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0]) mesh = mesh.apply_transform(rot) mesh_export = mesh.export("3d_cake.glb", file_type="glb") ``` 메시 파일을 데이터셋 레포지토리에 업로드해 Dataset viewer로 시각화하세요! <div class="flex justify-center"> <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/3D-cake.gif"/> </div>
diffusers/docs/source/ko/using-diffusers/shap-e.md/0
{ "file_path": "diffusers/docs/source/ko/using-diffusers/shap-e.md", "repo_id": "diffusers", "token_count": 4198 }
132
<!--版权 2025 HuggingFace 团队。保留所有权利。 根据 Apache 许可证 2.0 版本("许可证")授权; 除非符合许可证要求,否则不得使用本文件。 您可以在以下网址获取许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,本软件按"原样"分发, 无任何明示或暗示的担保或条件。详见许可证中 的特定语言规定和限制。 --> # 设计哲学 🧨 Diffusers 提供**最先进**的预训练扩散模型支持多模态任务。 其目标是成为推理和训练通用的**模块化工具箱**。 我们致力于构建一个经得起时间考验的库,因此对API设计极为重视。 简而言之,Diffusers 被设计为 PyTorch 的自然延伸。因此,我们的多数设计决策都基于 [PyTorch 设计原则](https://pytorch.org/docs/stable/community/design.html#pytorch-design-philosophy)。以下是核心原则: ## 可用性优先于性能 - 尽管 Diffusers 包含众多性能优化特性(参见[内存与速度优化](https://huggingface.co/docs/diffusers/optimization/fp16)),模型默认总是以最高精度和最低优化级别加载。因此除非用户指定,扩散流程(pipeline)默认在CPU上以float32精度初始化。这确保了跨平台和加速器的可用性,意味着运行本库无需复杂安装。 - Diffusers 追求**轻量化**,仅有少量必需依赖,但提供诸多可选依赖以提升性能(如`accelerate`、`safetensors`、`onnx`等)。我们竭力保持库的轻量级特性,使其能轻松作为其他包的依赖项。 - Diffusers 偏好简单、自解释的代码而非浓缩的"魔法"代码。这意味着lambda函数等简写语法和高级PyTorch操作符通常不被采用。 ## 简洁优于简易 正如PyTorch所言:**显式优于隐式**,**简洁优于复杂**。这一哲学体现在库的多个方面: - 我们遵循PyTorch的API设计,例如使用[`DiffusionPipeline.to`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.to)让用户自主管理设备。 - 明确的错误提示优于静默纠正错误输入。Diffusers 旨在教育用户,而非单纯降低使用难度。 - 暴露复杂的模型与调度器(scheduler)交互逻辑而非内部魔法处理。调度器/采样器与扩散模型分离且相互依赖最小化,迫使用户编写展开的去噪循环。但这种分离便于调试,并赋予用户更多控制权来调整去噪过程或切换模型/调度器。 - 扩散流程中独立训练的组件(如文本编码器、UNet、变分自编码器)各有专属模型类。这要求用户处理组件间交互,且序列化格式将组件分存不同文件。但此举便于调试和定制,得益于组件分离,DreamBooth或Textual Inversion训练变得极为简单。 ## 可定制与贡献友好优于抽象 库的大部分沿用了[Transformers库](https://github.com/huggingface/transformers)的重要设计原则:宁要重复代码,勿要仓促抽象。这一原则与[DRY原则](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)形成鲜明对比。 简言之,正如Transformers对建模文件的做法,Diffusers对流程(pipeline)和调度器(scheduler)保持极低抽象度与高度自包含代码。函数、长代码块甚至类可能在多文件中重复,初看像是糟糕的松散设计。但该设计已被Transformers证明极其成功,对社区驱动的开源机器学习库意义重大: - 机器学习领域发展迅猛,范式、模型架构和算法快速迭代,难以定义长效代码抽象。 - ML从业者常需快速修改现有代码进行研究,因此偏好自包含代码而非多重抽象。 - 开源库依赖社区贡献,必须构建易于参与的代码库。抽象度越高、依赖越复杂、可读性越差,贡献难度越大。过度抽象的库会吓退贡献者。若贡献不会破坏核心功能,不仅吸引新贡献者,也更便于并行审查和修改。 Hugging Face称此设计为**单文件政策**——即某个类的几乎所有代码都应写在单一自包含文件中。更多哲学探讨可参阅[此博文](https://huggingface.co/blog/transformers-design-philosophy)。 Diffusers对流程和调度器完全遵循该哲学,但对diffusion模型仅部分适用。原因在于多数扩散流程(如[DDPM](https://huggingface.co/docs/diffusers/api/pipelines/ddpm)、[Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview#stable-diffusion-pipelines)、[unCLIP (DALL·E 2)](https://huggingface.co/docs/diffusers/api/pipelines/unclip)和[Imagen](https://imagen.research.google/))都基于相同扩散模型——[UNet](https://huggingface.co/docs/diffusers/api/models/unet2d-cond)。 现在您应已理解🧨 Diffusers的设计理念🤗。我们力求在全库贯彻这些原则,但仍存在少数例外或欠佳设计。如有反馈,我们❤️欢迎在[GitHub提交](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=)。 ## 设计哲学细节 现在深入探讨设计细节。Diffusers主要包含三类:[流程(pipeline)](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines)、[模型](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models)和[调度器(scheduler)](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers)。以下是各类的具体设计决策。 ### 流程(Pipelines) 流程设计追求易用性(因此不完全遵循[*简洁优于简易*](#简洁优于简易)),不要求功能完备,应视为使用[模型](#模型)和[调度器](#调度器schedulers)进行推理的示例。 遵循原则: - 采用单文件政策。所有流程位于src/diffusers/pipelines下的独立目录。一个流程文件夹对应一篇扩散论文/项目/发布。如[`src/diffusers/pipelines/stable-diffusion`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/stable_diffusion)可包含多个流程文件。若流程功能相似,可使用[# Copied from机制](https://github.com/huggingface/diffusers/blob/125d783076e5bd9785beb05367a2d2566843a271/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L251)。 - 所有流程继承[`DiffusionPipeline`]。 - 每个流程由不同模型和调度器组件构成,这些组件记录于[`model_index.json`文件](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/model_index.json),可通过同名属性访问,并可用[`DiffusionPipeline.components`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.components)在流程间共享。 - 所有流程应能通过[`DiffusionPipeline.from_pretrained`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.from_pretrained)加载。 - 流程**仅**用于推理。 - 流程代码应具备高可读性、自解释性和易修改性。 - 流程应设计为可相互构建,便于集成到高层API。 - 流程**非**功能完备的用户界面。完整UI推荐[InvokeAI](https://github.com/invoke-ai/InvokeAI)、[Diffuzers](https://github.com/abhishekkrthakur/diffuzers)或[lama-cleaner](https://github.com/Sanster/lama-cleaner)。 - 每个流程应通过唯一的`__call__`方法运行,且参数命名应跨流程统一。 - 流程应以其解决的任务命名。 - 几乎所有新diffusion流程都应在新文件夹/文件中实现。 ### 模型 模型设计为可配置的工具箱,是[PyTorch Module类](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)的自然延伸,仅部分遵循**单文件政策**。 遵循原则: - 模型对应**特定架构类型**。如[`UNet2DConditionModel`]类适用于所有需要2D图像输入且受上下文调节的UNet变体。 - 所有模型位于[`src/diffusers/models`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models),每种架构应有独立文件,如[`unets/unet_2d_condition.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d_condition.py)、[`transformers/transformer_2d.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_2d.py)等。 - 模型**不**采用单文件政策,应使用小型建模模块如[`attention.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py)、[`resnet.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py)、[`embeddings.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py)等。**注意**:这与Transformers的建模文件截然不同,表明模型未完全遵循单文件政策。 - 模型意图暴露复杂度(类似PyTorch的`Module`类),并提供明确错误提示。 - 所有模型继承`ModelMixin`和`ConfigMixin`。 - 当不涉及重大代码变更、保持向后兼容性且显著提升内存/计算效率时,可对模型进行性能优化。 - 模型默认应具备最高精度和最低性能设置。 - 若新模型检查点可归类为现有架构,应适配现有架构而非新建文件。仅当架构根本性不同时才创建新文件。 - 模型设计应便于未来扩展。可通过限制公开函数参数、配置参数和"预见"变更实现。例如:优先采用可扩展的`string`类型参数而非布尔型`is_..._type`参数。对现有架构的修改应保持最小化。 - 模型设计需在代码可读性与多检查点支持间权衡。多数情况下应适配现有类,但某些例外(如[UNet块](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unets/unet_2d_blocks.py)和[注意力处理器](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py))需新建类以保证长期可读性。 ### 调度器(Schedulers) 调度器负责引导推理去噪过程及定义训练噪声计划。它们设计为独立的可加载配置类,严格遵循**单文件政策**。 遵循原则: - 所有调度器位于[`src/diffusers/schedulers`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers)。 - 调度器**禁止**从大型工具文件导入,必须保持高度自包含。 - 一个调度器Python文件对应一种算法(如论文定义的算法)。 - 若调度器功能相似,可使用`# Copied from`机制。 - 所有调度器继承`SchedulerMixin`和`ConfigMixin`。 - 调度器可通过[`ConfigMixin.from_config`](https://huggingface.co/docs/diffusers/main/en/api/configuration#diffusers.ConfigMixin.from_config)轻松切换(详见[此处](../using-diffusers/schedulers))。 - 每个调度器必须包含`set_num_inference_steps`和`step`函数。在每次去噪过程前(即调用`step(...)`前)必须调用`set_num_inference_steps(...)`。 - 每个调度器通过`timesteps`属性暴露需要"循环"的时间步,这是模型将被调用的时间步数组。 - `step(...)`函数接收模型预测输出和"当前"样本(x_t),返回"前一个"略去噪的样本(x_t-1)。 - 鉴于扩散调度器的复杂性,`step`函数不暴露全部细节,可视为"黑盒"。 - 几乎所有新调度器都应在新文件中实现。
diffusers/docs/source/zh/conceptual/philosophy.md/0
{ "file_path": "diffusers/docs/source/zh/conceptual/philosophy.md", "repo_id": "diffusers", "token_count": 6996 }
133
<!-- 版权所有 2025 HuggingFace 团队。保留所有权利。 根据 Apache 许可证 2.0 版本(“许可证”)授权;除非符合许可证,否则不得使用此文件。您可以在以下网址获取许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,否则根据许可证分发的软件按“原样”分发,不附带任何明示或暗示的担保或条件。请参阅许可证以了解具体的语言管理权限和限制。 --> # 缓存 缓存通过存储和重用不同层的中间输出(如注意力层和前馈层)来加速推理,而不是在每个推理步骤执行整个计算。它显著提高了生成速度,但以更多内存为代价,并且不需要额外的训练。 本指南向您展示如何在 Diffusers 中使用支持的缓存方法。 ## 金字塔注意力广播 [金字塔注意力广播 (PAB)](https://huggingface.co/papers/2408.12588) 基于这样一种观察:在生成过程的连续时间步之间,注意力输出差异不大。注意力差异在交叉注意力层中最小,并且通常在一个较长的时间步范围内被缓存。其次是时间注意力和空间注意力层。 > [!TIP] > 并非所有视频模型都有三种类型的注意力(交叉、时间和空间)! PAB 可以与其他技术(如序列并行性和无分类器引导并行性(数据并行性))结合,实现近乎实时的视频生成。 设置并传递一个 [`PyramidAttentionBroadcastConfig`] 到管道的变换器以启用它。`spatial_attention_block_skip_range` 控制跳过空间注意力块中注意力计算的频率,`spatial_attention_timestep_skip_range` 是要跳过的时间步范围。注意选择一个合适的范围,因为较小的间隔可能导致推理速度变慢,而较大的间隔可能导致生成质量降低。 ```python import torch from diffusers import CogVideoXPipeline, PyramidAttentionBroadcastConfig pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16) pipeline.to("cuda") config = PyramidAttentionBroadcastConfig( spatial_attention_block_skip_range=2, spatial_attention_timestep_skip_range=(100, 800), current_timestep_callback=lambda: pipe.current_timestep, ) pipeline.transformer.enable_cache(config) ``` ## FasterCache [FasterCache](https://huggingface.co/papers/2410.19355) 缓存并重用注意力特征,类似于 [PAB](#pyramid-attention-broadcast),因为每个连续时间步的输出差异很小。 此方法在使用无分类器引导进行采样时(在大多数基础模型中常见),也可能选择跳过无条件分支预测,并且 如果连续时间步之间的预测潜在输出存在显著冗余,则从条件分支预测中估计它。 设置并将 [`FasterCacheConfig`] 传递给管道的 transformer 以启用它。 ```python import torch from diffusers import CogVideoXPipeline, FasterCacheConfig pipe line= CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16) pipeline.to("cuda") config = FasterCacheConfig( spatial_attention_block_skip_range=2, spatial_attention_timestep_skip_range=(-1, 681), current_timestep_callback=lambda: pipe.current_timestep, attention_weight_callback=lambda _: 0.3, unconditional_batch_skip_range=5, unconditional_batch_timestep_skip_range=(-1, 781), tensor_format="BFCHW", ) pipeline.transformer.enable_cache(config) ```
diffusers/docs/source/zh/optimization/cache.md/0
{ "file_path": "diffusers/docs/source/zh/optimization/cache.md", "repo_id": "diffusers", "token_count": 2003 }
134
<!--版权归2025年HuggingFace团队所有。保留所有权利。 根据Apache许可证2.0版("许可证")授权;除非符合许可证要求,否则不得使用本文件。您可以在以下网址获取许可证副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律要求或书面同意,本软件按"原样"分发,不附带任何明示或暗示的担保或条件。详见许可证中规定的特定语言及限制条款。 --> # xFormers 我们推荐在推理和训练过程中使用[xFormers](https://github.com/facebookresearch/xformers)。在我们的测试中,其对注意力模块的优化能同时提升运行速度并降低内存消耗。 通过`pip`安装xFormers: ```bash pip install xformers ``` <Tip> xFormers的`pip`安装包需要最新版本的PyTorch。如需使用旧版PyTorch,建议[从源码安装xFormers](https://github.com/facebookresearch/xformers#installing-xformers)。 </Tip> 安装完成后,您可调用`enable_xformers_memory_efficient_attention()`来实现更快的推理速度和更低的内存占用,具体用法参见[此章节](memory#memory-efficient-attention)。 <Tip warning={true}> 根据[此问题](https://github.com/huggingface/diffusers/issues/2234#issuecomment-1416931212)反馈,xFormers `v0.0.16`版本在某些GPU上无法用于训练(微调或DreamBooth)。如遇此问题,请按照该issue评论区指引安装开发版本。 </Tip>
diffusers/docs/source/zh/optimization/xformers.md/0
{ "file_path": "diffusers/docs/source/zh/optimization/xformers.md", "repo_id": "diffusers", "token_count": 866 }
135
<!--- Copyright 2025 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 agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # 🧨 Diffusers Examples Diffusers examples are a collection of scripts to demonstrate how to effectively use the `diffusers` library for a variety of use cases involving training or fine-tuning. **Note**: If you are looking for **official** examples on how to use `diffusers` for inference, please have a look at [src/diffusers/pipelines](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines). Our examples aspire to be **self-contained**, **easy-to-tweak**, **beginner-friendly** and for **one-purpose-only**. More specifically, this means: - **Self-contained**: An example script shall only depend on "pip-install-able" Python packages that can be found in a `requirements.txt` file. Example scripts shall **not** depend on any local files. This means that one can simply download an example script, *e.g.* [train_unconditional.py](https://github.com/huggingface/diffusers/blob/main/examples/unconditional_image_generation/train_unconditional.py), install the required dependencies, *e.g.* [requirements.txt](https://github.com/huggingface/diffusers/blob/main/examples/unconditional_image_generation/requirements.txt) and execute the example script. - **Easy-to-tweak**: While we strive to present as many use cases as possible, the example scripts are just that - examples. It is expected that they won't work out-of-the box on your specific problem and that you will be required to change a few lines of code to adapt them to your needs. To help you with that, most of the examples fully expose the preprocessing of the data and the training loop to allow you to tweak and edit them as required. - **Beginner-friendly**: We do not aim for providing state-of-the-art training scripts for the newest models, but rather examples that can be used as a way to better understand diffusion models and how to use them with the `diffusers` library. We often purposefully leave out certain state-of-the-art methods if we consider them too complex for beginners. - **One-purpose-only**: Examples should show one task and one task only. Even if a task is from a modeling point of view very similar, *e.g.* image super-resolution and image modification tend to use the same model and training method, we want examples to showcase only one task to keep them as readable and easy-to-understand as possible. We provide **official** examples that cover the most popular tasks of diffusion models. *Official* examples are **actively** maintained by the `diffusers` maintainers and we try to rigorously follow our example philosophy as defined above. If you feel like another important example should exist, we are more than happy to welcome a [Feature Request](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feature_request.md&title=) or directly a [Pull Request](https://github.com/huggingface/diffusers/compare) from you! Training examples show how to pretrain or fine-tune diffusion models for a variety of tasks. Currently we support: | Task | 🤗 Accelerate | 🤗 Datasets | Colab |---|---|:---:|:---:| | [**Unconditional Image Generation**](./unconditional_image_generation) | ✅ | ✅ | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) | [**Text-to-Image fine-tuning**](./text_to_image) | ✅ | ✅ | | [**Textual Inversion**](./textual_inversion) | ✅ | - | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_textual_inversion_training.ipynb) | [**Dreambooth**](./dreambooth) | ✅ | - | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_dreambooth_training.ipynb) | [**ControlNet**](./controlnet) | ✅ | ✅ | [Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/controlnet.ipynb) | [**InstructPix2Pix**](./instruct_pix2pix) | ✅ | ✅ | [Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/InstructPix2Pix_using_diffusers.ipynb) | [**Reinforcement Learning for Control**](./reinforcement_learning) | - | - | [Notebook1](https://github.com/huggingface/notebooks/blob/main/diffusers/reinforcement_learning_for_control.ipynb), [Notebook2](https://github.com/huggingface/notebooks/blob/main/diffusers/reinforcement_learning_with_diffusers.ipynb) ## Community In addition, we provide **community** examples, which are examples added and maintained by our community. Community examples can consist of both *training* examples or *inference* pipelines. For such examples, we are more lenient regarding the philosophy defined above and also cannot guarantee to provide maintenance for every issue. Examples that are useful for the community, but are either not yet deemed popular or not yet following our above philosophy should go into the [community examples](https://github.com/huggingface/diffusers/tree/main/examples/community) folder. The community folder therefore includes training examples and inference pipelines. **Note**: Community examples can be a [great first contribution](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) to show to the community how you like to use `diffusers` 🪄. ## Research Projects We also provide **research_projects** examples that are maintained by the community as defined in the respective research project folders. These examples are useful and offer the extended capabilities which are complementary to the official examples. You may refer to [research_projects](https://github.com/huggingface/diffusers/tree/main/examples/research_projects) for details. ## Important note To make sure you can successfully run the latest versions of the example scripts, you have to **install the library from source** and install some example-specific requirements. To do this, execute the following steps in a new virtual environment: ```bash git clone https://github.com/huggingface/diffusers cd diffusers pip install . ``` Then cd in the example folder of your choice and run ```bash pip install -r requirements.txt ```
diffusers/examples/README.md/0
{ "file_path": "diffusers/examples/README.md", "repo_id": "diffusers", "token_count": 1918 }
136