|
| 1 | +use serde_json::Value; |
| 2 | +use std::collections::HashMap; |
| 3 | +use std::env; |
| 4 | +use std::io; |
| 5 | +use wasmedge_wasi_nn::{ |
| 6 | + self, BackendError, Error, ExecutionTarget, GraphBuilder, GraphEncoding, GraphExecutionContext, |
| 7 | + TensorType, |
| 8 | +}; |
| 9 | + |
| 10 | +fn read_input() -> String { |
| 11 | + loop { |
| 12 | + let mut answer = String::new(); |
| 13 | + io::stdin() |
| 14 | + .read_line(&mut answer) |
| 15 | + .expect("Failed to read line"); |
| 16 | + if !answer.is_empty() && answer != "\n" && answer != "\r\n" { |
| 17 | + return answer.trim().to_string(); |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +fn get_options_from_env() -> HashMap<&'static str, Value> { |
| 23 | + let mut options = HashMap::new(); |
| 24 | + |
| 25 | + // Required parameters for llava |
| 26 | + if let Ok(val) = env::var("mmproj") { |
| 27 | + options.insert("mmproj", Value::from(val.as_str())); |
| 28 | + } else { |
| 29 | + eprintln!("Failed to get mmproj model."); |
| 30 | + std::process::exit(1); |
| 31 | + } |
| 32 | + if let Ok(val) = env::var("image") { |
| 33 | + options.insert("image", Value::from(val.as_str())); |
| 34 | + } else { |
| 35 | + eprintln!("Failed to get the target image."); |
| 36 | + std::process::exit(1); |
| 37 | + } |
| 38 | + |
| 39 | + // Optional parameters |
| 40 | + if let Ok(val) = env::var("enable_log") { |
| 41 | + options.insert("enable-log", serde_json::from_str(val.as_str()).unwrap()); |
| 42 | + } else { |
| 43 | + options.insert("enable-log", Value::from(false)); |
| 44 | + } |
| 45 | + if let Ok(val) = env::var("enable_debug_log") { |
| 46 | + options.insert( |
| 47 | + "enable-debug-log", |
| 48 | + serde_json::from_str(val.as_str()).unwrap(), |
| 49 | + ); |
| 50 | + } else { |
| 51 | + options.insert("enable-debug-log", Value::from(false)); |
| 52 | + } |
| 53 | + if let Ok(val) = env::var("ctx_size") { |
| 54 | + options.insert("ctx-size", serde_json::from_str(val.as_str()).unwrap()); |
| 55 | + } else { |
| 56 | + options.insert("ctx-size", Value::from(4096)); |
| 57 | + } |
| 58 | + if let Ok(val) = env::var("n_gpu_layers") { |
| 59 | + options.insert("n-gpu-layers", serde_json::from_str(val.as_str()).unwrap()); |
| 60 | + } else { |
| 61 | + options.insert("n-gpu-layers", Value::from(0)); |
| 62 | + } |
| 63 | + options |
| 64 | +} |
| 65 | + |
| 66 | +fn set_data_to_context(context: &mut GraphExecutionContext, data: Vec<u8>) -> Result<(), Error> { |
| 67 | + context.set_input(0, TensorType::U8, &[1], &data) |
| 68 | +} |
| 69 | + |
| 70 | +fn get_data_from_context(context: &GraphExecutionContext, index: usize) -> String { |
| 71 | + // Preserve for 4096 tokens with average token length 6 |
| 72 | + const MAX_OUTPUT_BUFFER_SIZE: usize = 4096 * 6; |
| 73 | + let mut output_buffer = vec![0u8; MAX_OUTPUT_BUFFER_SIZE]; |
| 74 | + let mut output_size = context |
| 75 | + .get_output(index, &mut output_buffer) |
| 76 | + .expect("Failed to get output"); |
| 77 | + output_size = std::cmp::min(MAX_OUTPUT_BUFFER_SIZE, output_size); |
| 78 | + |
| 79 | + String::from_utf8_lossy(&output_buffer[..output_size]).to_string() |
| 80 | +} |
| 81 | + |
| 82 | +fn get_output_from_context(context: &GraphExecutionContext) -> String { |
| 83 | + get_data_from_context(context, 0) |
| 84 | +} |
| 85 | + |
| 86 | +fn get_metadata_from_context(context: &GraphExecutionContext) -> Value { |
| 87 | + serde_json::from_str(&get_data_from_context(context, 1)).expect("Failed to get metadata") |
| 88 | +} |
| 89 | + |
| 90 | +fn main() { |
| 91 | + let args: Vec<String> = env::args().collect(); |
| 92 | + let model_name: &str = &args[1]; |
| 93 | + |
| 94 | + // Set options for the graph. Check our README for more details: |
| 95 | + // https://github.com/second-state/WasmEdge-WASINN-examples/tree/master/wasmedge-ggml#parameters |
| 96 | + let options = get_options_from_env(); |
| 97 | + // You could also set the options manually like this: |
| 98 | + |
| 99 | + // Create graph and initialize context. |
| 100 | + let graph = GraphBuilder::new(GraphEncoding::Ggml, ExecutionTarget::AUTO) |
| 101 | + .config(serde_json::to_string(&options).expect("Failed to serialize options")) |
| 102 | + .build_from_cache(model_name) |
| 103 | + .expect("Failed to build graph"); |
| 104 | + let mut context = graph |
| 105 | + .init_execution_context() |
| 106 | + .expect("Failed to init context"); |
| 107 | + |
| 108 | + // If there is a third argument, use it as the prompt and enter non-interactive mode. |
| 109 | + // This is mainly for the CI workflow. |
| 110 | + if args.len() >= 3 { |
| 111 | + let prompt = &args[2]; |
| 112 | + // Set the prompt. |
| 113 | + println!("Prompt:\n{}", prompt); |
| 114 | + let tensor_data = prompt.as_bytes().to_vec(); |
| 115 | + context |
| 116 | + .set_input(0, TensorType::U8, &[1], &tensor_data) |
| 117 | + .expect("Failed to set input"); |
| 118 | + println!("Response:"); |
| 119 | + |
| 120 | + // Get the number of input tokens and llama.cpp versions. |
| 121 | + let input_metadata = get_metadata_from_context(&context); |
| 122 | + println!("[INFO] llama_commit: {}", input_metadata["llama_commit"]); |
| 123 | + println!( |
| 124 | + "[INFO] llama_build_number: {}", |
| 125 | + input_metadata["llama_build_number"] |
| 126 | + ); |
| 127 | + println!( |
| 128 | + "[INFO] Number of input tokens: {}", |
| 129 | + input_metadata["input_tokens"] |
| 130 | + ); |
| 131 | + |
| 132 | + // Get the output. |
| 133 | + context.compute().expect("Failed to compute"); |
| 134 | + let output = get_output_from_context(&context); |
| 135 | + println!("{}", output.trim()); |
| 136 | + |
| 137 | + // Retrieve the output metadata. |
| 138 | + let metadata = get_metadata_from_context(&context); |
| 139 | + println!( |
| 140 | + "[INFO] Number of input tokens: {}", |
| 141 | + metadata["input_tokens"] |
| 142 | + ); |
| 143 | + println!( |
| 144 | + "[INFO] Number of output tokens: {}", |
| 145 | + metadata["output_tokens"] |
| 146 | + ); |
| 147 | + return; |
| 148 | + } |
| 149 | + |
| 150 | + let mut saved_prompt = String::new(); |
| 151 | + let image_placeholder = "<image>"; |
| 152 | + |
| 153 | + loop { |
| 154 | + println!("USER:"); |
| 155 | + let input = read_input(); |
| 156 | + |
| 157 | + // Gemma-3 prompt format: '<start_of_turn>user\n<start_of_image><image><end_of_image>Describe this image<end_of_turn>\n<start_of_turn>model\n' |
| 158 | + if saved_prompt.is_empty() { |
| 159 | + saved_prompt = format!( |
| 160 | + "<start_of_turn>user\n<start_of_image>{}<end_of_image>{}<end_of_turn>\n<start_of_turn>model\n", |
| 161 | + image_placeholder, input |
| 162 | + ); |
| 163 | + } else { |
| 164 | + saved_prompt = format!( |
| 165 | + "{}<start_of_turn>user\n{}<end_of_turn>\n<start_of_turn>model\n", |
| 166 | + saved_prompt, input |
| 167 | + ); |
| 168 | + } |
| 169 | + |
| 170 | + // Set prompt to the input tensor. |
| 171 | + set_data_to_context(&mut context, saved_prompt.as_bytes().to_vec()) |
| 172 | + .expect("Failed to set input"); |
| 173 | + |
| 174 | + // Execute the inference. |
| 175 | + let mut reset_prompt = false; |
| 176 | + match context.compute() { |
| 177 | + Ok(_) => (), |
| 178 | + Err(Error::BackendError(BackendError::ContextFull)) => { |
| 179 | + println!("\n[INFO] Context full, we'll reset the context and continue."); |
| 180 | + reset_prompt = true; |
| 181 | + } |
| 182 | + Err(Error::BackendError(BackendError::PromptTooLong)) => { |
| 183 | + println!("\n[INFO] Prompt too long, we'll reset the context and continue."); |
| 184 | + reset_prompt = true; |
| 185 | + } |
| 186 | + Err(err) => { |
| 187 | + println!("\n[ERROR] {}", err); |
| 188 | + std::process::exit(1); |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + // Retrieve the output. |
| 193 | + let mut output = get_output_from_context(&context); |
| 194 | + println!("ASSISTANT:\n{}", output.trim()); |
| 195 | + |
| 196 | + // Update the saved prompt. |
| 197 | + if reset_prompt { |
| 198 | + saved_prompt.clear(); |
| 199 | + } else { |
| 200 | + output = output.trim().to_string(); |
| 201 | + saved_prompt = format!("{}{}<end_of_turn>\n", saved_prompt, output); |
| 202 | + } |
| 203 | + } |
| 204 | +} |
0 commit comments