|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::path::PathBuf; |
| 3 | +use std::sync::RwLock; |
| 4 | + |
| 5 | +use base64::Engine; |
| 6 | +use candle_core::{DType, Device}; |
| 7 | +use candle_nn::VarBuilder; |
| 8 | +use image::ImageFormat; |
| 9 | + |
| 10 | +use crate::embeddings::embed::{EmbedData, EmbeddingResult}; |
| 11 | +use crate::embeddings::local::colpali::{get_images_from_pdf, ColPaliEmbed}; |
| 12 | +use crate::embeddings::select_device; |
| 13 | +use crate::models::idefics3::model::{ColIdefics3Model, Idefics3Config}; |
| 14 | +use crate::{ |
| 15 | + models::idefics3::tensor_processing::Idefics3Processor, |
| 16 | +}; |
| 17 | + |
| 18 | +pub struct ColSmolEmbedder { |
| 19 | + pub model: RwLock<ColIdefics3Model>, |
| 20 | + pub processor: Idefics3Processor, |
| 21 | + pub device: Device, |
| 22 | +} |
| 23 | + |
| 24 | +impl ColSmolEmbedder { |
| 25 | + pub fn new(model_id: &str, revision: Option<&str>) -> Result<Self, anyhow::Error> { |
| 26 | + let api = hf_hub::api::sync::Api::new()?; |
| 27 | + let repo: hf_hub::api::sync::ApiRepo = match revision { |
| 28 | + Some(rev) => api.repo(hf_hub::Repo::with_revision( |
| 29 | + model_id.to_string(), |
| 30 | + hf_hub::RepoType::Model, |
| 31 | + rev.to_string(), |
| 32 | + )), |
| 33 | + None => api.repo(hf_hub::Repo::new( |
| 34 | + model_id.to_string(), |
| 35 | + hf_hub::RepoType::Model, |
| 36 | + )), |
| 37 | + }; |
| 38 | + |
| 39 | + let model_file = repo.get("model.safetensors")?; |
| 40 | + let device = select_device(); |
| 41 | + let dtype = if device.is_cuda() { |
| 42 | + DType::BF16 |
| 43 | + } else { |
| 44 | + DType::F32 |
| 45 | + }; |
| 46 | + |
| 47 | + let vb = unsafe { |
| 48 | + VarBuilder::from_mmaped_safetensors(&[model_file], dtype, &device)? |
| 49 | + }; |
| 50 | + let config_file = repo.get("config.json")?; |
| 51 | + |
| 52 | + let processor = Idefics3Processor::from_pretrained("akshayballal/colSmol-256M-merged")?; |
| 53 | + let config: Idefics3Config = serde_json::from_slice(&std::fs::read(config_file)?)?; |
| 54 | + |
| 55 | + |
| 56 | + let model = ColIdefics3Model::load(&config, false, vb)?; |
| 57 | + |
| 58 | + Ok(Self { |
| 59 | + model: RwLock::new(model), |
| 60 | + processor, |
| 61 | + device, |
| 62 | + }) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl ColPaliEmbed for ColSmolEmbedder { |
| 67 | + fn embed( |
| 68 | + &self, |
| 69 | + text_batch: &[&str], |
| 70 | + batch_size: Option<usize>, |
| 71 | + ) -> Result<Vec<EmbeddingResult>, anyhow::Error> { |
| 72 | + let mut encodings = Vec::new(); |
| 73 | + for mini_text_batch in text_batch.chunks(batch_size.unwrap_or(32)) { |
| 74 | + let (input_ids, attention_mask) = self |
| 75 | + .processor |
| 76 | + .tokenize_batch(mini_text_batch.to_vec(), &self.device)?; |
| 77 | + let batch_encodings = self |
| 78 | + .model |
| 79 | + .write() |
| 80 | + .map_err(|e| anyhow::anyhow!("{}", e))? |
| 81 | + .forward(&input_ids, &attention_mask, &None, &None)? |
| 82 | + .to_dtype(DType::F32)?; |
| 83 | + |
| 84 | + encodings.extend( |
| 85 | + batch_encodings |
| 86 | + .to_vec3::<f32>()? |
| 87 | + .iter() |
| 88 | + .map(|x| EmbeddingResult::MultiVector(x.to_vec())), |
| 89 | + ); |
| 90 | + } |
| 91 | + Ok(encodings) |
| 92 | + } |
| 93 | + |
| 94 | + fn embed_query(&self, query: &str) -> anyhow::Result<Vec<EmbedData>> { |
| 95 | + let (input_ids, attention_mask) = |
| 96 | + self.processor.tokenize_batch(vec![query], &self.device)?; |
| 97 | + |
| 98 | + let encoding = self |
| 99 | + .model |
| 100 | + .write() |
| 101 | + .map_err(|e| anyhow::anyhow!("{}", e))? |
| 102 | + .forward(&input_ids, &attention_mask, &None, &None)? |
| 103 | + .to_dtype(DType::F32)? |
| 104 | + .to_vec3::<f32>()? |
| 105 | + .into_iter() |
| 106 | + .map(|x| EmbeddingResult::MultiVector(x.to_vec())); |
| 107 | + |
| 108 | + Ok(encoding |
| 109 | + .map(|x| EmbedData::new(x.clone(), None, None)) |
| 110 | + .collect::<Vec<_>>()) |
| 111 | + } |
| 112 | + |
| 113 | + fn embed_image( |
| 114 | + &self, |
| 115 | + image_path: PathBuf, |
| 116 | + metadata: Option<HashMap<String, String>>, |
| 117 | + ) -> anyhow::Result<EmbedData> { |
| 118 | + let image = image::open(image_path)?; |
| 119 | + let (input_ids, attention_mask, pixel_values, pixel_attention_mask) = |
| 120 | + self.processor.preprocess(&[image], &self.device)?; |
| 121 | + let encoding = self |
| 122 | + .model |
| 123 | + .write() |
| 124 | + .unwrap() |
| 125 | + .forward( |
| 126 | + &input_ids, |
| 127 | + &attention_mask, |
| 128 | + &Some(pixel_values), |
| 129 | + &pixel_attention_mask, |
| 130 | + )? |
| 131 | + .to_dtype(DType::F32)? |
| 132 | + .to_vec3::<f32>()? |
| 133 | + .into_iter() |
| 134 | + .map(|x| EmbeddingResult::MultiVector(x.to_vec())) |
| 135 | + .collect::<Vec<_>>(); |
| 136 | + |
| 137 | + Ok(EmbedData::new(encoding[0].clone(), None, metadata)) |
| 138 | + } |
| 139 | + |
| 140 | + fn embed_image_batch(&self, image_paths: &[PathBuf]) -> anyhow::Result<Vec<EmbedData>> { |
| 141 | + let images = image_paths |
| 142 | + .iter() |
| 143 | + .map(|path| image::open(path)) |
| 144 | + .collect::<Result<Vec<_>, _>>()?; |
| 145 | + let (input_ids, attention_mask, pixel_values, pixel_attention_mask) = |
| 146 | + self.processor.preprocess(&images, &self.device)?; |
| 147 | + let encodings = self |
| 148 | + .model |
| 149 | + .write() |
| 150 | + .unwrap() |
| 151 | + .forward( |
| 152 | + &input_ids, |
| 153 | + &attention_mask, |
| 154 | + &Some(pixel_values), |
| 155 | + &pixel_attention_mask, |
| 156 | + )? |
| 157 | + .to_dtype(DType::F32)? |
| 158 | + .to_vec3::<f32>()?; |
| 159 | + |
| 160 | + Ok(encodings |
| 161 | + .into_iter() |
| 162 | + .map(|x| EmbedData::new(EmbeddingResult::MultiVector(x), None, None)) |
| 163 | + .collect::<Vec<_>>()) |
| 164 | + } |
| 165 | + fn embed_file(&self, file_path: PathBuf, batch_size: usize) -> anyhow::Result<Vec<EmbedData>> { |
| 166 | + let pages = get_images_from_pdf(&file_path)?; |
| 167 | + let mut embed_data = Vec::new(); |
| 168 | + for (index, batch) in pages.chunks(batch_size).enumerate() { |
| 169 | + let start_page = index * batch_size + 1; |
| 170 | + let end_page = start_page + batch.len(); |
| 171 | + let page_numbers = (start_page..=end_page).collect::<Vec<_>>(); |
| 172 | + let (input_ids, attention_mask, pixel_values, pixel_attention_mask) = |
| 173 | + self.processor.preprocess(batch, &self.device)?; |
| 174 | + |
| 175 | + let image_embeddings = self |
| 176 | + .model |
| 177 | + .write() |
| 178 | + .map_err(|e| anyhow::anyhow!("{}", e))? |
| 179 | + .forward( |
| 180 | + &input_ids, |
| 181 | + &attention_mask, |
| 182 | + &Some(pixel_values), |
| 183 | + &pixel_attention_mask, |
| 184 | + )? |
| 185 | + .to_dtype(DType::F32)? |
| 186 | + .to_vec3::<f32>()? |
| 187 | + .into_iter() |
| 188 | + .map(|x| EmbeddingResult::MultiVector(x.to_vec())); |
| 189 | + |
| 190 | + // zip the embeddings with the page numbers |
| 191 | + let embed_data_batch = image_embeddings |
| 192 | + .zip(page_numbers.into_iter()) |
| 193 | + .zip(batch.iter()) |
| 194 | + .map(|((embedding, page_number), page_image)| { |
| 195 | + let mut metadata = HashMap::new(); |
| 196 | + |
| 197 | + let mut buf = Vec::new(); |
| 198 | + let mut cursor = std::io::Cursor::new(&mut buf); |
| 199 | + page_image.write_to(&mut cursor, ImageFormat::Png).unwrap(); |
| 200 | + let engine = base64::engine::general_purpose::STANDARD; |
| 201 | + let base64_image = engine.encode(&buf); |
| 202 | + |
| 203 | + metadata.insert("page_number".to_string(), page_number.to_string()); |
| 204 | + metadata.insert( |
| 205 | + "file_path".to_string(), |
| 206 | + file_path.to_str().unwrap_or("").to_string(), |
| 207 | + ); |
| 208 | + metadata.insert("image".to_string(), base64_image); |
| 209 | + EmbedData::new(embedding, None, Some(metadata)) |
| 210 | + }); |
| 211 | + embed_data.extend(embed_data_batch); |
| 212 | + } |
| 213 | + Ok(embed_data) |
| 214 | + } |
| 215 | +} |
0 commit comments