mirror of
https://github.com/huggingface/text-generation-inference.git
synced 2025-04-27 04:52:07 +00:00
* wip
wip
refacto
refacto
Initial setup for CXX binding to TRTLLM
Working FFI call for TGI and TRTLLM backend
Remove unused parameters annd force tokenizer name to be set
Overall build TRTLLM and deps through CMake build system
Enable end to end CMake build
First version loading engines and making it ready for inference
Remembering to check how we can detect support for chunked context
Move to latest TensorRT-LLM version
Specify which default log level to use depending on CMake build type
make leader executor mode working
unconditionally call InitializeBackend on the FFI layer
bind to CUDA::nvml to retrieve compute capabilities at runtime
updated logic and comment to detect cuda compute capabilities
implement the Stream method to send new tokens through a callback
use spdlog release 1.14.1 moving forward
update trtllm to latest version a96cccafcf6365c128f004f779160951f8c0801c
correctly tell cmake to build dependent tensorrt-llm required libraries
create cmake install target to put everything relevant in installation folder
add auth_token CLI argument to provide hf hub authentification token
allow converting huggingface::tokenizers error to TensorRtLlmBackendError
use correct include for spdlog
include guard to build example in cmakelists
working setup of the ffi layer
remove fmt import
use external fmt lib
end to end ffi flow working
make sure to track include/ffi.h to trigger rebuild from cargo
impl the rust backend which currently cannot move the actual computation in background thread
expose shutdown function at ffi layer
impl RwLock scenario for TensorRtLllmBackend
oops missing c++ backend definitions
compute the number of maximum new tokens for each request independently
make sure the context is not dropped in the middle of the async decoding.
remove unnecessary log
add all the necessary plumbery to return the generated content
update invalid doc in cpp file
correctly forward back the log probabilities
remove unneeded scope variable for now
refactor Stream impl for Generation to factorise code
expose the internal missing start/queue timestamp
forward tgi parameters rep/freq penalty
add some more validation about grammar not supported
define a shared struct to hold the result of a decoding step
expose information about potential error happening while decoding
remove logging
add logging in case of decoding error
make sure executor_worker is provided
add initial Dockerfile for TRTLLM backend
add some more information in CMakeLists.txt to correctly install executorWorker
add some more information in CMakeLists.txt to correctly find and install nvrtc wrapper
simplify prebuilt trtllm libraries name definition
do the same name definition stuff for tensorrt_llm_executor_static
leverage pkg-config to probe libraries paths and reuse new install structure from cmake
fix bad copy/past missing nvinfer linkage direction
align all the linker search dependency
add missing pkgconfig folder for MPI in Dockerfile
correctly setup linking search path for runtime layer
fix missing / before tgi lib path
adding missing ld_library_path for cuda stubs in Dockerfile
update tgi entrypoint
commenting out Python part for TensorRT installation
refactored docker image
move to TensorRT-LLM v0.11.0
make docker linter happy with same capitalization rule
fix typo
refactor the compute capabilities detection along with num gpus
update TensorRT-LLM to latest version
update TensorRT install script to latest
update build.rs to link to cuda 12.5
add missing dependant libraries for linking
clean up a bit
install to decoder_attention target
add some custom stuff for nccl linkage
fix envvar CARGO_CFG_TARGET_ARCH set at runtime vs compile time
use std::env::const::ARCH
make sure variable live long enough...
look for cuda 12.5
add some more basic info in README.md
* Rebase.
* Fix autodocs.
* Let's try to enable trtllm backend.
* Ignore backends/v3 by default.
* Fixing client.
* Fix makefile + autodocs.
* Updating the schema thing + redocly.
* Fix trtllm lint.
* Adding pb files ?
* Remove cargo fmt temporarily.
* ?
* Tmp.
* Remove both check + clippy ?
* Backporting telemetry.
* Backporting 457fb0a1
* Remove PB from git.
* Fixing PB with default member backends/client
* update TensorRT-LLM to latest version
* provided None for api_key
* link against libtensorrt_llm and not libtensorrt-llm
---------
Co-authored-by: OlivierDehaene <23298448+OlivierDehaene@users.noreply.github.com>
Co-authored-by: Morgan Funtowicz <morgan@huggingface.co>
261 lines
8.7 KiB
Rust
261 lines
8.7 KiB
Rust
use crate::client::{ClientError, Result};
|
|
/// Multi shard Client
|
|
use crate::client::{Health, ShardInfo};
|
|
|
|
use crate::client::grpc_client::{DecodeTimings, PrefillTimings};
|
|
use crate::client::{
|
|
Batch, CachedBatch, Client, Generation, GrammarType, HealthResponse,
|
|
NextTokenChooserParameters, Request, StoppingCriteriaParameters,
|
|
};
|
|
use crate::client::{Chunk, InfoResponse, Input};
|
|
use async_trait::async_trait;
|
|
use futures::future::join_all;
|
|
use tonic::transport::Uri;
|
|
use tracing::instrument;
|
|
|
|
#[derive(Debug, Clone)]
|
|
/// Text Generation Inference gRPC multi client
|
|
pub struct ShardedClient {
|
|
clients: Vec<Client>,
|
|
}
|
|
|
|
impl ShardedClient {
|
|
fn new(clients: Vec<Client>) -> Self {
|
|
Self { clients }
|
|
}
|
|
|
|
/// Create a new ShardedClient from a master client. The master client will communicate with
|
|
/// the other shards and returns all uris/unix sockets with the `service_discovery` gRPC method.
|
|
async fn from_master_client(mut master_client: Client) -> Result<Self> {
|
|
// Get all uris/unix sockets from the master client
|
|
let uris = master_client.service_discovery().await?;
|
|
let futures = uris.into_iter().map(Client::connect_uds);
|
|
let clients: Result<Vec<Client>> = join_all(futures).await.into_iter().collect();
|
|
Ok(Self::new(clients?))
|
|
}
|
|
|
|
/// Returns a client connected to the given uri
|
|
#[allow(dead_code)]
|
|
pub async fn connect(uri: Uri) -> Result<Self> {
|
|
let master_client = Client::connect(uri).await?;
|
|
Self::from_master_client(master_client).await
|
|
}
|
|
|
|
/// Returns a client connected to the given unix socket
|
|
pub async fn connect_uds(path: String) -> Result<Self> {
|
|
let master_client = Client::connect_uds(path).await?;
|
|
Self::from_master_client(master_client).await
|
|
}
|
|
|
|
/// Get the model info
|
|
#[instrument(skip(self))]
|
|
pub async fn info(&mut self) -> Result<ShardInfo> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| client.info())
|
|
.collect();
|
|
join_all(futures).await.pop().unwrap().map(ShardInfo::from)
|
|
}
|
|
|
|
/// GRPC health check
|
|
#[instrument(skip(self))]
|
|
pub async fn health(&mut self) -> Result<HealthResponse> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| client.health())
|
|
.collect();
|
|
join_all(futures).await.pop().unwrap()
|
|
}
|
|
|
|
/// Clear the past generations cache
|
|
#[instrument(skip(self))]
|
|
pub async fn clear_cache(&mut self, batch_id: Option<u64>) -> Result<()> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| client.clear_cache(batch_id))
|
|
.collect();
|
|
join_all(futures).await.into_iter().collect()
|
|
}
|
|
|
|
/// Filter a cached batch
|
|
#[instrument(skip(self))]
|
|
pub async fn filter_batch(
|
|
&mut self,
|
|
batch_id: u64,
|
|
request_ids: Vec<u64>,
|
|
) -> Result<Option<CachedBatch>> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| Box::pin(client.filter_batch(batch_id, request_ids.clone())))
|
|
.collect();
|
|
// all shards return the same message
|
|
join_all(futures).await.pop().unwrap()
|
|
}
|
|
|
|
/// Warmup on a max size batch
|
|
///
|
|
/// Returns the maximum amount of tokens supported by the hardware
|
|
#[instrument(skip(self))]
|
|
pub async fn warmup(
|
|
&mut self,
|
|
max_input_length: u32,
|
|
max_prefill_tokens: u32,
|
|
max_total_tokens: u32,
|
|
max_batch_size: Option<usize>,
|
|
) -> Result<Option<u32>> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| {
|
|
Box::pin(client.warmup(
|
|
max_input_length,
|
|
max_prefill_tokens,
|
|
max_total_tokens,
|
|
max_batch_size,
|
|
))
|
|
})
|
|
.collect();
|
|
// Take the minimum value
|
|
let results = join_all(futures)
|
|
.await
|
|
.into_iter()
|
|
.collect::<Result<Vec<Option<u32>>>>()?;
|
|
Ok(results.into_iter().flatten().min())
|
|
}
|
|
|
|
/// Generate one token for each request in the given batch
|
|
///
|
|
/// Returns Generation for each request in batch
|
|
/// and the next cached batch
|
|
#[instrument(skip_all, fields(id = & batch.id, size = & batch.size))]
|
|
pub async fn prefill(
|
|
&mut self,
|
|
batch: Batch,
|
|
) -> Result<(Vec<Generation>, Option<CachedBatch>, PrefillTimings)> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| Box::pin(client.prefill(batch.clone())))
|
|
.collect();
|
|
#[allow(clippy::type_complexity)]
|
|
let results: Result<Vec<(Vec<Generation>, Option<CachedBatch>, PrefillTimings)>> =
|
|
join_all(futures).await.into_iter().collect();
|
|
let mut results = results?;
|
|
|
|
let (mut generations, next_batch, mut timings) =
|
|
results.pop().ok_or(ClientError::EmptyResults)?;
|
|
|
|
// Merge generations from different model shards
|
|
for (mut shard_generations, _, shard_timings) in results.into_iter() {
|
|
generations.append(&mut shard_generations);
|
|
// Return the timings of the slowest shard
|
|
if shard_timings.total > timings.total {
|
|
timings = shard_timings;
|
|
}
|
|
}
|
|
Ok((generations, next_batch, timings))
|
|
}
|
|
|
|
/// Generate one token for each request in the given cached batches
|
|
///
|
|
/// Returns Generation for each request in batches
|
|
/// and the next cached batch
|
|
#[instrument(skip_all, fields(size = batches.iter().map(| batch | {batch.size}).sum::< u32 > ()))]
|
|
pub async fn decode(
|
|
&mut self,
|
|
batches: Vec<CachedBatch>,
|
|
) -> Result<(Vec<Generation>, Option<CachedBatch>, DecodeTimings)> {
|
|
let futures: Vec<_> = self
|
|
.clients
|
|
.iter_mut()
|
|
.map(|client| Box::pin(client.decode(batches.clone())))
|
|
.collect();
|
|
#[allow(clippy::type_complexity)]
|
|
let results: Result<Vec<(Vec<Generation>, Option<CachedBatch>, DecodeTimings)>> =
|
|
join_all(futures).await.into_iter().collect();
|
|
let mut results = results?;
|
|
|
|
let (mut generations, next_batch, mut timings) =
|
|
results.pop().ok_or(ClientError::EmptyResults)?;
|
|
|
|
// Merge generations from different model shards
|
|
for (mut shard_generations, _, shard_timings) in results.into_iter() {
|
|
generations.append(&mut shard_generations);
|
|
// Return the timings of the slowest shard
|
|
if shard_timings.total > timings.total {
|
|
timings = shard_timings;
|
|
}
|
|
}
|
|
Ok((generations, next_batch, timings))
|
|
}
|
|
}
|
|
|
|
impl From<InfoResponse> for ShardInfo {
|
|
fn from(value: InfoResponse) -> Self {
|
|
Self {
|
|
requires_padding: value.requires_padding,
|
|
dtype: value.dtype,
|
|
device_type: value.device_type,
|
|
window_size: value.window_size,
|
|
speculate: value.speculate,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl Health for ShardedClient {
|
|
async fn device_health(&self) -> Result<()> {
|
|
self.clone().health().await?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn model_health(&self) -> Result<()> {
|
|
// Dummy batch of 1 token and 1 generated token
|
|
let liveness_request = Request {
|
|
id: u64::MAX,
|
|
inputs: "liveness".to_string(),
|
|
input_chunks: Some(Input {
|
|
chunks: vec![Chunk::Text("liveness".into()).into()],
|
|
}),
|
|
truncate: 10,
|
|
prefill_logprobs: false,
|
|
parameters: Some(NextTokenChooserParameters {
|
|
temperature: 1.0,
|
|
top_k: 0,
|
|
top_p: 1.0,
|
|
typical_p: 1.0,
|
|
do_sample: false,
|
|
seed: 0,
|
|
repetition_penalty: 1.0,
|
|
frequency_penalty: 0.0,
|
|
watermark: false,
|
|
grammar: String::new(),
|
|
grammar_type: GrammarType::None as i32,
|
|
}),
|
|
stopping_parameters: Some(StoppingCriteriaParameters {
|
|
max_new_tokens: 1,
|
|
stop_sequences: vec![],
|
|
ignore_eos_token: false,
|
|
}),
|
|
top_n_tokens: 0,
|
|
// Block 0 is reserved for health checks
|
|
blocks: vec![0],
|
|
slots: (0..16).collect(),
|
|
adapter_id: None,
|
|
};
|
|
let batch = Batch {
|
|
id: u64::MAX,
|
|
requests: vec![liveness_request],
|
|
size: 1,
|
|
max_tokens: 2,
|
|
max_blocks: 1,
|
|
};
|
|
self.clone().prefill(batch).await?;
|
|
Ok(())
|
|
}
|
|
}
|