Adding Llava-Next (Llava 1.6) with full support. (#1709)
# What does this PR do?
- Changed all models to extract `embed_tokens` in order to enable llava
to separately call the embeddings and the core model layers.
- Added VlmCausalLM to inherit from FlashMistral in order to be
maximally supported. The only added logics sits on top and parses images
into pixel values, preallocates input_ids space for the image
embeddings, and passes them for the model.
- Added Clip for the vision tower.
- Didn't add flash for the vision tower since there's no padding anyway.
- Added heuristic (potentially incomplete) to calculate number of
features *before* calculating the clip patches (allows for easier logic
reuse of the LLM under the hood).
Still needs to be done:
- [x] Implement the image parsing in the controller side, to avoid
downloading n times per TP shard and also refusing requests too large
early and avoid issues where the truncation actually truncates the
image.
- [ ] Make sure it works with quantization properly.
- [x] Make sure it works with TP>1
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-04-09 19:32:00 +00:00
|
|
|
use crate::config::Config;
|
2023-01-31 16:04:00 +00:00
|
|
|
/// HTTP Server logic
|
2023-06-16 14:25:11 +00:00
|
|
|
use crate::health::Health;
|
2024-04-16 13:02:46 +00:00
|
|
|
use crate::infer::{InferError, InferResponse, InferStreamResponse, ToolGrammar};
|
2023-03-09 14:30:54 +00:00
|
|
|
use crate::validation::ValidationError;
|
2022-10-27 12:25:29 +00:00
|
|
|
use crate::{
|
2024-02-29 15:44:20 +00:00
|
|
|
BestOfSequence, Details, ErrorResponse, FinishReason, GenerateParameters, GenerateRequest,
|
|
|
|
GenerateResponse, GrammarType, HubModelInfo, HubTokenizerConfig, Infer, Info, Message,
|
|
|
|
PrefillToken, SimpleToken, StreamDetails, StreamResponse, Token, TokenizeResponse, Usage,
|
|
|
|
Validation,
|
|
|
|
};
|
|
|
|
use crate::{
|
|
|
|
ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionComplete,
|
|
|
|
ChatCompletionDelta, ChatCompletionLogprob, ChatCompletionLogprobs, ChatCompletionTopLogprob,
|
|
|
|
ChatRequest, CompatGenerateRequest, Completion, CompletionComplete, CompletionCompleteChunk,
|
2024-03-29 18:17:24 +00:00
|
|
|
CompletionRequest, DeltaToolCall, Function, Tool, VertexRequest, VertexResponse,
|
2022-10-27 12:25:29 +00:00
|
|
|
};
|
2024-04-16 13:02:46 +00:00
|
|
|
use crate::{FunctionDefinition, ToolCall, ToolType};
|
2022-10-11 16:14:39 +00:00
|
|
|
use axum::extract::Extension;
|
2023-02-17 17:22:00 +00:00
|
|
|
use axum::http::{HeaderMap, Method, StatusCode};
|
2023-01-31 16:04:00 +00:00
|
|
|
use axum::response::sse::{Event, KeepAlive, Sse};
|
2023-03-02 10:41:51 +00:00
|
|
|
use axum::response::{IntoResponse, Response};
|
2022-10-15 18:21:50 +00:00
|
|
|
use axum::routing::{get, post};
|
2023-02-17 17:22:00 +00:00
|
|
|
use axum::{http, Json, Router};
|
2023-09-27 08:40:18 +00:00
|
|
|
use axum_tracing_opentelemetry::middleware::OtelAxumLayer;
|
2024-02-20 13:04:51 +00:00
|
|
|
use futures::stream::FuturesUnordered;
|
2023-04-09 18:22:27 +00:00
|
|
|
use futures::stream::StreamExt;
|
2023-01-31 16:04:00 +00:00
|
|
|
use futures::Stream;
|
2024-02-20 13:04:51 +00:00
|
|
|
use futures::TryStreamExt;
|
2023-04-09 18:13:28 +00:00
|
|
|
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};
|
2024-02-28 10:10:27 +00:00
|
|
|
use serde_json::Value;
|
2023-01-31 16:04:00 +00:00
|
|
|
use std::convert::Infallible;
|
2022-10-14 13:56:21 +00:00
|
|
|
use std::net::SocketAddr;
|
2023-04-26 18:23:54 +00:00
|
|
|
use std::sync::atomic::AtomicBool;
|
|
|
|
use std::sync::Arc;
|
2023-04-21 13:36:29 +00:00
|
|
|
use text_generation_client::{ShardInfo, ShardedClient};
|
2022-10-11 14:50:54 +00:00
|
|
|
use tokenizers::Tokenizer;
|
2022-10-18 13:19:03 +00:00
|
|
|
use tokio::signal;
|
2022-10-11 08:36:51 +00:00
|
|
|
use tokio::time::Instant;
|
2023-02-17 17:22:00 +00:00
|
|
|
use tower_http::cors::{AllowOrigin, CorsLayer};
|
2023-02-13 12:02:45 +00:00
|
|
|
use tracing::{info_span, instrument, Instrument};
|
2023-02-03 11:43:37 +00:00
|
|
|
use utoipa::OpenApi;
|
|
|
|
use utoipa_swagger_ui::SwaggerUi;
|
2022-10-11 08:36:51 +00:00
|
|
|
|
2023-04-18 14:16:06 +00:00
|
|
|
/// Generate tokens if `stream == false` or a stream of token if `stream == true`
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/",
|
|
|
|
request_body = CompatGenerateRequest,
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Generated Text",
|
|
|
|
content(
|
|
|
|
("application/json" = GenerateResponse),
|
|
|
|
("text/event-stream" = StreamResponse),
|
|
|
|
)),
|
|
|
|
(status = 424, description = "Generation Error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Request failed during generation"})),
|
|
|
|
(status = 429, description = "Model is overloaded", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Model is overloaded"})),
|
|
|
|
(status = 422, description = "Input validation error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Input validation error"})),
|
|
|
|
(status = 500, description = "Incomplete generation", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Incomplete generation"})),
|
|
|
|
)
|
2023-04-18 14:16:06 +00:00
|
|
|
)]
|
2023-05-23 18:47:37 +00:00
|
|
|
#[instrument(skip(infer, req))]
|
2023-02-27 13:56:58 +00:00
|
|
|
async fn compat_generate(
|
2023-08-10 08:52:50 +00:00
|
|
|
Extension(default_return_full_text): Extension<bool>,
|
2023-02-27 13:56:58 +00:00
|
|
|
infer: Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
compute_type: Extension<ComputeType>,
|
2023-08-10 08:52:50 +00:00
|
|
|
Json(mut req): Json<CompatGenerateRequest>,
|
2023-03-02 10:41:51 +00:00
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
2023-02-28 09:19:32 +00:00
|
|
|
// default return_full_text given the pipeline_tag
|
|
|
|
if req.parameters.return_full_text.is_none() {
|
2023-08-10 08:52:50 +00:00
|
|
|
req.parameters.return_full_text = Some(default_return_full_text)
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
|
|
|
|
2023-02-27 13:56:58 +00:00
|
|
|
// switch on stream
|
|
|
|
if req.stream {
|
2024-01-29 11:30:50 +00:00
|
|
|
Ok(generate_stream(infer, compute_type, Json(req.into()))
|
2023-02-27 13:56:58 +00:00
|
|
|
.await
|
|
|
|
.into_response())
|
|
|
|
} else {
|
2024-01-29 10:20:08 +00:00
|
|
|
let (headers, Json(generation)) = generate(infer, compute_type, Json(req.into())).await?;
|
2023-02-27 13:56:58 +00:00
|
|
|
// wrap generation inside a Vec to match api-inference
|
2023-08-10 08:52:50 +00:00
|
|
|
Ok((headers, Json(vec![generation])).into_response())
|
2023-02-27 13:56:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-18 14:16:06 +00:00
|
|
|
/// Text Generation Inference endpoint info
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
get,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/info",
|
|
|
|
responses((status = 200, description = "Served model info", body = Info))
|
2023-04-18 14:16:06 +00:00
|
|
|
)]
|
|
|
|
#[instrument]
|
2023-04-25 11:11:18 +00:00
|
|
|
async fn get_model_info(info: Extension<Info>) -> Json<Info> {
|
|
|
|
Json(info.0)
|
2023-04-18 14:16:06 +00:00
|
|
|
}
|
|
|
|
|
2023-04-26 18:23:54 +00:00
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
get,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/health",
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Everything is working fine"),
|
|
|
|
(status = 503, description = "Text generation inference is down", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "unhealthy", "error_type": "healthcheck"})),
|
|
|
|
)
|
2023-04-26 18:23:54 +00:00
|
|
|
)]
|
|
|
|
#[instrument(skip(health))]
|
2022-10-18 13:19:03 +00:00
|
|
|
/// Health check method
|
2023-04-26 18:23:54 +00:00
|
|
|
async fn health(mut health: Extension<Health>) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
|
|
|
|
match health.check().await {
|
|
|
|
true => Ok(()),
|
|
|
|
false => Err((
|
|
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "unhealthy".to_string(),
|
|
|
|
error_type: "healthcheck".to_string(),
|
|
|
|
}),
|
|
|
|
)),
|
|
|
|
}
|
2022-10-14 13:56:21 +00:00
|
|
|
}
|
|
|
|
|
2023-02-03 11:43:37 +00:00
|
|
|
/// Generate tokens
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/generate",
|
|
|
|
request_body = GenerateRequest,
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Generated Text", body = GenerateResponse),
|
|
|
|
(status = 424, description = "Generation Error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Request failed during generation"})),
|
|
|
|
(status = 429, description = "Model is overloaded", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Model is overloaded"})),
|
|
|
|
(status = 422, description = "Input validation error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Input validation error"})),
|
|
|
|
(status = 500, description = "Incomplete generation", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Incomplete generation"})),
|
|
|
|
)
|
2023-02-03 11:43:37 +00:00
|
|
|
)]
|
2022-10-21 14:40:05 +00:00
|
|
|
#[instrument(
|
2023-07-21 14:56:30 +00:00
|
|
|
skip_all,
|
|
|
|
fields(
|
2023-08-10 08:52:50 +00:00
|
|
|
parameters = ? req.parameters,
|
2023-07-21 14:56:30 +00:00
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
2022-10-21 14:40:05 +00:00
|
|
|
)]
|
2022-10-11 08:36:51 +00:00
|
|
|
async fn generate(
|
2023-01-31 16:04:00 +00:00
|
|
|
infer: Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
Extension(ComputeType(compute_type)): Extension<ComputeType>,
|
2023-08-10 08:52:50 +00:00
|
|
|
Json(req): Json<GenerateRequest>,
|
2023-02-27 13:56:58 +00:00
|
|
|
) -> Result<(HeaderMap, Json<GenerateResponse>), (StatusCode, Json<ErrorResponse>)> {
|
2023-01-31 16:04:00 +00:00
|
|
|
let span = tracing::Span::current();
|
2022-10-21 14:40:05 +00:00
|
|
|
let start_time = Instant::now();
|
2023-04-09 18:13:28 +00:00
|
|
|
metrics::increment_counter!("tgi_request_count");
|
2023-01-31 13:21:51 +00:00
|
|
|
|
Adding Llava-Next (Llava 1.6) with full support. (#1709)
# What does this PR do?
- Changed all models to extract `embed_tokens` in order to enable llava
to separately call the embeddings and the core model layers.
- Added VlmCausalLM to inherit from FlashMistral in order to be
maximally supported. The only added logics sits on top and parses images
into pixel values, preallocates input_ids space for the image
embeddings, and passes them for the model.
- Added Clip for the vision tower.
- Didn't add flash for the vision tower since there's no padding anyway.
- Added heuristic (potentially incomplete) to calculate number of
features *before* calculating the clip patches (allows for easier logic
reuse of the LLM under the hood).
Still needs to be done:
- [x] Implement the image parsing in the controller side, to avoid
downloading n times per TP shard and also refusing requests too large
early and avoid issues where the truncation actually truncates the
image.
- [ ] Make sure it works with quantization properly.
- [x] Make sure it works with TP>1
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-04-09 19:32:00 +00:00
|
|
|
// Do not long ultra long inputs, like image payloads.
|
|
|
|
tracing::debug!("Input: {}", &req.inputs[..1000.min(req.inputs.len())]);
|
2023-05-23 18:47:37 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
let compute_characters = req.inputs.chars().count();
|
2023-02-28 09:19:32 +00:00
|
|
|
let mut add_prompt = None;
|
2023-08-10 08:52:50 +00:00
|
|
|
if req.parameters.return_full_text.unwrap_or(false) {
|
|
|
|
add_prompt = Some(req.inputs.clone());
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
|
|
|
|
2023-08-28 09:43:47 +00:00
|
|
|
let details: bool = req.parameters.details || req.parameters.decoder_input_details;
|
2023-02-28 09:19:32 +00:00
|
|
|
|
|
|
|
// Inference
|
2023-08-10 08:52:50 +00:00
|
|
|
let (response, best_of_responses) = match req.parameters.best_of {
|
2023-03-09 14:30:54 +00:00
|
|
|
Some(best_of) if best_of > 1 => {
|
2023-08-10 08:52:50 +00:00
|
|
|
let (response, best_of_responses) = infer.generate_best_of(req, best_of).await?;
|
2023-03-09 14:30:54 +00:00
|
|
|
(response, Some(best_of_responses))
|
|
|
|
}
|
2023-08-10 08:52:50 +00:00
|
|
|
_ => (infer.generate(req).await?, None),
|
2023-03-09 14:30:54 +00:00
|
|
|
};
|
2022-10-17 12:59:00 +00:00
|
|
|
|
2022-12-15 16:03:56 +00:00
|
|
|
// Token details
|
2024-01-11 18:01:43 +00:00
|
|
|
let input_length = response._input_length;
|
2022-12-15 16:03:56 +00:00
|
|
|
let details = match details {
|
2023-03-09 14:30:54 +00:00
|
|
|
true => {
|
|
|
|
// convert best_of_responses
|
|
|
|
let best_of_sequences = best_of_responses.map(|responses: Vec<InferResponse>| {
|
|
|
|
responses
|
|
|
|
.into_iter()
|
|
|
|
.map(|response: InferResponse| {
|
|
|
|
// Add prompt if return_full_text
|
|
|
|
let mut output_text = response.generated_text.text;
|
|
|
|
if let Some(prompt) = &add_prompt {
|
|
|
|
output_text = prompt.clone() + &output_text;
|
|
|
|
}
|
|
|
|
|
|
|
|
BestOfSequence {
|
|
|
|
generated_text: output_text,
|
|
|
|
finish_reason: FinishReason::from(
|
|
|
|
response.generated_text.finish_reason,
|
|
|
|
),
|
|
|
|
generated_tokens: response.generated_text.generated_tokens,
|
|
|
|
prefill: response.prefill,
|
|
|
|
tokens: response.tokens,
|
2023-08-28 09:43:47 +00:00
|
|
|
top_tokens: response.top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
seed: response.generated_text.seed,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect()
|
|
|
|
});
|
|
|
|
|
|
|
|
Some(Details {
|
|
|
|
finish_reason: FinishReason::from(response.generated_text.finish_reason),
|
|
|
|
generated_tokens: response.generated_text.generated_tokens,
|
|
|
|
prefill: response.prefill,
|
|
|
|
tokens: response.tokens,
|
|
|
|
seed: response.generated_text.seed,
|
|
|
|
best_of_sequences,
|
2023-08-28 09:43:47 +00:00
|
|
|
top_tokens: response.top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
})
|
|
|
|
}
|
2022-12-15 16:03:56 +00:00
|
|
|
false => None,
|
|
|
|
};
|
|
|
|
|
2022-10-21 14:40:05 +00:00
|
|
|
// Timings
|
|
|
|
let total_time = start_time.elapsed();
|
|
|
|
let validation_time = response.queued - start_time;
|
|
|
|
let queue_time = response.start - response.queued;
|
2023-01-31 16:04:00 +00:00
|
|
|
let inference_time = Instant::now() - response.start;
|
|
|
|
let time_per_token = inference_time / response.generated_text.generated_tokens;
|
2022-10-21 14:40:05 +00:00
|
|
|
|
2023-04-09 18:13:28 +00:00
|
|
|
// Tracing metadata
|
|
|
|
span.record("total_time", format!("{total_time:?}"));
|
|
|
|
span.record("validation_time", format!("{validation_time:?}"));
|
|
|
|
span.record("queue_time", format!("{queue_time:?}"));
|
|
|
|
span.record("inference_time", format!("{inference_time:?}"));
|
|
|
|
span.record("time_per_token", format!("{time_per_token:?}"));
|
|
|
|
span.record("seed", format!("{:?}", response.generated_text.seed));
|
|
|
|
|
2022-10-21 14:40:05 +00:00
|
|
|
// Headers
|
|
|
|
let mut headers = HeaderMap::new();
|
2024-01-29 10:20:08 +00:00
|
|
|
headers.insert("x-compute-type", compute_type.parse().unwrap());
|
2023-03-02 10:41:51 +00:00
|
|
|
headers.insert(
|
|
|
|
"x-compute-time",
|
2024-02-28 10:30:37 +00:00
|
|
|
total_time.as_secs_f64().to_string().parse().unwrap(),
|
2023-03-02 10:41:51 +00:00
|
|
|
);
|
|
|
|
headers.insert(
|
|
|
|
"x-compute-characters",
|
|
|
|
compute_characters.to_string().parse().unwrap(),
|
|
|
|
);
|
2022-10-21 14:40:05 +00:00
|
|
|
headers.insert(
|
|
|
|
"x-total-time",
|
|
|
|
total_time.as_millis().to_string().parse().unwrap(),
|
|
|
|
);
|
|
|
|
headers.insert(
|
|
|
|
"x-validation-time",
|
|
|
|
validation_time.as_millis().to_string().parse().unwrap(),
|
|
|
|
);
|
|
|
|
headers.insert(
|
|
|
|
"x-queue-time",
|
|
|
|
queue_time.as_millis().to_string().parse().unwrap(),
|
2022-10-17 12:59:00 +00:00
|
|
|
);
|
2022-10-21 14:40:05 +00:00
|
|
|
headers.insert(
|
|
|
|
"x-inference-time",
|
|
|
|
inference_time.as_millis().to_string().parse().unwrap(),
|
|
|
|
);
|
|
|
|
headers.insert(
|
|
|
|
"x-time-per-token",
|
|
|
|
time_per_token.as_millis().to_string().parse().unwrap(),
|
|
|
|
);
|
2024-01-11 18:01:43 +00:00
|
|
|
headers.insert("x-prompt-tokens", input_length.into());
|
|
|
|
headers.insert(
|
|
|
|
"x-generated-tokens",
|
|
|
|
response.generated_text.generated_tokens.into(),
|
|
|
|
);
|
2022-10-21 14:40:05 +00:00
|
|
|
|
2023-02-16 16:18:53 +00:00
|
|
|
// Metrics
|
|
|
|
metrics::increment_counter!("tgi_request_success");
|
2023-04-09 18:13:28 +00:00
|
|
|
metrics::histogram!("tgi_request_duration", total_time.as_secs_f64());
|
|
|
|
metrics::histogram!(
|
|
|
|
"tgi_request_validation_duration",
|
|
|
|
validation_time.as_secs_f64()
|
|
|
|
);
|
|
|
|
metrics::histogram!("tgi_request_queue_duration", queue_time.as_secs_f64());
|
|
|
|
metrics::histogram!(
|
|
|
|
"tgi_request_inference_duration",
|
|
|
|
inference_time.as_secs_f64()
|
|
|
|
);
|
|
|
|
metrics::histogram!(
|
|
|
|
"tgi_request_mean_time_per_token_duration",
|
|
|
|
time_per_token.as_secs_f64()
|
|
|
|
);
|
2023-02-16 16:18:53 +00:00
|
|
|
metrics::histogram!(
|
|
|
|
"tgi_request_generated_tokens",
|
|
|
|
response.generated_text.generated_tokens as f64
|
|
|
|
);
|
|
|
|
|
2022-10-18 13:19:03 +00:00
|
|
|
// Send response
|
2023-02-28 09:19:32 +00:00
|
|
|
let mut output_text = response.generated_text.text;
|
|
|
|
if let Some(prompt) = add_prompt {
|
|
|
|
output_text = prompt + &output_text;
|
|
|
|
}
|
|
|
|
|
2023-05-23 18:47:37 +00:00
|
|
|
tracing::debug!("Output: {}", output_text);
|
|
|
|
tracing::info!("Success");
|
2023-04-09 18:13:28 +00:00
|
|
|
|
2023-02-02 14:02:04 +00:00
|
|
|
let response = GenerateResponse {
|
2023-02-28 09:19:32 +00:00
|
|
|
generated_text: output_text,
|
2022-12-15 16:03:56 +00:00
|
|
|
details,
|
2023-02-02 14:02:04 +00:00
|
|
|
};
|
2022-10-21 14:40:05 +00:00
|
|
|
Ok((headers, Json(response)))
|
2022-10-11 08:36:51 +00:00
|
|
|
}
|
|
|
|
|
2023-02-08 21:30:11 +00:00
|
|
|
/// Generate a stream of token using Server-Sent Events
|
2023-02-03 11:43:37 +00:00
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/generate_stream",
|
|
|
|
request_body = GenerateRequest,
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Generated Text", body = StreamResponse,
|
|
|
|
content_type = "text/event-stream"),
|
|
|
|
(status = 424, description = "Generation Error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Request failed during generation"}),
|
|
|
|
content_type = "text/event-stream"),
|
|
|
|
(status = 429, description = "Model is overloaded", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Model is overloaded"}),
|
|
|
|
content_type = "text/event-stream"),
|
|
|
|
(status = 422, description = "Input validation error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Input validation error"}),
|
|
|
|
content_type = "text/event-stream"),
|
|
|
|
(status = 500, description = "Incomplete generation", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Incomplete generation"}),
|
|
|
|
content_type = "text/event-stream"),
|
|
|
|
)
|
2023-02-03 11:43:37 +00:00
|
|
|
)]
|
2023-01-31 16:04:00 +00:00
|
|
|
#[instrument(
|
2023-07-21 14:56:30 +00:00
|
|
|
skip_all,
|
|
|
|
fields(
|
2023-08-10 08:52:50 +00:00
|
|
|
parameters = ? req.parameters,
|
2023-07-21 14:56:30 +00:00
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
2023-01-31 16:04:00 +00:00
|
|
|
)]
|
|
|
|
async fn generate_stream(
|
2023-08-10 08:52:50 +00:00
|
|
|
Extension(infer): Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
2023-08-10 08:52:50 +00:00
|
|
|
Json(req): Json<GenerateRequest>,
|
2023-03-02 10:41:51 +00:00
|
|
|
) -> (
|
|
|
|
HeaderMap,
|
|
|
|
Sse<impl Stream<Item = Result<Event, Infallible>>>,
|
|
|
|
) {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let on_message_callback = |stream_token: StreamResponse| {
|
|
|
|
let event = Event::default();
|
|
|
|
event.json_data(stream_token).unwrap()
|
|
|
|
};
|
|
|
|
let (headers, response_stream) =
|
2024-01-29 10:20:08 +00:00
|
|
|
generate_stream_internal(infer, compute_type, Json(req), on_message_callback).await;
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
|
|
|
|
(headers, sse)
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn generate_stream_internal(
|
|
|
|
infer: Infer,
|
2024-01-29 10:20:08 +00:00
|
|
|
ComputeType(compute_type): ComputeType,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
Json(req): Json<GenerateRequest>,
|
|
|
|
on_message_callback: impl Fn(StreamResponse) -> Event,
|
|
|
|
) -> (HeaderMap, impl Stream<Item = Result<Event, Infallible>>) {
|
2023-01-31 16:04:00 +00:00
|
|
|
let span = tracing::Span::current();
|
|
|
|
let start_time = Instant::now();
|
2023-04-09 18:13:28 +00:00
|
|
|
metrics::increment_counter!("tgi_request_count");
|
2023-01-31 16:04:00 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
tracing::debug!("Input: {}", req.inputs);
|
2023-05-23 18:47:37 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
let compute_characters = req.inputs.chars().count();
|
2023-03-02 10:41:51 +00:00
|
|
|
|
|
|
|
let mut headers = HeaderMap::new();
|
2024-01-29 11:30:50 +00:00
|
|
|
headers.insert("x-compute-type", compute_type.parse().unwrap());
|
2023-03-02 10:41:51 +00:00
|
|
|
headers.insert(
|
|
|
|
"x-compute-characters",
|
|
|
|
compute_characters.to_string().parse().unwrap(),
|
|
|
|
);
|
2023-06-28 09:50:12 +00:00
|
|
|
headers.insert("X-Accel-Buffering", "no".parse().unwrap());
|
2023-03-02 10:41:51 +00:00
|
|
|
|
2023-01-31 16:04:00 +00:00
|
|
|
let stream = async_stream::stream! {
|
|
|
|
// Inference
|
|
|
|
let mut end_reached = false;
|
|
|
|
let mut error = false;
|
2023-02-28 09:19:32 +00:00
|
|
|
|
|
|
|
let mut add_prompt = None;
|
2023-08-10 08:52:50 +00:00
|
|
|
if req.parameters.return_full_text.unwrap_or(false) {
|
|
|
|
add_prompt = Some(req.inputs.clone());
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
2023-08-10 08:52:50 +00:00
|
|
|
let details = req.parameters.details;
|
2023-01-31 16:04:00 +00:00
|
|
|
|
2023-08-10 08:52:50 +00:00
|
|
|
let best_of = req.parameters.best_of.unwrap_or(1);
|
2023-06-02 15:12:30 +00:00
|
|
|
if best_of != 1 {
|
|
|
|
let err = InferError::from(ValidationError::BestOfStream);
|
|
|
|
metrics::increment_counter!("tgi_request_failure", "err" => "validation");
|
|
|
|
tracing::error!("{err}");
|
|
|
|
yield Ok(Event::from(err));
|
2023-08-10 08:52:50 +00:00
|
|
|
} else if req.parameters.decoder_input_details {
|
2023-06-02 15:12:30 +00:00
|
|
|
let err = InferError::from(ValidationError::PrefillDetailsStream);
|
|
|
|
metrics::increment_counter!("tgi_request_failure", "err" => "validation");
|
|
|
|
tracing::error!("{err}");
|
|
|
|
yield Ok(Event::from(err));
|
|
|
|
} else {
|
2023-08-10 08:52:50 +00:00
|
|
|
match infer.generate_stream(req).instrument(info_span!(parent: &span, "async_stream")).await {
|
2023-04-20 09:07:40 +00:00
|
|
|
// Keep permit as long as generate_stream lives
|
2024-01-11 18:01:43 +00:00
|
|
|
Ok((_permit, _input_length, mut response_stream)) => {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let mut index = 0;
|
2023-03-09 14:30:54 +00:00
|
|
|
// Server-Sent Event stream
|
|
|
|
while let Some(response) = response_stream.next().await {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
index += 1;
|
2023-03-09 14:30:54 +00:00
|
|
|
match response {
|
|
|
|
Ok(response) => {
|
|
|
|
match response {
|
|
|
|
// Prefill is ignored
|
|
|
|
InferStreamResponse::Prefill(_) => {}
|
|
|
|
// Yield event for every new token
|
2023-08-28 09:43:47 +00:00
|
|
|
InferStreamResponse::Intermediate{
|
|
|
|
token,
|
|
|
|
top_tokens,
|
|
|
|
} => {
|
2023-05-23 18:47:37 +00:00
|
|
|
tracing::debug!(parent: &span, "Token: {:?}", token);
|
|
|
|
|
2023-03-09 14:30:54 +00:00
|
|
|
// StreamResponse
|
|
|
|
let stream_token = StreamResponse {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
index,
|
2023-03-09 14:30:54 +00:00
|
|
|
token,
|
2023-09-27 08:40:18 +00:00
|
|
|
top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_text: None,
|
|
|
|
details: None,
|
|
|
|
};
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let event = on_message_callback(stream_token);
|
|
|
|
yield Ok(event);
|
2023-02-28 09:19:32 +00:00
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
// Yield event for last token and compute timings
|
|
|
|
InferStreamResponse::End {
|
2023-01-31 16:04:00 +00:00
|
|
|
token,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_text,
|
|
|
|
start,
|
|
|
|
queued,
|
2023-08-28 09:43:47 +00:00
|
|
|
top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
} => {
|
|
|
|
// Token details
|
|
|
|
let details = match details {
|
|
|
|
true => Some(StreamDetails {
|
|
|
|
finish_reason: FinishReason::from(generated_text.finish_reason),
|
|
|
|
generated_tokens: generated_text.generated_tokens,
|
|
|
|
seed: generated_text.seed,
|
|
|
|
}),
|
|
|
|
false => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Timings
|
|
|
|
let total_time = start_time.elapsed();
|
|
|
|
let validation_time = queued - start_time;
|
|
|
|
let queue_time = start - queued;
|
|
|
|
let inference_time = Instant::now() - start;
|
|
|
|
let time_per_token = inference_time / generated_text.generated_tokens;
|
|
|
|
|
|
|
|
// Tracing metadata
|
|
|
|
span.record("total_time", format!("{total_time:?}"));
|
|
|
|
span.record("validation_time", format!("{validation_time:?}"));
|
|
|
|
span.record("queue_time", format!("{queue_time:?}"));
|
|
|
|
span.record("inference_time", format!("{inference_time:?}"));
|
|
|
|
span.record("time_per_token", format!("{time_per_token:?}"));
|
|
|
|
span.record("seed", format!("{:?}", generated_text.seed));
|
|
|
|
|
|
|
|
// Metrics
|
|
|
|
metrics::increment_counter!("tgi_request_success");
|
2023-04-09 18:13:28 +00:00
|
|
|
metrics::histogram!("tgi_request_duration", total_time.as_secs_f64());
|
|
|
|
metrics::histogram!("tgi_request_validation_duration", validation_time.as_secs_f64());
|
|
|
|
metrics::histogram!("tgi_request_queue_duration", queue_time.as_secs_f64());
|
|
|
|
metrics::histogram!("tgi_request_inference_duration", inference_time.as_secs_f64());
|
|
|
|
metrics::histogram!("tgi_request_mean_time_per_token_duration", time_per_token.as_secs_f64());
|
2023-03-09 14:30:54 +00:00
|
|
|
metrics::histogram!("tgi_request_generated_tokens", generated_text.generated_tokens as f64);
|
|
|
|
|
|
|
|
// StreamResponse
|
|
|
|
end_reached = true;
|
|
|
|
|
|
|
|
let mut output_text = generated_text.text;
|
|
|
|
if let Some(prompt) = add_prompt {
|
|
|
|
output_text = prompt + &output_text;
|
|
|
|
}
|
|
|
|
|
2023-05-23 18:47:37 +00:00
|
|
|
tracing::debug!(parent: &span, "Output: {}", output_text);
|
|
|
|
tracing::info!(parent: &span, "Success");
|
2023-04-09 18:13:28 +00:00
|
|
|
|
2023-03-09 14:30:54 +00:00
|
|
|
let stream_token = StreamResponse {
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
index,
|
2023-03-09 14:30:54 +00:00
|
|
|
token,
|
2023-09-27 08:40:18 +00:00
|
|
|
top_tokens,
|
2023-03-09 14:30:54 +00:00
|
|
|
generated_text: Some(output_text),
|
|
|
|
details
|
|
|
|
};
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
|
|
|
|
let event = on_message_callback(stream_token);
|
|
|
|
yield Ok(event);
|
2023-03-09 14:30:54 +00:00
|
|
|
break;
|
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
// yield error
|
|
|
|
Err(err) => {
|
|
|
|
error = true;
|
|
|
|
yield Ok(Event::from(err));
|
|
|
|
break;
|
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
},
|
|
|
|
// yield error
|
|
|
|
Err(err) => {
|
|
|
|
error = true;
|
|
|
|
yield Ok(Event::from(err));
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
2023-03-09 14:30:54 +00:00
|
|
|
}
|
|
|
|
// Check if generation reached the end
|
|
|
|
// Skip if we already sent an error
|
|
|
|
if !end_reached && !error {
|
|
|
|
let err = InferError::IncompleteGeneration;
|
|
|
|
metrics::increment_counter!("tgi_request_failure", "err" => "incomplete");
|
|
|
|
tracing::error!("{err}");
|
2023-02-28 09:19:32 +00:00
|
|
|
yield Ok(Event::from(err));
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
(headers, stream)
|
|
|
|
}
|
|
|
|
|
2024-02-29 15:44:20 +00:00
|
|
|
/// Generate tokens
|
|
|
|
#[utoipa::path(
|
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/v1/completions",
|
|
|
|
request_body = CompletionRequest,
|
|
|
|
responses(
|
2024-04-16 17:26:32 +00:00
|
|
|
(status = 200, description = "Generated Chat Completion",
|
|
|
|
content(
|
|
|
|
("application/json" = Completion),
|
|
|
|
("text/event-stream" = CompletionCompleteChunk),
|
|
|
|
)),
|
2024-02-29 15:44:20 +00:00
|
|
|
(status = 424, description = "Generation Error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Request failed during generation"})),
|
|
|
|
(status = 429, description = "Model is overloaded", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Model is overloaded"})),
|
|
|
|
(status = 422, description = "Input validation error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Input validation error"})),
|
|
|
|
(status = 500, description = "Incomplete generation", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Incomplete generation"})),
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
#[instrument(
|
|
|
|
skip_all,
|
|
|
|
fields(
|
|
|
|
// parameters = ? req.parameters,
|
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
async fn completions(
|
|
|
|
Extension(infer): Extension<Infer>,
|
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
|
|
|
Extension(info): Extension<Info>,
|
|
|
|
Json(req): Json<CompletionRequest>,
|
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
|
|
|
metrics::increment_counter!("tgi_request_count");
|
|
|
|
|
|
|
|
let stream = req.stream;
|
|
|
|
let max_new_tokens = req.max_tokens.or(Some(100));
|
|
|
|
let seed = req.seed;
|
|
|
|
|
|
|
|
// if suffix is present throw an error
|
|
|
|
if req.suffix.is_some() {
|
|
|
|
metrics::increment_counter!("tgi_request_failure", "err" => "validation");
|
|
|
|
return Err((
|
|
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "Suffix is not supported and can be achieved by preprocessing the prompt."
|
|
|
|
.to_string(),
|
|
|
|
error_type: "suffix not supported".to_string(),
|
|
|
|
}),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
// build the request passing some parameters
|
|
|
|
let generate_request = GenerateRequest {
|
|
|
|
inputs: req.prompt.to_string(),
|
|
|
|
parameters: GenerateParameters {
|
|
|
|
best_of: None,
|
|
|
|
temperature: req.temperature,
|
|
|
|
repetition_penalty: req.repetition_penalty,
|
|
|
|
frequency_penalty: req.frequency_penalty,
|
|
|
|
top_k: None,
|
|
|
|
top_p: req.top_p,
|
|
|
|
typical_p: None,
|
|
|
|
do_sample: true,
|
|
|
|
max_new_tokens,
|
|
|
|
return_full_text: None,
|
|
|
|
stop: Vec::new(),
|
|
|
|
truncate: None,
|
|
|
|
watermark: false,
|
|
|
|
details: true,
|
|
|
|
decoder_input_details: !stream,
|
|
|
|
seed,
|
|
|
|
top_n_tokens: None,
|
|
|
|
grammar: None,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
if stream {
|
|
|
|
let on_message_callback = move |stream_token: StreamResponse| {
|
|
|
|
let event = Event::default();
|
|
|
|
|
|
|
|
let current_time = std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
|
|
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
|
|
|
|
.as_secs();
|
|
|
|
|
|
|
|
event
|
|
|
|
.json_data(CompletionCompleteChunk {
|
|
|
|
id: "".to_string(),
|
|
|
|
object: "text_completion".to_string(),
|
|
|
|
created: current_time,
|
|
|
|
|
|
|
|
choices: vec![CompletionComplete {
|
|
|
|
finish_reason: "".to_string(),
|
|
|
|
index: 0,
|
|
|
|
logprobs: None,
|
|
|
|
text: stream_token.token.text,
|
|
|
|
}],
|
|
|
|
|
|
|
|
model: info.model_id.clone(),
|
|
|
|
system_fingerprint: format!(
|
|
|
|
"{}-{}",
|
|
|
|
info.version,
|
|
|
|
info.docker_label.unwrap_or("native")
|
|
|
|
),
|
|
|
|
})
|
|
|
|
.map_or_else(
|
|
|
|
|e| {
|
2024-04-16 17:26:32 +00:00
|
|
|
println!("Failed to serialize CompletionCompleteChunk: {:?}", e);
|
2024-02-29 15:44:20 +00:00
|
|
|
Event::default()
|
|
|
|
},
|
|
|
|
|data| data,
|
|
|
|
)
|
|
|
|
};
|
|
|
|
|
|
|
|
let (headers, response_stream) = generate_stream_internal(
|
|
|
|
infer,
|
|
|
|
compute_type,
|
|
|
|
Json(generate_request),
|
|
|
|
on_message_callback,
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
|
|
|
|
Ok((headers, sse).into_response())
|
|
|
|
} else {
|
|
|
|
let (headers, Json(generation)) = generate(
|
|
|
|
Extension(infer),
|
|
|
|
Extension(compute_type),
|
|
|
|
Json(generate_request),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
let current_time = std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
|
|
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
|
|
|
|
.as_secs();
|
|
|
|
|
|
|
|
let details = generation.details.ok_or((
|
|
|
|
// this should never happen but handle if details are missing unexpectedly
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "No details in generation".to_string(),
|
|
|
|
error_type: "no details".to_string(),
|
|
|
|
}),
|
|
|
|
))?;
|
|
|
|
|
|
|
|
let response = Completion {
|
|
|
|
id: "".to_string(),
|
|
|
|
object: "text_completion".to_string(),
|
|
|
|
created: current_time,
|
|
|
|
model: info.model_id.clone(),
|
|
|
|
system_fingerprint: format!(
|
|
|
|
"{}-{}",
|
|
|
|
info.version,
|
|
|
|
info.docker_label.unwrap_or("native")
|
|
|
|
),
|
|
|
|
choices: vec![CompletionComplete {
|
|
|
|
finish_reason: details.finish_reason.to_string(),
|
|
|
|
index: 0,
|
|
|
|
logprobs: None,
|
|
|
|
text: generation.generated_text,
|
|
|
|
}],
|
|
|
|
usage: Usage {
|
|
|
|
prompt_tokens: details.prefill.len() as u32,
|
|
|
|
completion_tokens: details.generated_tokens,
|
|
|
|
total_tokens: details.prefill.len() as u32 + details.generated_tokens,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok((headers, Json(response)).into_response())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
/// Generate tokens
|
|
|
|
#[utoipa::path(
|
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/v1/chat/completions",
|
|
|
|
request_body = ChatRequest,
|
|
|
|
responses(
|
2024-04-16 17:26:32 +00:00
|
|
|
(status = 200, description = "Generated Chat Completion",
|
|
|
|
content(
|
|
|
|
("application/json" = ChatCompletion),
|
|
|
|
("text/event-stream" = ChatCompletionChunk),
|
|
|
|
)),
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
(status = 424, description = "Generation Error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Request failed during generation"})),
|
|
|
|
(status = 429, description = "Model is overloaded", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Model is overloaded"})),
|
|
|
|
(status = 422, description = "Input validation error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Input validation error"})),
|
|
|
|
(status = 500, description = "Incomplete generation", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Incomplete generation"})),
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
#[instrument(
|
|
|
|
skip_all,
|
|
|
|
fields(
|
|
|
|
// parameters = ? req.parameters,
|
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
async fn chat_completions(
|
|
|
|
Extension(infer): Extension<Infer>,
|
2024-01-29 10:20:08 +00:00
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
Extension(info): Extension<Info>,
|
|
|
|
Json(req): Json<ChatRequest>,
|
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
|
|
|
metrics::increment_counter!("tgi_request_count");
|
|
|
|
|
2024-04-16 13:02:46 +00:00
|
|
|
let ChatRequest {
|
|
|
|
logprobs,
|
|
|
|
max_tokens,
|
|
|
|
messages,
|
|
|
|
presence_penalty,
|
|
|
|
seed,
|
|
|
|
stop,
|
|
|
|
stream,
|
|
|
|
tools,
|
|
|
|
tool_choice,
|
|
|
|
tool_prompt,
|
|
|
|
..
|
|
|
|
} = req;
|
|
|
|
|
|
|
|
let repetition_penalty = presence_penalty.map(|x| x + 2.0);
|
|
|
|
let max_new_tokens = max_tokens.or(Some(100));
|
|
|
|
let logprobs = logprobs.unwrap_or(false);
|
|
|
|
let tool_prompt = tool_prompt.unwrap_or_default();
|
|
|
|
let stop = stop.unwrap_or_default();
|
|
|
|
|
|
|
|
// extract tool grammar if present
|
|
|
|
let tool_grammar = match ToolGrammar::apply(tools, tool_choice) {
|
|
|
|
Ok(grammar) => grammar,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
Err(err) => {
|
|
|
|
metrics::increment_counter!("tgi_request_failure", "err" => "validation");
|
|
|
|
tracing::error!("{err}");
|
|
|
|
return Err((
|
|
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: err.to_string(),
|
|
|
|
error_type: err.error_type().to_string(),
|
|
|
|
}),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-04-16 13:02:46 +00:00
|
|
|
let grammar_with_prompt = tool_grammar
|
|
|
|
.as_ref()
|
|
|
|
.map(|t| (GrammarType::Json(serde_json::json!(t)), tool_prompt));
|
2024-02-28 10:10:27 +00:00
|
|
|
|
2024-04-16 13:02:46 +00:00
|
|
|
let typed_grammar = grammar_with_prompt
|
|
|
|
.as_ref()
|
|
|
|
.map(|(grammar, _)| grammar.clone());
|
2024-02-28 10:10:27 +00:00
|
|
|
|
2024-04-16 13:02:46 +00:00
|
|
|
// apply chat template to flatten the request into a single input
|
|
|
|
let inputs = match infer.apply_chat_template(messages, grammar_with_prompt) {
|
|
|
|
Ok(inputs) => inputs,
|
|
|
|
Err(err) => {
|
|
|
|
metrics::increment_counter!("tgi_request_failure", "err" => "validation");
|
|
|
|
tracing::error!("{err}");
|
|
|
|
return Err((
|
2024-02-28 10:10:27 +00:00
|
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
|
|
Json(ErrorResponse {
|
2024-04-16 13:02:46 +00:00
|
|
|
error: err.to_string(),
|
|
|
|
error_type: err.error_type().to_string(),
|
2024-02-28 10:10:27 +00:00
|
|
|
}),
|
2024-04-16 13:02:46 +00:00
|
|
|
));
|
|
|
|
}
|
2024-02-28 10:10:27 +00:00
|
|
|
};
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
// build the request passing some parameters
|
|
|
|
let generate_request = GenerateRequest {
|
|
|
|
inputs: inputs.to_string(),
|
|
|
|
parameters: GenerateParameters {
|
|
|
|
best_of: None,
|
Disable `decoder_input_details` on OpenAI-compatible chat streaming, pass temp and top-k from API (#1470)
This PR makes some minor tweaks to the new OpenAI-compatible chat
endpoint #1427 in `GenerateParameters`:
- Disables `decoder_input_details` when streaming is enabled. This was
causing all streaming chat requests to fail before, since
[`decoder_input_details`==true is not enabled when streaming
tokens](https://github.com/huggingface/text-generation-inference/blob/98e5faff9daec6170cc2b0f963f2d73cf846b341/router/src/validation.rs#L406).
- Passes through `temperature` and `top_p` hyperparameters from the API
request to `GenerateParameters`
## Testing
```bash
curl localhost:8080/v1/chat/completions \
-X POST \
-d '{
"model": "",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
Should work correctly. Currently, most recent release from `main`
returns error:
```
data:{"error":"Input validation error: `decoder_input_details` == true is not supported when streaming tokens","error_type":"validation"}
```
It's my first time contributing to this project, so I could be missing
something. Would especially appreciate @drbh's eyes on this one
2024-01-23 14:55:05 +00:00
|
|
|
temperature: req.temperature,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
repetition_penalty,
|
2024-02-08 17:41:25 +00:00
|
|
|
frequency_penalty: req.frequency_penalty,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
top_k: None,
|
Disable `decoder_input_details` on OpenAI-compatible chat streaming, pass temp and top-k from API (#1470)
This PR makes some minor tweaks to the new OpenAI-compatible chat
endpoint #1427 in `GenerateParameters`:
- Disables `decoder_input_details` when streaming is enabled. This was
causing all streaming chat requests to fail before, since
[`decoder_input_details`==true is not enabled when streaming
tokens](https://github.com/huggingface/text-generation-inference/blob/98e5faff9daec6170cc2b0f963f2d73cf846b341/router/src/validation.rs#L406).
- Passes through `temperature` and `top_p` hyperparameters from the API
request to `GenerateParameters`
## Testing
```bash
curl localhost:8080/v1/chat/completions \
-X POST \
-d '{
"model": "",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
Should work correctly. Currently, most recent release from `main`
returns error:
```
data:{"error":"Input validation error: `decoder_input_details` == true is not supported when streaming tokens","error_type":"validation"}
```
It's my first time contributing to this project, so I could be missing
something. Would especially appreciate @drbh's eyes on this one
2024-01-23 14:55:05 +00:00
|
|
|
top_p: req.top_p,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
typical_p: None,
|
|
|
|
do_sample: true,
|
|
|
|
max_new_tokens,
|
|
|
|
return_full_text: None,
|
2024-03-01 17:08:11 +00:00
|
|
|
stop,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
truncate: None,
|
|
|
|
watermark: false,
|
|
|
|
details: true,
|
Disable `decoder_input_details` on OpenAI-compatible chat streaming, pass temp and top-k from API (#1470)
This PR makes some minor tweaks to the new OpenAI-compatible chat
endpoint #1427 in `GenerateParameters`:
- Disables `decoder_input_details` when streaming is enabled. This was
causing all streaming chat requests to fail before, since
[`decoder_input_details`==true is not enabled when streaming
tokens](https://github.com/huggingface/text-generation-inference/blob/98e5faff9daec6170cc2b0f963f2d73cf846b341/router/src/validation.rs#L406).
- Passes through `temperature` and `top_p` hyperparameters from the API
request to `GenerateParameters`
## Testing
```bash
curl localhost:8080/v1/chat/completions \
-X POST \
-d '{
"model": "",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
Should work correctly. Currently, most recent release from `main`
returns error:
```
data:{"error":"Input validation error: `decoder_input_details` == true is not supported when streaming tokens","error_type":"validation"}
```
It's my first time contributing to this project, so I could be missing
something. Would especially appreciate @drbh's eyes on this one
2024-01-23 14:55:05 +00:00
|
|
|
decoder_input_details: !stream,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
seed,
|
fix: adjust logprob response logic (#1682)
This PR fixes a bug with `ChatCompletionLogprobs` where if
`top_tokens.len() == 0` empty results were returned.
```bash
curl http://localhost:3000/v1/chat/completions \
-X POST \
-H 'Content-Type: application/json' \
-d '{
"model": "tgi",
"logprobs": true,
"messages": [
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": false,
"max_tokens": 20
}'
```
response
```json
{"id":"","object":"text_completion","created":1711588522,"model":"google/gemma-2b-it","system_fingerprint":"1.4.4-native","choices":[{"index":0,"message":{"role":"assistant","content":"**Deep learning** is a subset of machine learning (ML) that emphasizes the creation of **artificial"},"logprobs":{"content":[{"token":"**","logprob":-0.22558594,"top_logprobs":[]},{"token":"Deep","logprob":-0.0014877319,"top_logprobs":[]},{"token":" learning","logprob":-0.12695312,"top_logprobs":[]},{"token":"**","logprob":-0.055664062,"top_logprobs":[]},{"token":" is","logprob":-0.00090026855,"top_logprobs":[]},{"token":" a","logprob":-0.006072998,"top_logprobs":[]},{"token":" subset","logprob":-2.25,"top_logprobs":[]},{"token":" of","logprob":-0.00031089783,"top_logprobs":[]},{"token":" machine","logprob":-0.091308594,"top_logprobs":[]},{"token":" learning","logprob":-0.00002348423,"top_logprobs":[]},{"token":" (","logprob":-1.671875,"top_logprobs":[]},{"token":"ML","logprob":-0.00040626526,"top_logprobs":[]},{"token":")","logprob":-0.00016212463,"top_logprobs":[]},{"token":" that","logprob":-0.13769531,"top_logprobs":[]},{"token":" emphasizes","logprob":-4.03125,"top_logprobs":[]},{"token":" the","logprob":-0.2890625,"top_logprobs":[]},{"token":" creation","logprob":-3.109375,"top_logprobs":[]},{"token":" of","logprob":-0.00024032593,"top_logprobs":[]},{"token":" **","logprob":-1.2265625,"top_logprobs":[]},{"token":"artificial","logprob":-0.10546875,"top_logprobs":[]}]},"finish_reason":"length"}],"usage":{"prompt_tokens":15,"completion_tokens":20,"total_tokens":35}}
```
2024-03-28 16:01:46 +00:00
|
|
|
top_n_tokens: req.top_logprobs,
|
2024-04-16 13:02:46 +00:00
|
|
|
grammar: typed_grammar,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
// static values that will be returned in all cases
|
|
|
|
let model_id = info.model_id.clone();
|
|
|
|
let system_fingerprint = format!("{}-{}", info.version, info.docker_label.unwrap_or("native"));
|
|
|
|
|
|
|
|
// switch on stream
|
|
|
|
if stream {
|
|
|
|
// pass this callback to the stream generation and build the required event structure
|
|
|
|
let on_message_callback = move |stream_token: StreamResponse| {
|
|
|
|
let event = Event::default();
|
|
|
|
|
|
|
|
let current_time = std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
|
|
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
|
|
|
|
.as_secs();
|
|
|
|
|
2024-02-08 17:41:25 +00:00
|
|
|
let logprobs = logprobs.then(|| {
|
|
|
|
ChatCompletionLogprobs::from((stream_token.token.clone(), stream_token.top_tokens))
|
|
|
|
});
|
|
|
|
|
2024-02-28 10:10:27 +00:00
|
|
|
// replace the content with the tool calls if grammar is present
|
|
|
|
let (content, tool_calls) = if tool_grammar.is_some() {
|
|
|
|
(None, Some(vec![stream_token.token.text]))
|
|
|
|
} else {
|
|
|
|
(Some(stream_token.token.text), None)
|
|
|
|
};
|
|
|
|
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
event
|
|
|
|
.json_data(ChatCompletionChunk::new(
|
|
|
|
model_id.clone(),
|
|
|
|
system_fingerprint.clone(),
|
2024-02-28 10:10:27 +00:00
|
|
|
content,
|
|
|
|
tool_calls,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
current_time,
|
2024-02-08 17:41:25 +00:00
|
|
|
logprobs,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
stream_token.details.map(|d| d.finish_reason.to_string()),
|
|
|
|
))
|
|
|
|
.map_or_else(
|
|
|
|
|e| {
|
|
|
|
println!("Failed to serialize ChatCompletionChunk: {:?}", e);
|
|
|
|
Event::default()
|
|
|
|
},
|
|
|
|
|data| data,
|
|
|
|
)
|
|
|
|
};
|
|
|
|
|
2024-01-29 11:30:50 +00:00
|
|
|
let (headers, response_stream) = generate_stream_internal(
|
|
|
|
infer,
|
|
|
|
compute_type,
|
|
|
|
Json(generate_request),
|
|
|
|
on_message_callback,
|
|
|
|
)
|
|
|
|
.await;
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
let sse = Sse::new(response_stream).keep_alive(KeepAlive::default());
|
|
|
|
Ok((headers, sse).into_response())
|
|
|
|
} else {
|
2024-01-29 11:30:50 +00:00
|
|
|
let (headers, Json(generation)) = generate(
|
|
|
|
Extension(infer),
|
|
|
|
Extension(compute_type),
|
|
|
|
Json(generate_request),
|
|
|
|
)
|
|
|
|
.await?;
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
|
|
|
|
let current_time = std::time::SystemTime::now()
|
|
|
|
.duration_since(std::time::UNIX_EPOCH)
|
|
|
|
.unwrap_or_else(|_| std::time::Duration::from_secs(0))
|
|
|
|
.as_secs();
|
|
|
|
|
2024-02-28 10:10:27 +00:00
|
|
|
let (tool_calls, output) = if tool_grammar.is_some() {
|
|
|
|
// gen_text should be valid json
|
|
|
|
let gen_text_value: Value =
|
|
|
|
serde_json::from_str(&generation.generated_text).map_err(|e| {
|
|
|
|
(
|
|
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: e.to_string(),
|
|
|
|
error_type: "Input validation error".to_string(),
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
})?;
|
2024-03-21 16:45:56 +00:00
|
|
|
let tool_calls = vec![ToolCall {
|
2024-02-28 10:10:27 +00:00
|
|
|
id: 0,
|
|
|
|
r#type: "function".to_string(),
|
|
|
|
function: FunctionDefinition {
|
|
|
|
description: None,
|
2024-04-16 13:02:46 +00:00
|
|
|
name: gen_text_value
|
|
|
|
.get("function")
|
|
|
|
.and_then(|f| f.get("_name"))
|
|
|
|
.and_then(|name| name.as_str())
|
|
|
|
.unwrap_or("default_function_name")
|
|
|
|
.to_string(),
|
|
|
|
// Serialize the JSON object obtained from "function" to an escaped JSON string
|
|
|
|
arguments: gen_text_value
|
|
|
|
.get("function")
|
|
|
|
.map(|f| {
|
|
|
|
let mut f_cloned = f.clone();
|
|
|
|
if let Value::Object(ref mut props) = f_cloned {
|
|
|
|
props.remove("_name");
|
|
|
|
}
|
|
|
|
f_cloned
|
|
|
|
})
|
|
|
|
.unwrap_or_default(),
|
2024-02-28 10:10:27 +00:00
|
|
|
},
|
2024-03-21 16:45:56 +00:00
|
|
|
}];
|
|
|
|
(Some(tool_calls), None)
|
2024-02-28 10:10:27 +00:00
|
|
|
} else {
|
|
|
|
(None, Some(generation.generated_text))
|
|
|
|
};
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
// build the complete response object with the full text
|
|
|
|
let response = ChatCompletion::new(
|
|
|
|
model_id,
|
|
|
|
system_fingerprint,
|
2024-02-28 10:10:27 +00:00
|
|
|
output,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
current_time,
|
|
|
|
generation.details.unwrap(),
|
|
|
|
logprobs,
|
2024-02-28 10:10:27 +00:00
|
|
|
tool_calls,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
// wrap generation inside a Vec to match api-inference
|
|
|
|
Ok((headers, Json(response)).into_response())
|
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
}
|
|
|
|
|
2024-02-20 13:04:51 +00:00
|
|
|
/// Generate tokens from Vertex request
|
|
|
|
#[utoipa::path(
|
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/vertex",
|
|
|
|
request_body = VertexRequest,
|
|
|
|
responses(
|
|
|
|
(status = 200, description = "Generated Text", body = VertexResponse),
|
|
|
|
(status = 424, description = "Generation Error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Request failed during generation"})),
|
|
|
|
(status = 429, description = "Model is overloaded", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Model is overloaded"})),
|
|
|
|
(status = 422, description = "Input validation error", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Input validation error"})),
|
|
|
|
(status = 500, description = "Incomplete generation", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "Incomplete generation"})),
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
#[instrument(
|
|
|
|
skip_all,
|
|
|
|
fields(
|
|
|
|
total_time,
|
|
|
|
validation_time,
|
|
|
|
queue_time,
|
|
|
|
inference_time,
|
|
|
|
time_per_token,
|
|
|
|
seed,
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
async fn vertex_compatibility(
|
|
|
|
Extension(infer): Extension<Infer>,
|
|
|
|
Extension(compute_type): Extension<ComputeType>,
|
|
|
|
Json(req): Json<VertexRequest>,
|
|
|
|
) -> Result<Response, (StatusCode, Json<ErrorResponse>)> {
|
|
|
|
metrics::increment_counter!("tgi_request_count");
|
|
|
|
|
|
|
|
// check that theres at least one instance
|
|
|
|
if req.instances.is_empty() {
|
|
|
|
return Err((
|
|
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "Input validation error".to_string(),
|
|
|
|
error_type: "Input validation error".to_string(),
|
|
|
|
}),
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Process all instances
|
|
|
|
let predictions = req
|
|
|
|
.instances
|
|
|
|
.iter()
|
|
|
|
.map(|instance| {
|
|
|
|
let generate_request = GenerateRequest {
|
|
|
|
inputs: instance.inputs.clone(),
|
|
|
|
parameters: GenerateParameters {
|
|
|
|
do_sample: true,
|
|
|
|
max_new_tokens: instance.parameters.as_ref().and_then(|p| p.max_new_tokens),
|
|
|
|
seed: instance.parameters.as_ref().and_then(|p| p.seed),
|
|
|
|
details: true,
|
|
|
|
decoder_input_details: true,
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
async {
|
|
|
|
generate(
|
|
|
|
Extension(infer.clone()),
|
|
|
|
Extension(compute_type.clone()),
|
|
|
|
Json(generate_request),
|
|
|
|
)
|
|
|
|
.await
|
|
|
|
.map(|(_, Json(generation))| generation.generated_text)
|
|
|
|
.map_err(|_| {
|
|
|
|
(
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "Incomplete generation".into(),
|
|
|
|
error_type: "Incomplete generation".into(),
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect::<FuturesUnordered<_>>()
|
|
|
|
.try_collect::<Vec<_>>()
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
let response = VertexResponse { predictions };
|
|
|
|
Ok((HeaderMap::new(), Json(response)).into_response())
|
|
|
|
}
|
|
|
|
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
/// Tokenize inputs
|
|
|
|
#[utoipa::path(
|
|
|
|
post,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/tokenize",
|
2024-01-26 15:07:31 +00:00
|
|
|
request_body = GenerateRequest,
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
responses(
|
|
|
|
(status = 200, description = "Tokenized ids", body = TokenizeResponse),
|
|
|
|
(status = 404, description = "No tokenizer found", body = ErrorResponse,
|
|
|
|
example = json ! ({"error": "No fast tokenizer available"})),
|
|
|
|
)
|
|
|
|
)]
|
|
|
|
#[instrument(skip_all)]
|
|
|
|
async fn tokenize(
|
|
|
|
Extension(infer): Extension<Infer>,
|
|
|
|
Json(req): Json<GenerateRequest>,
|
2024-01-26 15:07:31 +00:00
|
|
|
) -> Result<Json<TokenizeResponse>, (StatusCode, Json<ErrorResponse>)> {
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
let input = req.inputs.clone();
|
|
|
|
let encoding = infer.tokenize(req).await?;
|
|
|
|
if let Some(encoding) = encoding {
|
|
|
|
let tokens: Vec<SimpleToken> = encoding
|
|
|
|
.get_ids()
|
|
|
|
.iter()
|
|
|
|
.zip(encoding.get_offsets())
|
|
|
|
.map(|(&id, &(start, stop))| {
|
|
|
|
let text: String = input.chars().skip(start).take(stop - start).collect();
|
|
|
|
SimpleToken {
|
|
|
|
id,
|
|
|
|
text,
|
|
|
|
start,
|
|
|
|
stop,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect();
|
2024-01-26 15:07:31 +00:00
|
|
|
Ok(Json(TokenizeResponse(tokens)))
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
} else {
|
|
|
|
Err((
|
|
|
|
StatusCode::NOT_FOUND,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: "No fast tokenizer or tokenizer.json for this model".to_string(),
|
|
|
|
error_type: "no fast tokenizer".to_string(),
|
|
|
|
}),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-16 16:18:53 +00:00
|
|
|
/// Prometheus metrics scrape endpoint
|
|
|
|
#[utoipa::path(
|
2023-07-21 14:56:30 +00:00
|
|
|
get,
|
|
|
|
tag = "Text Generation Inference",
|
|
|
|
path = "/metrics",
|
|
|
|
responses((status = 200, description = "Prometheus Metrics", body = String))
|
2023-02-16 16:18:53 +00:00
|
|
|
)]
|
|
|
|
async fn metrics(prom_handle: Extension<PrometheusHandle>) -> String {
|
|
|
|
prom_handle.render()
|
|
|
|
}
|
|
|
|
|
2024-01-29 10:20:08 +00:00
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub(crate) struct ComputeType(String);
|
|
|
|
|
2022-10-18 13:19:03 +00:00
|
|
|
/// Serving method
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
|
|
pub async fn run(
|
2023-04-21 13:36:29 +00:00
|
|
|
model_info: HubModelInfo,
|
|
|
|
shard_info: ShardInfo,
|
2023-02-28 09:19:32 +00:00
|
|
|
compat_return_full_text: bool,
|
2022-10-18 13:19:03 +00:00
|
|
|
max_concurrent_requests: usize,
|
2023-03-09 14:30:54 +00:00
|
|
|
max_best_of: usize,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_stop_sequences: usize,
|
2023-08-28 09:43:47 +00:00
|
|
|
max_top_n_tokens: u32,
|
2022-10-18 13:19:03 +00:00
|
|
|
max_input_length: usize,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_total_tokens: usize,
|
2023-04-24 15:59:00 +00:00
|
|
|
waiting_served_ratio: f32,
|
2023-06-30 17:09:59 +00:00
|
|
|
max_batch_prefill_tokens: u32,
|
2023-04-24 15:59:00 +00:00
|
|
|
max_batch_total_tokens: u32,
|
2022-10-21 14:40:05 +00:00
|
|
|
max_waiting_tokens: usize,
|
2024-02-09 11:38:41 +00:00
|
|
|
max_batch_size: Option<usize>,
|
2022-10-18 13:19:03 +00:00
|
|
|
client: ShardedClient,
|
2023-04-09 18:22:27 +00:00
|
|
|
tokenizer: Option<Tokenizer>,
|
Adding Llava-Next (Llava 1.6) with full support. (#1709)
# What does this PR do?
- Changed all models to extract `embed_tokens` in order to enable llava
to separately call the embeddings and the core model layers.
- Added VlmCausalLM to inherit from FlashMistral in order to be
maximally supported. The only added logics sits on top and parses images
into pixel values, preallocates input_ids space for the image
embeddings, and passes them for the model.
- Added Clip for the vision tower.
- Didn't add flash for the vision tower since there's no padding anyway.
- Added heuristic (potentially incomplete) to calculate number of
features *before* calculating the clip patches (allows for easier logic
reuse of the LLM under the hood).
Still needs to be done:
- [x] Implement the image parsing in the controller side, to avoid
downloading n times per TP shard and also refusing requests too large
early and avoid issues where the truncation actually truncates the
image.
- [ ] Make sure it works with quantization properly.
- [x] Make sure it works with TP>1
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-04-09 19:32:00 +00:00
|
|
|
config: Option<Config>,
|
2022-10-18 13:19:03 +00:00
|
|
|
validation_workers: usize,
|
|
|
|
addr: SocketAddr,
|
2023-02-17 17:22:00 +00:00
|
|
|
allow_origin: Option<AllowOrigin>,
|
2023-06-16 14:25:11 +00:00
|
|
|
ngrok: bool,
|
|
|
|
ngrok_authtoken: Option<String>,
|
2023-07-19 09:59:58 +00:00
|
|
|
ngrok_edge: Option<String>,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
tokenizer_config: HubTokenizerConfig,
|
2024-01-24 16:41:28 +00:00
|
|
|
messages_api_enabled: bool,
|
2024-02-15 09:28:10 +00:00
|
|
|
grammar_support: bool,
|
2023-07-10 12:47:15 +00:00
|
|
|
) -> Result<(), axum::BoxError> {
|
2023-02-03 11:43:37 +00:00
|
|
|
// OpenAPI documentation
|
|
|
|
#[derive(OpenApi)]
|
|
|
|
#[openapi(
|
2023-07-21 14:56:30 +00:00
|
|
|
paths(
|
|
|
|
health,
|
|
|
|
get_model_info,
|
|
|
|
compat_generate,
|
|
|
|
generate,
|
|
|
|
generate_stream,
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
chat_completions,
|
2024-02-29 15:44:20 +00:00
|
|
|
completions,
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
tokenize,
|
2023-07-21 14:56:30 +00:00
|
|
|
metrics,
|
|
|
|
),
|
|
|
|
components(
|
|
|
|
schemas(
|
|
|
|
Info,
|
|
|
|
CompatGenerateRequest,
|
|
|
|
GenerateRequest,
|
2024-02-21 10:05:32 +00:00
|
|
|
GrammarType,
|
2024-01-26 15:07:31 +00:00
|
|
|
ChatRequest,
|
|
|
|
Message,
|
2024-02-21 14:30:45 +00:00
|
|
|
ChatCompletionComplete,
|
2024-01-26 15:07:31 +00:00
|
|
|
ChatCompletionChoice,
|
|
|
|
ChatCompletionDelta,
|
|
|
|
ChatCompletionChunk,
|
2024-02-21 14:30:45 +00:00
|
|
|
ChatCompletionLogprob,
|
|
|
|
ChatCompletionLogprobs,
|
|
|
|
ChatCompletionTopLogprob,
|
2024-01-26 15:07:31 +00:00
|
|
|
ChatCompletion,
|
2024-02-29 15:44:20 +00:00
|
|
|
CompletionRequest,
|
|
|
|
CompletionComplete,
|
|
|
|
CompletionCompleteChunk,
|
2023-07-21 14:56:30 +00:00
|
|
|
GenerateParameters,
|
|
|
|
PrefillToken,
|
|
|
|
Token,
|
|
|
|
GenerateResponse,
|
2024-01-26 15:07:31 +00:00
|
|
|
TokenizeResponse,
|
|
|
|
SimpleToken,
|
2023-07-21 14:56:30 +00:00
|
|
|
BestOfSequence,
|
|
|
|
Details,
|
|
|
|
FinishReason,
|
|
|
|
StreamResponse,
|
|
|
|
StreamDetails,
|
|
|
|
ErrorResponse,
|
2024-02-20 13:04:51 +00:00
|
|
|
GrammarType,
|
2024-02-21 14:30:45 +00:00
|
|
|
Usage,
|
2024-03-29 18:17:24 +00:00
|
|
|
DeltaToolCall,
|
|
|
|
ToolType,
|
|
|
|
Tool,
|
|
|
|
ToolCall,
|
|
|
|
Function,
|
|
|
|
FunctionDefinition,
|
2023-07-21 14:56:30 +00:00
|
|
|
)
|
|
|
|
),
|
|
|
|
tags(
|
|
|
|
(name = "Text Generation Inference", description = "Hugging Face Text Generation Inference API")
|
|
|
|
),
|
|
|
|
info(
|
|
|
|
title = "Text Generation Inference",
|
|
|
|
license(
|
|
|
|
name = "Apache 2.0",
|
|
|
|
url = "https://www.apache.org/licenses/LICENSE-2.0"
|
|
|
|
)
|
|
|
|
)
|
2023-02-03 11:43:37 +00:00
|
|
|
)]
|
|
|
|
struct ApiDoc;
|
|
|
|
|
2022-10-18 13:19:03 +00:00
|
|
|
// Create state
|
2023-02-15 20:56:59 +00:00
|
|
|
let validation = Validation::new(
|
|
|
|
validation_workers,
|
|
|
|
tokenizer,
|
Adding Llava-Next (Llava 1.6) with full support. (#1709)
# What does this PR do?
- Changed all models to extract `embed_tokens` in order to enable llava
to separately call the embeddings and the core model layers.
- Added VlmCausalLM to inherit from FlashMistral in order to be
maximally supported. The only added logics sits on top and parses images
into pixel values, preallocates input_ids space for the image
embeddings, and passes them for the model.
- Added Clip for the vision tower.
- Didn't add flash for the vision tower since there's no padding anyway.
- Added heuristic (potentially incomplete) to calculate number of
features *before* calculating the clip patches (allows for easier logic
reuse of the LLM under the hood).
Still needs to be done:
- [x] Implement the image parsing in the controller side, to avoid
downloading n times per TP shard and also refusing requests too large
early and avoid issues where the truncation actually truncates the
image.
- [ ] Make sure it works with quantization properly.
- [x] Make sure it works with TP>1
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-04-09 19:32:00 +00:00
|
|
|
config,
|
2023-03-09 14:30:54 +00:00
|
|
|
max_best_of,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_stop_sequences,
|
2023-08-28 09:43:47 +00:00
|
|
|
max_top_n_tokens,
|
2023-02-15 20:56:59 +00:00
|
|
|
max_input_length,
|
|
|
|
max_total_tokens,
|
2024-02-15 09:28:10 +00:00
|
|
|
grammar_support,
|
2023-02-15 20:56:59 +00:00
|
|
|
);
|
2023-04-26 18:23:54 +00:00
|
|
|
let generation_health = Arc::new(AtomicBool::new(false));
|
|
|
|
let health_ext = Health::new(client.clone(), generation_health.clone());
|
2023-01-31 16:04:00 +00:00
|
|
|
let infer = Infer::new(
|
|
|
|
client,
|
2022-10-18 13:19:03 +00:00
|
|
|
validation,
|
2023-04-24 15:59:00 +00:00
|
|
|
waiting_served_ratio,
|
2023-06-30 17:09:59 +00:00
|
|
|
max_batch_prefill_tokens,
|
2023-04-24 15:59:00 +00:00
|
|
|
max_batch_total_tokens,
|
2023-01-31 16:04:00 +00:00
|
|
|
max_waiting_tokens,
|
2024-02-09 11:38:41 +00:00
|
|
|
max_batch_size,
|
2023-01-31 16:04:00 +00:00
|
|
|
max_concurrent_requests,
|
2023-04-24 15:59:00 +00:00
|
|
|
shard_info.requires_padding,
|
2023-09-28 07:55:47 +00:00
|
|
|
shard_info.window_size,
|
2023-12-11 11:46:30 +00:00
|
|
|
shard_info.speculate,
|
2023-04-26 18:23:54 +00:00
|
|
|
generation_health,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
tokenizer_config,
|
2023-01-31 16:04:00 +00:00
|
|
|
);
|
2022-10-18 13:19:03 +00:00
|
|
|
|
2023-04-09 18:13:28 +00:00
|
|
|
// Duration buckets
|
|
|
|
let duration_matcher = Matcher::Suffix(String::from("duration"));
|
|
|
|
let n_duration_buckets = 35;
|
|
|
|
let mut duration_buckets = Vec::with_capacity(n_duration_buckets);
|
|
|
|
// Minimum duration in seconds
|
|
|
|
let mut value = 0.0001;
|
|
|
|
for _ in 0..n_duration_buckets {
|
|
|
|
// geometric sequence
|
|
|
|
value *= 1.5;
|
|
|
|
duration_buckets.push(value);
|
|
|
|
}
|
|
|
|
// Input Length buckets
|
|
|
|
let input_length_matcher = Matcher::Full(String::from("tgi_request_input_length"));
|
|
|
|
let input_length_buckets: Vec<f64> = (0..100)
|
|
|
|
.map(|x| (max_input_length as f64 / 100.0) * (x + 1) as f64)
|
|
|
|
.collect();
|
|
|
|
// Generated tokens buckets
|
|
|
|
let generated_tokens_matcher = Matcher::Full(String::from("tgi_request_generated_tokens"));
|
|
|
|
let generated_tokens_buckets: Vec<f64> = (0..100)
|
|
|
|
.map(|x| (max_total_tokens as f64 / 100.0) * (x + 1) as f64)
|
|
|
|
.collect();
|
|
|
|
// Input Length buckets
|
|
|
|
let max_new_tokens_matcher = Matcher::Full(String::from("tgi_request_max_new_tokens"));
|
|
|
|
let max_new_tokens_buckets: Vec<f64> = (0..100)
|
|
|
|
.map(|x| (max_total_tokens as f64 / 100.0) * (x + 1) as f64)
|
|
|
|
.collect();
|
|
|
|
// Batch size buckets
|
|
|
|
let batch_size_matcher = Matcher::Full(String::from("tgi_batch_next_size"));
|
2023-04-24 15:59:00 +00:00
|
|
|
let batch_size_buckets: Vec<f64> = (0..1024).map(|x| (x + 1) as f64).collect();
|
2023-12-11 13:43:40 +00:00
|
|
|
// Speculated tokens buckets
|
|
|
|
let skipped_matcher = Matcher::Full(String::from("tgi_request_skipped_tokens"));
|
|
|
|
let skipped_buckets: Vec<f64> = (0..shard_info.speculate + 1).map(|x| x as f64).collect();
|
2023-04-09 18:13:28 +00:00
|
|
|
|
2023-02-16 16:18:53 +00:00
|
|
|
// Prometheus handler
|
2023-04-09 18:13:28 +00:00
|
|
|
let builder = PrometheusBuilder::new()
|
|
|
|
.set_buckets_for_metric(duration_matcher, &duration_buckets)
|
|
|
|
.unwrap()
|
|
|
|
.set_buckets_for_metric(input_length_matcher, &input_length_buckets)
|
|
|
|
.unwrap()
|
|
|
|
.set_buckets_for_metric(generated_tokens_matcher, &generated_tokens_buckets)
|
|
|
|
.unwrap()
|
|
|
|
.set_buckets_for_metric(max_new_tokens_matcher, &max_new_tokens_buckets)
|
|
|
|
.unwrap()
|
|
|
|
.set_buckets_for_metric(batch_size_matcher, &batch_size_buckets)
|
2023-12-11 13:43:40 +00:00
|
|
|
.unwrap()
|
|
|
|
.set_buckets_for_metric(skipped_matcher, &skipped_buckets)
|
2023-04-09 18:13:28 +00:00
|
|
|
.unwrap();
|
2023-02-16 16:18:53 +00:00
|
|
|
let prom_handle = builder
|
|
|
|
.install_recorder()
|
|
|
|
.expect("failed to install metrics recorder");
|
|
|
|
|
2023-02-17 17:22:00 +00:00
|
|
|
// CORS layer
|
|
|
|
let allow_origin = allow_origin.unwrap_or(AllowOrigin::any());
|
|
|
|
let cors_layer = CorsLayer::new()
|
|
|
|
.allow_methods([Method::GET, Method::POST])
|
|
|
|
.allow_headers([http::header::CONTENT_TYPE])
|
|
|
|
.allow_origin(allow_origin);
|
|
|
|
|
2023-04-25 11:11:18 +00:00
|
|
|
// Endpoint info
|
|
|
|
let info = Info {
|
|
|
|
model_id: model_info.model_id,
|
|
|
|
model_sha: model_info.sha,
|
|
|
|
model_dtype: shard_info.dtype,
|
|
|
|
model_device_type: shard_info.device_type,
|
|
|
|
model_pipeline_tag: model_info.pipeline_tag,
|
|
|
|
max_concurrent_requests,
|
|
|
|
max_best_of,
|
|
|
|
max_stop_sequences,
|
|
|
|
max_input_length,
|
|
|
|
max_total_tokens,
|
|
|
|
waiting_served_ratio,
|
|
|
|
max_batch_total_tokens,
|
|
|
|
max_waiting_tokens,
|
2024-02-09 11:38:41 +00:00
|
|
|
max_batch_size,
|
2023-04-25 11:11:18 +00:00
|
|
|
validation_workers,
|
|
|
|
version: env!("CARGO_PKG_VERSION"),
|
|
|
|
sha: option_env!("VERGEN_GIT_SHA"),
|
2023-05-02 13:43:19 +00:00
|
|
|
docker_label: option_env!("DOCKER_LABEL"),
|
2023-04-25 11:11:18 +00:00
|
|
|
};
|
|
|
|
|
2024-02-20 13:04:51 +00:00
|
|
|
// Define VertextApiDoc conditionally only if the "google" feature is enabled
|
|
|
|
let doc = {
|
|
|
|
// avoid `mut` if possible
|
|
|
|
#[cfg(feature = "google")]
|
|
|
|
{
|
2024-02-20 15:38:35 +00:00
|
|
|
use crate::VertexInstance;
|
|
|
|
|
|
|
|
#[derive(OpenApi)]
|
|
|
|
#[openapi(
|
|
|
|
paths(vertex_compatibility),
|
|
|
|
components(schemas(VertexInstance, VertexRequest, VertexResponse))
|
|
|
|
)]
|
|
|
|
struct VertextApiDoc;
|
|
|
|
|
2024-02-20 13:04:51 +00:00
|
|
|
// limiting mutability to the smallest scope necessary
|
2024-02-20 15:38:35 +00:00
|
|
|
let mut doc = ApiDoc::openapi();
|
2024-02-20 13:04:51 +00:00
|
|
|
doc.merge(VertextApiDoc::openapi());
|
|
|
|
doc
|
|
|
|
}
|
|
|
|
#[cfg(not(feature = "google"))]
|
|
|
|
ApiDoc::openapi()
|
|
|
|
};
|
|
|
|
|
2024-01-22 15:29:01 +00:00
|
|
|
// Configure Swagger UI
|
2024-02-20 13:04:51 +00:00
|
|
|
let swagger_ui = SwaggerUi::new("/docs").url("/api-doc/openapi.json", doc);
|
2024-01-22 15:29:01 +00:00
|
|
|
|
|
|
|
// Define base and health routes
|
|
|
|
let base_routes = Router::new()
|
2023-02-27 13:56:58 +00:00
|
|
|
.route("/", post(compat_generate))
|
2024-02-01 12:29:04 +00:00
|
|
|
.route("/", get(health))
|
2023-04-18 14:16:06 +00:00
|
|
|
.route("/info", get(get_model_info))
|
2022-10-14 13:56:21 +00:00
|
|
|
.route("/generate", post(generate))
|
2023-01-31 16:04:00 +00:00
|
|
|
.route("/generate_stream", post(generate_stream))
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
.route("/v1/chat/completions", post(chat_completions))
|
2024-02-29 15:44:20 +00:00
|
|
|
.route("/v1/completions", post(completions))
|
2024-02-20 13:04:51 +00:00
|
|
|
.route("/vertex", post(vertex_compatibility))
|
Add a new `/tokenize` route to get the tokenized input (#1471)
# What does this PR do?
Ideally this is done client side, but this is a recurring request,
therefore we implemented it.
- Runs only if rust tokenizer is present (not encumbering the main
inference pipeline is important).
- Returns simple results, ID, text (gotten with offsets from the
original string) and offsets (so users can do things like highlighting
text).
<!--
Congratulations! You've made it this far! You're not quite done yet
though.
Once merged, your PR is going to appear in the release notes with the
title you set, so make sure it's a great title that fully reflects the
extent of your awesome contribution.
Then, please replace this with a description of the change and which
issue is fixed (if applicable). Please also include relevant motivation
and context. List any dependencies (if any) that are required for this
change.
Once you're done, someone will review your PR shortly (see the section
"Who can review?" below to tag some potential reviewers). They may
suggest changes to make the code even better. If no one reviewed your PR
after a week has passed, don't hesitate to post a new comment
@-mentioning the same persons---sometimes notifications get lost.
-->
<!-- Remove if not applicable -->
Fixes # (issue)
## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the
other checks if that's the case).
- [ ] Did you read the [contributor
guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#start-contributing-pull-requests),
Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the
[forum](https://discuss.huggingface.co/)? Please add a link
to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes?
Here are the
[documentation
guidelines](https://github.com/huggingface/transformers/tree/main/docs),
and
[here are tips on formatting
docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?
## Who can review?
Anyone in the community is free to review the PR once the tests have
passed. Feel free to tag
members/contributors who may be interested in your PR.
<!-- Your PR will be replied to more quickly if you can figure out the
right person to tag with @
@OlivierDehaene OR @Narsil
-->
2024-01-25 13:19:03 +00:00
|
|
|
.route("/tokenize", post(tokenize))
|
2022-10-18 13:19:03 +00:00
|
|
|
.route("/health", get(health))
|
2023-03-29 19:38:30 +00:00
|
|
|
.route("/ping", get(health))
|
2024-01-22 15:29:01 +00:00
|
|
|
.route("/metrics", get(metrics));
|
|
|
|
|
|
|
|
// Conditional AWS Sagemaker route
|
2024-01-24 16:41:28 +00:00
|
|
|
let aws_sagemaker_route = if messages_api_enabled {
|
2024-01-22 15:29:01 +00:00
|
|
|
Router::new().route("/invocations", post(chat_completions)) // Use 'chat_completions' for OAI_ENABLED
|
|
|
|
} else {
|
|
|
|
Router::new().route("/invocations", post(compat_generate)) // Use 'compat_generate' otherwise
|
|
|
|
};
|
|
|
|
|
2024-01-29 11:30:50 +00:00
|
|
|
let compute_type =
|
|
|
|
ComputeType(std::env::var("COMPUTE_TYPE").unwrap_or("gpu+optimized".to_string()));
|
2024-01-29 10:20:08 +00:00
|
|
|
|
2024-01-22 15:29:01 +00:00
|
|
|
// Combine routes and layers
|
2024-02-20 13:04:51 +00:00
|
|
|
let mut app = Router::new()
|
2024-01-22 15:29:01 +00:00
|
|
|
.merge(swagger_ui)
|
|
|
|
.merge(base_routes)
|
2024-02-20 13:04:51 +00:00
|
|
|
.merge(aws_sagemaker_route);
|
|
|
|
|
|
|
|
#[cfg(feature = "google")]
|
|
|
|
{
|
|
|
|
tracing::info!("Built with `google` feature");
|
|
|
|
tracing::info!(
|
|
|
|
"Environment variables `AIP_PREDICT_ROUTE` and `AIP_HEALTH_ROUTE` will be respected."
|
|
|
|
);
|
|
|
|
if let Ok(env_predict_route) = std::env::var("AIP_PREDICT_ROUTE") {
|
|
|
|
app = app.route(&env_predict_route, post(vertex_compatibility));
|
|
|
|
}
|
|
|
|
if let Ok(env_health_route) = std::env::var("AIP_HEALTH_ROUTE") {
|
|
|
|
app = app.route(&env_health_route, get(health));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// add layers after routes
|
|
|
|
app = app
|
2023-04-25 11:11:18 +00:00
|
|
|
.layer(Extension(info))
|
2023-07-21 14:56:30 +00:00
|
|
|
.layer(Extension(health_ext.clone()))
|
2023-02-28 09:19:32 +00:00
|
|
|
.layer(Extension(compat_return_full_text))
|
|
|
|
.layer(Extension(infer))
|
2024-01-29 10:20:08 +00:00
|
|
|
.layer(Extension(compute_type))
|
2023-07-21 14:56:30 +00:00
|
|
|
.layer(Extension(prom_handle.clone()))
|
2023-09-27 08:40:18 +00:00
|
|
|
.layer(OtelAxumLayer::default())
|
2023-02-17 17:22:00 +00:00
|
|
|
.layer(cors_layer);
|
2022-10-11 08:36:51 +00:00
|
|
|
|
2023-06-16 14:25:11 +00:00
|
|
|
if ngrok {
|
|
|
|
#[cfg(feature = "ngrok")]
|
|
|
|
{
|
|
|
|
use ngrok::config::TunnelBuilder;
|
|
|
|
|
|
|
|
let _ = addr;
|
|
|
|
|
|
|
|
let authtoken =
|
|
|
|
ngrok_authtoken.expect("`ngrok-authtoken` must be set when using ngrok tunneling");
|
|
|
|
|
2023-07-19 09:59:58 +00:00
|
|
|
let edge = ngrok_edge.expect("`ngrok-edge` must be set when using ngrok tunneling");
|
|
|
|
|
|
|
|
let tunnel = ngrok::Session::builder()
|
2023-06-16 14:25:11 +00:00
|
|
|
.authtoken(authtoken)
|
|
|
|
.connect()
|
|
|
|
.await
|
|
|
|
.unwrap()
|
2023-07-19 09:59:58 +00:00
|
|
|
.labeled_tunnel()
|
|
|
|
.label("edge", edge);
|
2023-06-16 14:25:11 +00:00
|
|
|
|
|
|
|
let listener = tunnel.listen().await.unwrap();
|
2023-07-21 14:56:30 +00:00
|
|
|
|
|
|
|
// Run prom metrics and health locally too
|
|
|
|
tokio::spawn(
|
|
|
|
axum::Server::bind(&addr)
|
|
|
|
.serve(
|
|
|
|
Router::new()
|
|
|
|
.route("/health", get(health))
|
|
|
|
.route("/metrics", get(metrics))
|
|
|
|
.layer(Extension(health_ext))
|
|
|
|
.layer(Extension(prom_handle))
|
|
|
|
.into_make_service(),
|
|
|
|
)
|
|
|
|
//Wait until all requests are finished to shut down
|
|
|
|
.with_graceful_shutdown(shutdown_signal()),
|
|
|
|
);
|
2023-06-16 14:25:11 +00:00
|
|
|
|
|
|
|
// Run server
|
|
|
|
axum::Server::builder(listener)
|
|
|
|
.serve(app.into_make_service())
|
|
|
|
//Wait until all requests are finished to shut down
|
|
|
|
.with_graceful_shutdown(shutdown_signal())
|
2023-07-10 12:47:15 +00:00
|
|
|
.await?;
|
2023-06-16 14:25:11 +00:00
|
|
|
}
|
|
|
|
#[cfg(not(feature = "ngrok"))]
|
|
|
|
{
|
|
|
|
let _ngrok_authtoken = ngrok_authtoken;
|
|
|
|
let _ngrok_domain = ngrok_domain;
|
|
|
|
let _ngrok_username = ngrok_username;
|
|
|
|
let _ngrok_password = ngrok_password;
|
|
|
|
|
|
|
|
panic!("`text-generation-router` was compiled without the `ngrok` feature");
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Run server
|
|
|
|
axum::Server::bind(&addr)
|
|
|
|
.serve(app.into_make_service())
|
|
|
|
// Wait until all requests are finished to shut down
|
|
|
|
.with_graceful_shutdown(shutdown_signal())
|
2023-07-10 12:47:15 +00:00
|
|
|
.await?;
|
2023-06-16 14:25:11 +00:00
|
|
|
}
|
2023-07-10 12:47:15 +00:00
|
|
|
Ok(())
|
2022-10-11 14:50:54 +00:00
|
|
|
}
|
2022-10-18 13:19:03 +00:00
|
|
|
|
|
|
|
/// Shutdown signal handler
|
|
|
|
async fn shutdown_signal() {
|
|
|
|
let ctrl_c = async {
|
|
|
|
signal::ctrl_c()
|
|
|
|
.await
|
|
|
|
.expect("failed to install Ctrl+C handler");
|
|
|
|
};
|
|
|
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
let terminate = async {
|
|
|
|
signal::unix::signal(signal::unix::SignalKind::terminate())
|
|
|
|
.expect("failed to install signal handler")
|
|
|
|
.recv()
|
|
|
|
.await;
|
|
|
|
};
|
|
|
|
|
|
|
|
#[cfg(not(unix))]
|
|
|
|
let terminate = std::future::pending::<()>();
|
|
|
|
|
|
|
|
tokio::select! {
|
|
|
|
_ = ctrl_c => {},
|
|
|
|
_ = terminate => {},
|
|
|
|
}
|
|
|
|
|
|
|
|
tracing::info!("signal received, starting graceful shutdown");
|
2023-02-13 12:02:45 +00:00
|
|
|
opentelemetry::global::shutdown_tracer_provider();
|
2022-10-18 13:19:03 +00:00
|
|
|
}
|
2023-01-31 16:04:00 +00:00
|
|
|
|
2023-02-03 11:43:37 +00:00
|
|
|
impl From<i32> for FinishReason {
|
|
|
|
fn from(finish_reason: i32) -> Self {
|
2023-09-27 08:40:18 +00:00
|
|
|
let finish_reason = text_generation_client::FinishReason::try_from(finish_reason).unwrap();
|
2023-02-03 11:43:37 +00:00
|
|
|
match finish_reason {
|
|
|
|
text_generation_client::FinishReason::Length => FinishReason::Length,
|
|
|
|
text_generation_client::FinishReason::EosToken => FinishReason::EndOfSequenceToken,
|
|
|
|
text_generation_client::FinishReason::StopSequence => FinishReason::StopSequence,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-31 16:04:00 +00:00
|
|
|
/// Convert to Axum supported formats
|
|
|
|
impl From<InferError> for (StatusCode, Json<ErrorResponse>) {
|
|
|
|
fn from(err: InferError) -> Self {
|
|
|
|
let status_code = match err {
|
|
|
|
InferError::GenerationError(_) => StatusCode::FAILED_DEPENDENCY,
|
|
|
|
InferError::Overloaded(_) => StatusCode::TOO_MANY_REQUESTS,
|
|
|
|
InferError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
|
|
|
InferError::IncompleteGeneration => StatusCode::INTERNAL_SERVER_ERROR,
|
feat: supports openai chat completions API (#1427)
This PR adds support to make TGI a drop in replacement for OpenAI
clients by exposing the same HTTP interface.
Notes
- TGI inits a single model at startup so the `model` field is unused in
HTTP requests.
- `max_tokens` and `stream` should work as expected but other params may
be (unimplemented or not supported)
General approach
- fetch the `tokenizer_config` at startup from the hub
- pass `tokenizer_config` into `Infer` so we have it at request time
- use the `chat_template` on the config to format chat request
- parse jinja template and render chat string
- pass inputs into existing generate function
- wrap generation output in expected structure before returning
# How to test
### Streaming curl
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{
"model": "tgi",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is deep learning?"
}
],
"stream": true,
"max_tokens": 20
}' \
-H 'Content-Type: application/json'
```
It is also possible to use the `openai` python library and change the
base url
### 🌊 STREAMING REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=True
)
# iterate and print stream
for message in chat_completion:
print(message)
# ChatCompletionChunk(id='', choices=[Choice(delta=ChoiceDelta(content=' that', function_call=None, role='assistant', tool_calls=None), finish_reason=None, index=2, logprobs=None)], created=1704486761, model='', object='text_completion', system_fingerprint='')
```
### 🚗 SYNCHRONOUS REQUEST
```python
from openai import OpenAI
# init the client but point it to TGI
client = OpenAI(
base_url="http://localhost:3000/v1",
api_key="not needed for a local LLM"
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{"role": "system", "content": "You are a helpful assistant." },
{"role": "user", "content": "What is deep learning?"}
],
stream=False
)
print(chat_completion)
# ChatCompletion(id='', choices=[Choice(finish_reason=None, index=0, logprobs=None, message=ChatCompletionMessage(content='\nDeep learning is a new field of research that has been gaining traction in the last ...', role='assistant', function_call=None, tool_calls=None))], created=1704486762, model='', object='text_completion', system_fingerprint='', usage=CompletionUsage(completion_tokens=100, prompt_tokens=76, total_tokens=176))
```
## How to run dev
```bash
cd text-generation-inference/server
MASTER_ADDR=127.0.0.1 MASTER_PORT=5555 text-generation-server serve --trust-remote-code gpt2
```
***note many of the existing `chat_templates` use non standard `jinja`
(ie. adding a `raise` to the template) which will throw an error when
parsing; hence using `upstage/SOLAR-10.7B-Instruct-v1.0` since it has a
valid template
```bash
cd text-generation-inference/router
cargo run -- --tokenizer-name upstage/SOLAR-10.7B-Instruct-v1.0
```
trigger
```bash
curl localhost:3000/v1/chat/completions \
-X POST \
-d '{ "model": "gpt-3.5-turbo", "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What is the IP address of the Google DNS servers?" } ], "stream": true, "max_tokens": 20, "logprobs": true }' \
-H 'Content-Type: application/json'
```
^ supports `stream: true` and `stream: false` requests
2024-01-16 10:07:41 +00:00
|
|
|
InferError::TemplateError(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
2024-04-16 13:02:46 +00:00
|
|
|
InferError::ToolError(_) => StatusCode::UNPROCESSABLE_ENTITY,
|
2023-01-31 16:04:00 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
(
|
|
|
|
status_code,
|
|
|
|
Json(ErrorResponse {
|
|
|
|
error: err.to_string(),
|
2023-03-07 17:52:22 +00:00
|
|
|
error_type: err.error_type().to_string(),
|
2023-01-31 16:04:00 +00:00
|
|
|
}),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<InferError> for Event {
|
|
|
|
fn from(err: InferError) -> Self {
|
|
|
|
Event::default()
|
|
|
|
.json_data(ErrorResponse {
|
|
|
|
error: err.to_string(),
|
2023-03-07 17:52:22 +00:00
|
|
|
error_type: err.error_type().to_string(),
|
2023-01-31 16:04:00 +00:00
|
|
|
})
|
|
|
|
.unwrap()
|
|
|
|
}
|
|
|
|
}
|