-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: YdrMaster <[email protected]>
- Loading branch information
Showing
14 changed files
with
209 additions
and
60 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
use common::utok; | ||
use log::LevelFilter; | ||
use simple_logger::SimpleLogger; | ||
use std::{io::ErrorKind::NotFound, path::Path}; | ||
use tokenizer::{Tokenizer, VocabTxt, BPE}; | ||
|
||
pub(crate) fn logger_init(log_level: Option<String>) { | ||
let log = log_level | ||
.and_then(|log| match log.to_lowercase().as_str() { | ||
"off" | "none" => Some(LevelFilter::Off), | ||
"trace" => Some(LevelFilter::Trace), | ||
"debug" => Some(LevelFilter::Debug), | ||
"info" => Some(LevelFilter::Info), | ||
"error" => Some(LevelFilter::Error), | ||
_ => None, | ||
}) | ||
.unwrap_or(LevelFilter::Warn); | ||
SimpleLogger::new().with_level(log).init().unwrap(); | ||
} | ||
|
||
pub(crate) fn tokenizer(path: Option<String>, model_dir: impl AsRef<Path>) -> Box<dyn Tokenizer> { | ||
match path { | ||
Some(path) => match Path::new(&path).extension() { | ||
Some(ext) if ext == "txt" => Box::new(VocabTxt::from_txt_file(path).unwrap()), | ||
Some(ext) if ext == "model" => Box::new(BPE::from_model_file(path).unwrap()), | ||
_ => panic!("Tokenizer file {path:?} not supported"), | ||
}, | ||
None => { | ||
match BPE::from_model_file(model_dir.as_ref().join("tokenizer.model")) { | ||
Ok(bpe) => return Box::new(bpe), | ||
Err(e) if e.kind() == NotFound => {} | ||
Err(e) => panic!("{e:?}"), | ||
} | ||
match VocabTxt::from_txt_file(model_dir.as_ref().join("vocabs.txt")) { | ||
Ok(voc) => return Box::new(voc), | ||
Err(e) if e.kind() == NotFound => {} | ||
Err(e) => panic!("{e:?}"), | ||
} | ||
panic!("Tokenizer file not found"); | ||
} | ||
} | ||
} | ||
|
||
pub(crate) fn argmax<T: PartialOrd>(logits: &[T]) -> utok { | ||
logits | ||
.iter() | ||
.enumerate() | ||
.max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap()) | ||
.unwrap() | ||
.0 as _ | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
use super::ServiceArgs; | ||
use crate::common::{argmax, logger_init, tokenizer}; | ||
use common::upos; | ||
use std::{collections::HashMap, path::Path, time::Instant}; | ||
use tokenizer::Tokenizer; | ||
use transformer_cpu::{model_parameters::Memory, LayerCache, Transformer}; | ||
|
||
pub(super) struct CpuService { | ||
transformer: Transformer, | ||
sessions: HashMap<usize, SessionContext>, | ||
tokenizer: Box<dyn Tokenizer>, | ||
} | ||
|
||
struct SessionContext { | ||
pos: upos, | ||
kv_cache: Vec<LayerCache>, | ||
} | ||
|
||
impl From<ServiceArgs> for CpuService { | ||
fn from(args: ServiceArgs) -> Self { | ||
logger_init(args.log); | ||
|
||
let model_dir = Path::new(&args.model); | ||
|
||
let time = Instant::now(); | ||
let tokenizer = tokenizer(args.tokenizer, &model_dir); | ||
info!("build tokenizer ... {:?}", time.elapsed()); | ||
|
||
let time = Instant::now(); | ||
let model = Box::new(Memory::load_safetensors_from_dir(model_dir).unwrap()); | ||
info!("load model ... {:?}", time.elapsed()); | ||
|
||
let time = Instant::now(); | ||
let transformer = Transformer::new(model); | ||
info!("build transformer ... {:?}", time.elapsed()); | ||
|
||
Self { | ||
transformer, | ||
sessions: HashMap::new(), | ||
tokenizer, | ||
} | ||
} | ||
} | ||
|
||
impl CpuService { | ||
pub fn run(mut self) { | ||
loop { | ||
let id = 0; | ||
let prompt = "The quick brown fox jumps over the lazy dog"; | ||
|
||
let session = self.sessions.entry(id).or_insert_with(|| SessionContext { | ||
pos: 0, | ||
kv_cache: self.transformer.new_cache(), | ||
}); | ||
|
||
let prompt_tokens = self.tokenizer.encode(&prompt.trim()); | ||
let (last, tokens) = prompt_tokens.split_last().expect("prompt is empty"); | ||
if !tokens.is_empty() { | ||
self.transformer | ||
.update(tokens, &mut session.kv_cache, session.pos as _); | ||
session.pos += tokens.len() as upos; | ||
} | ||
|
||
let mut token = *last; | ||
let max_pos = self.transformer.max_seq_len() as upos; | ||
let mut out = String::new(); | ||
while session.pos < max_pos { | ||
let logits = | ||
self.transformer | ||
.forward(token, &mut session.kv_cache, session.pos as _); | ||
let next = argmax(logits); | ||
|
||
token = next; | ||
session.pos += 1; | ||
|
||
out.push_str(&self.tokenizer.decode(next).replace('▁', " ")); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
mod cpu; | ||
#[cfg(detected_cuda)] | ||
mod nvidia; | ||
|
||
#[derive(Args, Default)] | ||
pub(crate) struct ServiceArgs { | ||
/// Model directory. | ||
#[clap(short, long)] | ||
model: String, | ||
/// Tokenizer file. | ||
#[clap(short, long)] | ||
tokenizer: Option<String>, | ||
/// Log level, may be "off", "trace", "debug", "info" or "error". | ||
#[clap(long)] | ||
log: Option<String>, | ||
|
||
/// Use Nvidia GPU. | ||
#[clap(long)] | ||
nvidia: bool, | ||
} | ||
|
||
impl ServiceArgs { | ||
pub fn launch(self) { | ||
if self.nvidia { | ||
#[cfg(detected_cuda)] | ||
{ | ||
nvidia::NvidiaService::from(self).run(); | ||
} | ||
#[cfg(not(detected_cuda))] | ||
{ | ||
panic!("Nvidia GPU is not available"); | ||
} | ||
} else { | ||
cpu::CpuService::from(self).run(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
use super::ServiceArgs; | ||
|
||
pub(super) struct NvidiaService {} | ||
|
||
impl From<ServiceArgs> for NvidiaService { | ||
fn from(_: ServiceArgs) -> Self { | ||
todo!() | ||
} | ||
} | ||
|
||
impl NvidiaService { | ||
pub fn run(self) { | ||
todo!() | ||
} | ||
} |