Merge branch 'main' into configure-more-params

This commit is contained in:
giubots
2025-05-02 12:23:45 +02:00
committed by GitHub
9 changed files with 126 additions and 57 deletions
+13 -5
View File
@@ -20,6 +20,8 @@ class ServeClientTensorRT(ServeClientBase):
client_uid=None,
model=None,
single_model=False,
use_py_session=False,
max_new_tokens=225,
send_last_n_segments=10,
no_speech_thresh=0.45,
clip_audio=False,
@@ -39,6 +41,8 @@ class ServeClientTensorRT(ServeClientBase):
language (str, optional): The language for transcription. Defaults to None.
client_uid (str, optional): A unique identifier for the client. Defaults to None.
single_model (bool, optional): Whether to instantiate a new model for each client connection. Defaults to False.
use_py_session (bool, optional): Use python session or cpp session. Defaults to Cpp Session.
max_new_tokens (int, optional): Max number of tokens to generate.
send_last_n_segments (int, optional): Number of most recent segments to send to the client. Defaults to 10.
no_speech_thresh (float, optional): Segments with no speech probability above this threshold will be discarded. Defaults to 0.45.
clip_audio (bool, optional): Whether to clip audio with no valid segments. Defaults to False.
@@ -52,18 +56,20 @@ class ServeClientTensorRT(ServeClientBase):
clip_audio,
same_output_threshold,
)
self.language = language if multilingual else "en"
self.task = task
self.eos = False
self.max_new_tokens = max_new_tokens
if single_model:
if ServeClientTensorRT.SINGLE_MODEL is None:
self.create_model(model, multilingual)
self.create_model(model, multilingual, use_py_session=use_py_session)
ServeClientTensorRT.SINGLE_MODEL = self.transcriber
else:
self.transcriber = ServeClientTensorRT.SINGLE_MODEL
else:
self.create_model(model, multilingual)
self.create_model(model, multilingual, use_py_session=use_py_session)
# threading
self.trans_thread = threading.Thread(target=self.speech_to_text)
@@ -75,7 +81,7 @@ class ServeClientTensorRT(ServeClientBase):
"backend": "tensorrt"
}))
def create_model(self, model, multilingual, warmup=True):
def create_model(self, model, multilingual, warmup=True, use_py_session=False):
"""
Instantiates a new model, sets it as the transcriber and does warmup if desired.
"""
@@ -85,7 +91,9 @@ class ServeClientTensorRT(ServeClientBase):
device="cuda",
is_multilingual=multilingual,
language=self.language,
task=self.task
task=self.task,
use_py_session=use_py_session,
max_output_len=self.max_new_tokens,
)
if warmup:
self.warmup()
@@ -140,7 +148,7 @@ class ServeClientTensorRT(ServeClientBase):
mel, duration = self.transcriber.log_mel_spectrogram(input_bytes)
last_segment = self.transcriber.transcribe(
mel,
text_prefix=f"<|startoftranscript|><|{self.language}|><|{self.task}|><|notimestamps|>"
text_prefix=f"<|startoftranscript|><|{self.language}|><|{self.task}|><|notimestamps|>",
)
if ServeClientTensorRT.SINGLE_MODEL:
ServeClientTensorRT.SINGLE_MODEL_LOCK.release()
+1 -1
View File
@@ -106,7 +106,7 @@ class Client:
# start websocket client in a thread
self.ws_thread = threading.Thread(target=self.client_socket.run_forever)
self.ws_thread.setDaemon(True)
self.ws_thread.daemon = True
self.ws_thread.start()
self.transcript = []
+11 -7
View File
@@ -153,7 +153,7 @@ class TranscriptionServer:
def initialize_client(
self, websocket, options, faster_whisper_custom_model_path,
whisper_tensorrt_path, trt_multilingual
whisper_tensorrt_path, trt_multilingual, trt_py_session=False,
):
client: Optional[ServeClientBase] = None
@@ -168,6 +168,7 @@ class TranscriptionServer:
client_uid=options["uid"],
model=whisper_tensorrt_path,
single_model=self.single_model,
use_py_session=trt_py_session,
send_last_n_segments=options.get("send_last_n_segments", 10),
no_speech_thresh=options.get("no_speech_thresh", 0.45),
clip_audio=options.get("clip_audio", False),
@@ -260,7 +261,7 @@ class TranscriptionServer:
return np.frombuffer(frame_data, dtype=np.float32)
def handle_new_connection(self, websocket, faster_whisper_custom_model_path,
whisper_tensorrt_path, trt_multilingual):
whisper_tensorrt_path, trt_multilingual, trt_py_session=False):
try:
logging.info("New client connected")
options = websocket.recv()
@@ -279,7 +280,7 @@ class TranscriptionServer:
if self.backend.is_tensorrt():
self.vad_detector = VoiceActivityDetector(frame_rate=self.RATE)
self.initialize_client(websocket, options, faster_whisper_custom_model_path,
whisper_tensorrt_path, trt_multilingual)
whisper_tensorrt_path, trt_multilingual, trt_py_session=trt_py_session)
return True
except json.JSONDecodeError:
logging.error("Failed to decode JSON from client")
@@ -311,11 +312,12 @@ class TranscriptionServer:
return True
def recv_audio(self,
websocket,
websocket,
backend: BackendType = BackendType.FASTER_WHISPER,
faster_whisper_custom_model_path=None,
whisper_tensorrt_path=None,
trt_multilingual=False):
trt_multilingual=False,
trt_py_session=False):
"""
Receive audio chunks from a client in an infinite loop.
@@ -342,7 +344,7 @@ class TranscriptionServer:
"""
self.backend = backend
if not self.handle_new_connection(websocket, faster_whisper_custom_model_path,
whisper_tensorrt_path, trt_multilingual):
whisper_tensorrt_path, trt_multilingual, trt_py_session=trt_py_session):
return
try:
@@ -366,6 +368,7 @@ class TranscriptionServer:
faster_whisper_custom_model_path=None,
whisper_tensorrt_path=None,
trt_multilingual=False,
trt_py_session=False,
single_model=False):
"""
Run the transcription server.
@@ -393,7 +396,8 @@ class TranscriptionServer:
backend=BackendType(backend),
faster_whisper_custom_model_path=faster_whisper_custom_model_path,
whisper_tensorrt_path=whisper_tensorrt_path,
trt_multilingual=trt_multilingual
trt_multilingual=trt_multilingual,
trt_py_session=trt_py_session,
),
host,
port
@@ -23,7 +23,8 @@ from tensorrt_llm._utils import (str_dtype_to_torch, str_dtype_to_trt,
from tensorrt_llm.bindings import GptJsonConfig, KVCacheType
from tensorrt_llm.runtime import PYTHON_BINDINGS, ModelConfig, SamplingConfig
from tensorrt_llm.runtime.session import Session, TensorInfo
if PYTHON_BINDINGS:
from tensorrt_llm.runtime import ModelRunnerCpp
SAMPLE_RATE = 16000
N_FFT = 400
@@ -255,8 +256,17 @@ class WhisperDecoding:
class WhisperTRTLLM(object):
def __init__(self, engine_dir, assets_dir=None, device=None, is_multilingual=False,
language="en", task="transcribe"):
def __init__(self,
engine_dir,
assets_dir=None,
device=None,
is_multilingual=False,
language="en",
task="transcribe",
use_py_session=False,
num_beams=1,
debug_mode=False,
max_output_len=96):
world_size = 1
runtime_rank = tensorrt_llm.mpi_rank()
runtime_mapping = tensorrt_llm.Mapping(world_size, runtime_rank)
@@ -268,13 +278,6 @@ class WhisperTRTLLM(object):
self.num_languages = encoder_config['num_languages']
is_multilingual = (decoder_config['vocab_size'] >= 51865)
self.encoder = WhisperEncoding(engine_dir)
self.decoder = WhisperDecoding(engine_dir,
runtime_mapping,
debug_mode=False)
self.n_mels = self.encoder.n_mels
# self.tokenizer = get_tokenizer(num_languages=self.encoder.num_languages,
# tokenizer_dir=assets_dir)
self.device = device
self.tokenizer = get_tokenizer(
is_multilingual,
@@ -282,7 +285,28 @@ class WhisperTRTLLM(object):
language=language,
task=task,
)
self.filters = mel_filters(self.device, self.encoder.n_mels, assets_dir)
if use_py_session:
self.encoder = WhisperEncoding(engine_dir)
self.decoder = WhisperDecoding(engine_dir,
runtime_mapping,
debug_mode=False)
else:
json_config = GptJsonConfig.parse_file(engine_dir / 'decoder' /
'config.json')
assert json_config.model_config.supports_inflight_batching
runner_kwargs = dict(engine_dir=engine_dir,
is_enc_dec=True,
max_batch_size=1,
max_input_len=3000,
max_output_len=max_output_len,
max_beam_width=num_beams,
debug_mode=debug_mode,
kv_cache_free_gpu_memory_fraction=0.9,
cross_kv_cache_fraction=0.5)
self.model_runner_cpp = ModelRunnerCpp.from_dir(**runner_kwargs)
self.filters = mel_filters(self.device, self.n_mels, assets_dir)
self.use_py_session = use_py_session
def log_mel_spectrogram(
self,
@@ -355,16 +379,38 @@ class WhisperTRTLLM(object):
prompt_id = torch.tensor(prompt_id)
batch_size = mel.shape[0]
decoder_input_ids = prompt_id.repeat(batch_size, 1)
encoder_output, encoder_output_lengths = self.encoder.get_audio_features(mel, mel_input_lengths)
encoder_max_input_length = torch.max(encoder_output_lengths).item()
output_ids = self.decoder.generate(decoder_input_ids,
encoder_output,
encoder_max_input_length,
encoder_output_lengths,
self.tokenizer.eot,
max_new_tokens=max_new_tokens,
num_beams=num_beams)
if self.use_py_session:
encoder_output, encoder_output_lengths = self.encoder.get_audio_features(mel, mel_input_lengths)
encoder_max_input_length = torch.max(encoder_output_lengths).item()
output_ids = self.decoder.generate(decoder_input_ids,
encoder_output,
encoder_max_input_length,
encoder_output_lengths,
self.tokenizer.eot,
max_new_tokens=max_new_tokens,
num_beams=num_beams)
else:
with torch.no_grad():
if isinstance(mel, list):
mel = [
m.transpose(1, 2).type(
str_dtype_to_torch("float16")).squeeze(0)
for m in mel
]
else:
mel = mel.transpose(1, 2)
outputs = self.model_runner_cpp.generate(
batch_input_ids=decoder_input_ids,
encoder_input_features=mel,
encoder_output_lengths=mel_input_lengths // 2,
max_new_tokens=max_new_tokens,
end_id=self.tokenizer.eot,
pad_id=self.tokenizer.eot,
num_beams=num_beams,
output_sequence_lengths=True,
return_dict=True)
torch.cuda.synchronize()
output_ids = outputs['output_ids'].cpu().numpy().tolist()
texts = []
for i in range(len(output_ids)):
text = self.tokenizer.decode(output_ids[i][0]).strip()
@@ -379,7 +425,8 @@ class WhisperTRTLLM(object):
batch_size=1,
num_beams=1,
padding_strategy="max",
):
max_new_tokens=96,
):
mel = mel.type(str_dtype_to_torch(dtype))
mel = mel.unsqueeze(0)
# repeat the mel spectrogram to match the batch size
@@ -393,7 +440,13 @@ class WhisperTRTLLM(object):
dtype=torch.int32,
device=mel.device)
predictions = self.process_batch(mel, features_input_lengths, text_prefix, num_beams)
predictions = self.process_batch(
mel,
features_input_lengths,
text_prefix,
num_beams,
max_new_tokens=max_new_tokens
)
prediction = predictions[0]
# remove all special tokens in the prediction