|
| 1 | +use aksr::Builder; |
| 2 | +use anyhow::Result; |
| 3 | +use ndarray::{s, Axis}; |
| 4 | +use rayon::prelude::*; |
| 5 | + |
| 6 | +use crate::{elapsed_module, Config, Engine, Image, LogitsSampler, Processor, Scale, X, Y}; |
| 7 | + |
| 8 | +#[derive(Debug, Builder)] |
| 9 | +pub struct FastVLM { |
| 10 | + vision: Engine, |
| 11 | + text_embed: Engine, |
| 12 | + decoder: Engine, |
| 13 | + scale: Scale, |
| 14 | + image_token: String, |
| 15 | + bos_token: String, |
| 16 | + eos_token: String, |
| 17 | + bos_token_id: u32, |
| 18 | + eos_token_id: u32, |
| 19 | + image_token_id: u32, |
| 20 | + max_length: usize, |
| 21 | + num_hidden_layers: usize, |
| 22 | + head_dim: usize, |
| 23 | + num_key_value_heads: usize, |
| 24 | + num_attention_heads: usize, |
| 25 | + hidden_size: usize, |
| 26 | + batch: usize, |
| 27 | + width: usize, |
| 28 | + height: usize, |
| 29 | + processor: Processor, |
| 30 | +} |
| 31 | + |
| 32 | +impl FastVLM { |
| 33 | + pub fn new(config: Config) -> Result<Self> { |
| 34 | + let vision = Engine::try_from_config(&config.visual)?; |
| 35 | + let text_embed = Engine::try_from_config(&config.textual)?; |
| 36 | + let decoder = Engine::try_from_config(&config.textual_decoder_merged)?; |
| 37 | + let max_length = config.max_tokens.unwrap_or(1024); |
| 38 | + let image_token = "<image>".to_string(); |
| 39 | + let image_token_id = 151646; |
| 40 | + let eos_token = "<|im_end|>".to_string(); |
| 41 | + let eos_token_id = 151645; |
| 42 | + let bos_token = "<|im_start|>".to_string(); |
| 43 | + let bos_token_id = 151644; |
| 44 | + let (num_hidden_layers, head_dim, num_key_value_heads, hidden_size, num_attention_heads) = |
| 45 | + match &config.scale { |
| 46 | + Some(Scale::Billion(0.5)) => (24, 64, 2, 896, 14), |
| 47 | + _ => unimplemented!(), |
| 48 | + }; |
| 49 | + let scale = config |
| 50 | + .scale |
| 51 | + .clone() |
| 52 | + .ok_or_else(|| anyhow::anyhow!("Scale configuration is required for FastVLM model"))?; |
| 53 | + let (batch, height, width) = ( |
| 54 | + vision.batch().opt(), |
| 55 | + vision.try_height().unwrap_or(&1024.into()).opt(), |
| 56 | + vision.try_width().unwrap_or(&1024.into()).opt(), |
| 57 | + ); |
| 58 | + let processor = Processor::try_from_config(&config.processor)? |
| 59 | + .with_image_width(width as _) |
| 60 | + .with_image_height(height as _); |
| 61 | + |
| 62 | + Ok(Self { |
| 63 | + vision, |
| 64 | + text_embed, |
| 65 | + decoder, |
| 66 | + scale, |
| 67 | + max_length, |
| 68 | + eos_token_id, |
| 69 | + bos_token_id, |
| 70 | + image_token, |
| 71 | + image_token_id, |
| 72 | + num_hidden_layers, |
| 73 | + head_dim, |
| 74 | + num_key_value_heads, |
| 75 | + num_attention_heads, |
| 76 | + hidden_size, |
| 77 | + bos_token, |
| 78 | + eos_token, |
| 79 | + batch, |
| 80 | + height, |
| 81 | + width, |
| 82 | + processor, |
| 83 | + }) |
| 84 | + } |
| 85 | + |
| 86 | + fn encode_images(&mut self, xs: &[Image]) -> Result<X> { |
| 87 | + let ys = self.processor.process_images(xs)?; |
| 88 | + self.batch = xs.len(); |
| 89 | + let ys = self.vision.run(ys.into())?; |
| 90 | + Ok(ys[0].to_owned()) |
| 91 | + } |
| 92 | + |
| 93 | + pub fn forward(&mut self, images: &[Image], text: &str) -> Result<Vec<Y>> { |
| 94 | + let image_embeddings = |
| 95 | + elapsed_module!("FastVLM", "encode-images", self.encode_images(images)?); |
| 96 | + elapsed_module!( |
| 97 | + "FastVLM", |
| 98 | + "generate", |
| 99 | + self.generate(&image_embeddings, text) |
| 100 | + ) |
| 101 | + } |
| 102 | + |
| 103 | + fn generate(&mut self, image_embeddings: &X, text: &str) -> Result<Vec<Y>> { |
| 104 | + let image_seq_len = image_embeddings.dims()[1]; |
| 105 | + |
| 106 | + // prompt |
| 107 | + let prompt = format!("<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<image>\n{}<|im_end|>\n<|im_start|>assistant\n", text); |
| 108 | + let input_ids: Vec<f32> = self.processor.encode_text_ids(&prompt, true)?; |
| 109 | + |
| 110 | + // inputs embeds |
| 111 | + let input_ids_x = X::from(input_ids.clone()) |
| 112 | + .insert_axis(0)? |
| 113 | + .repeat(0, self.batch)?; |
| 114 | + let inputs_embeds0 = self.text_embed.run(input_ids_x.into())?[0].clone(); |
| 115 | + let text_seq_len = inputs_embeds0.dims()[1]; |
| 116 | + // total_sequence_length |
| 117 | + let mut seq_len = text_seq_len + image_seq_len; |
| 118 | + |
| 119 | + // merge |
| 120 | + let mut inputs_embeds = X::zeros(&[self.batch, seq_len, self.hidden_size]); |
| 121 | + let pos = input_ids |
| 122 | + .iter() |
| 123 | + .position(|&x| x == self.image_token_id as f32) |
| 124 | + .unwrap_or(input_ids.len() / 2); |
| 125 | + inputs_embeds |
| 126 | + .slice_mut(s![.., ..pos, ..]) |
| 127 | + .assign(&inputs_embeds0.slice(s![.., ..pos, ..])); |
| 128 | + inputs_embeds |
| 129 | + .slice_mut(s![.., pos..pos + image_seq_len, ..]) |
| 130 | + .assign(&image_embeddings.slice(s![.., ..image_seq_len, ..])); |
| 131 | + if pos < text_seq_len { |
| 132 | + inputs_embeds |
| 133 | + .slice_mut(s![.., pos + image_seq_len.., ..]) |
| 134 | + .assign(&inputs_embeds0.slice(s![.., pos.., ..])); |
| 135 | + } |
| 136 | + |
| 137 | + // position ids |
| 138 | + let mut position_ids = X::from((0..seq_len).map(|x| x as f32).collect::<Vec<f32>>()) |
| 139 | + .insert_axis(0)? |
| 140 | + .repeat(0, self.batch)?; |
| 141 | + |
| 142 | + // past key_values |
| 143 | + let mut past_key_values = |
| 144 | + vec![ |
| 145 | + X::zeros(&[self.batch, self.num_key_value_heads, 0, self.head_dim]); |
| 146 | + self.num_hidden_layers * 2 |
| 147 | + ]; |
| 148 | + |
| 149 | + // token ids |
| 150 | + let mut token_ids: Vec<Vec<u32>> = vec![vec![]; self.batch]; |
| 151 | + let mut finished = vec![false; self.batch]; |
| 152 | + let mut last_tokens: Vec<f32> = vec![0.; self.batch]; |
| 153 | + |
| 154 | + // decode |
| 155 | + let logits_sampler = LogitsSampler::new(); |
| 156 | + for _ in 0..self.max_length { |
| 157 | + // inputs |
| 158 | + let attention_mask = X::ones(&[self.batch, seq_len]); |
| 159 | + let mut xs = vec![inputs_embeds.clone(), attention_mask, position_ids.clone()]; |
| 160 | + for i in 0..self.num_hidden_layers { |
| 161 | + xs.push(past_key_values[i * 2].clone()); |
| 162 | + xs.push(past_key_values[i * 2 + 1].clone()); |
| 163 | + } |
| 164 | + |
| 165 | + // decoder |
| 166 | + let decoder_outputs = self.decoder.run(xs.into())?; |
| 167 | + let logits = &decoder_outputs[0]; |
| 168 | + past_key_values = (1..decoder_outputs.len()) |
| 169 | + .step_by(2) |
| 170 | + .flat_map(|i| [i, i + 1]) |
| 171 | + .map(|i| decoder_outputs[i].clone()) |
| 172 | + .collect(); |
| 173 | + |
| 174 | + // decode each token for each batch· |
| 175 | + for (batch_idx, logit) in logits.axis_iter(Axis(0)).enumerate() { |
| 176 | + if !finished[batch_idx] { |
| 177 | + let token_id = logits_sampler.decode( |
| 178 | + &logit |
| 179 | + .slice(s![-1, ..]) |
| 180 | + .into_owned() |
| 181 | + .into_raw_vec_and_offset() |
| 182 | + .0, |
| 183 | + )?; |
| 184 | + |
| 185 | + // early return |
| 186 | + if token_id == self.eos_token_id { |
| 187 | + finished[batch_idx] = true; |
| 188 | + } else { |
| 189 | + token_ids[batch_idx].push(token_id); |
| 190 | + last_tokens[batch_idx] = token_id as f32; |
| 191 | + } |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + // all finished? |
| 196 | + if finished.iter().all(|&x| x) { |
| 197 | + break; |
| 198 | + } |
| 199 | + |
| 200 | + // inputs embeds for next iteration |
| 201 | + let input_ids_x = X::from(last_tokens.clone()).insert_axis(1)?; |
| 202 | + inputs_embeds = self.text_embed.run(input_ids_x.into())?[0].clone(); |
| 203 | + |
| 204 | + // update position_ids for next iteration |
| 205 | + position_ids = X::from( |
| 206 | + position_ids |
| 207 | + .slice(s![.., -1..]) |
| 208 | + .mapv(|x| x + 1.0) |
| 209 | + .into_owned() |
| 210 | + .into_dyn(), |
| 211 | + ); |
| 212 | + seq_len += 1; |
| 213 | + } |
| 214 | + |
| 215 | + // decode |
| 216 | + let texts = self.processor.decode_tokens_batch(&token_ids, true)?; |
| 217 | + let texts = texts |
| 218 | + .into_par_iter() |
| 219 | + .map(|x| Y::default().with_texts(&[x.into()])) |
| 220 | + .collect::<Vec<_>>(); |
| 221 | + |
| 222 | + Ok(texts) |
| 223 | + } |
| 224 | +} |
0 commit comments