Whisper audio transcription powered by AWS Batch and AWS Inferentia
OpenAI’s Whisper mannequin is a well-liked and extremely correct computerized speech recognition (ASR) mannequin, based mostly on the transformer structure. It’s launched beneath the MIT license and accessible for business use.
Many prospects need to host the Whisper mannequin on AWS however don’t want real-time or steady on-line inference. This is nice, as a result of it opens a chance for decreasing value by processing audio as a batch workload asynchronously utilizing AWS Batch. Customers can go even additional to tune their value by utilizing AWS Inferentia – a customized silicon choice constructed by AWS. (If you do want real-time or steady on-line inference, take a look at our earlier weblog publish on that matter).
In this publish, we’ll discover the right way to arrange and deploy a scalable, performant, and cost-efficient answer for batch audio transcription utilizing the Whisper mannequin deployed on demand utilizing an AWS Batch compute setting – powered by AWS Inferentia. We’ll describe the right way to implement this answer as an event-driven structure, triggering the pipeline mechanically when audio recordsdata arrive in Amazon Simple Storage Service (Amazon S3). We’ll describe the right way to construct a Docker picture that features a script to organize audio recordsdata for inference utilizing AWS Inferentia. And we’ll give you a cloud formation template that may automate the deployment of this answer so you can begin experimenting in a couple of minutes.
Solution Overview
AWS Batch
AWS Batch is a totally managed batch computing service that plans, schedules, and runs your containerized batch ML, simulation, and analytics workloads throughout the total vary of AWS compute choices, reminiscent of Amazon Elastic Container Service (Amazon ECS), Amazon Elastic Kubernetes Services (Amazon EKS), AWS Fargate, and Amazon EC2 Spot or On-Demand Instances. AWS Batch lets builders, scientists, and engineers throughout industries effectively run a whole bunch of 1000’s of batch computing jobs whereas optimizing compute sources.
AWS Inferentia overview
Amazon Elastic Compute Cloud (Amazon EC2) Inf2 situations are purpose-built for deep studying (DL) inference. They ship excessive efficiency on the lowest value in Amazon EC2 for generative synthetic intelligence (AI) fashions, together with giant language fashions (LLMs) and imaginative and prescient transformers. You can use Inf2 situations to run your inference functions for textual content summarization, code technology, video and picture technology, speech recognition, personalization, fraud detection, and extra.
Inf2 situations are powered by AWS Inferentia2, the second-generation AWS Inferentia chip. The AWS Neuron SDK helps builders deploy fashions on AWS Inferentia chips by integrating natively with frameworks like PyTorch and TensorFlow.
Overall structure
Next, let’s evaluation the structure for our answer. we’ve made the code and step-by-step information for implementing this accessible in GitHub.
Figure 1 beneath exhibits the event-driven Whisper audio transcription pipeline answer utilizing Amazon EventBridge and AWS Batch. Since Batch creates a containerized compute setting, it requires us to construct and stage a container picture in Amazon Elastic Container Registry (Amazon ECR). In the Batch job definition, we specify the container picture, the Amazon Machine Image (AMI), and Amazon EC2 occasion sort.
Figure 1. Event-driven audio transcription pipeline with Amazon EventBridge and AWS Batch
We’ll focus on every numbered structure characteristic.
- Build docker picture and push to Amazon ECR – We construct the docker picture at design time and push it to ECR. The docker picture contains all of the libraries and python script code to retrieve the mannequin artifacts and the audio file from Amazon S3 and course of it utilizing the Whisper mannequin encoder and decoder.
- Add audio transcription job to AWS Batch job queue on file add – When an audio file is uploaded to Amazon S3 within the designated Bucket and folder, EventBridge captures the PutEvent and triggers Batch so as to add the file to its job queue.
- Batch launches compute setting to course of queued jobs – If there’s no lively compute setting (CE), Batch will provision a managed CE to course of every job within the queue till the queue is empty. The CE is created utilizing an Amazon EC2 Inf2 occasion, an AMI that features the Neuron SDK libraries, and the container picture uploaded to ECR in step one. These configurations are outlined within the Batch Job Definition file.
- Batch processes job and writes transcription to Amazon S3 output location – The compute setting processes every audio file and writes a transcription file to an Amazon S3 bucket. Once the job queue is empty, Batch shuts down the situations within the CE.
Next, we’ll reveal the right way to implement this answer.
Implementing the answer
Before continuing, make sure you’ve glad the next conditions.
Prerequisites
- Create an AWS account for those who don’t have already got one and check in. Create a person utilizing AWS Identity Center (successor to AWS Single Sign-On) with full administrator permissions as described in Add customers. Sign in to the AWS Management Console utilizing the Identity Center person you simply created.
- Install the AWS Command Line Interface (AWS CLI) in your native improvement machine and create a profile for the admin person as described at Set Up the AWS CLI.
- Install Docker in your native machine.
- Clone Our GitHub repository to your native machine.
With these conditions glad, you may proceed with configuring the answer.
Choose AMI
The AMI we’ll select for our AWS Batch compute setting shall be an Amazon Linux AMI that’s ECS-optimized. This AMI has Neuron drivers pre-installed to assist AWS Inferentia2 situations. Remember that AMIs are region-specific, and since we’re utilizing the us-east-1 Region, we’ll use this neighborhood AMI printed by AWS: ami-07979ad4c774a29ab. We can search and discover this AMI within the Application and OS Images (Amazon Machine Image) catalog search within the Amazon EC2 Launch an occasion display screen (proven in Figure 2 beneath).
Figure 2. Amazon Linux AMI with Neuron drivers preinstalled
Build the Docker picture
After cloning the GitHub repo, find the Dockerfile. Notice that the referenced base picture installs the AWS Neuron SDK for PyTorch 1.13.1 on AWS Inferentia.
FROM public.ecr.aws/neuron/pytorch-inference-neuronx:1.13.1-neuronx-py310-sdk2.18.1-ubuntu20.04
We will construct the picture utilizing the next command:
docker construct --no-cache -t whisper:newest .
If profitable, the output from the construct ought to appear like Figure 3 beneath.
Figure 3. Successful construct of the docker picture
Push picture to ECR
With the picture constructed domestically, we have to create a repository in ECR and push our picture to it in order that will probably be accessible for Batch to make use of when launching compute environments.
aws ecr create-repository --repository-name whisper
We then tag the Docker picture to match the repository URL.
docker tag whisper:newest [your-account-id].dkr.ecr.[your-region].amazonaws.com/whisper:newest
Finally, we push the picture to the Amazon ECR repository.
docker push [your-account-id].dkr.ecr.[your-region].amazonaws.com/whisper:newest
Create mannequin artifacts
We present a script known as export-model.py that may create the encoder and decoder mannequin recordsdata that shall be utilized in our inference script. Let’s check out the code on this script.
First, we obtain a pattern dataset to make use of for our Neuron hint.
# Load a pattern from the dataset
dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clear", break up="validation")
# pattern #3 is ~9.9seconds and produces 33 output tokens + pad token
pattern = dataset[3]["audio"]
input_features = processor(pattern["array"], sampling_rate=pattern["sampling_rate"], return_tensors="pt").input_features
Next, we set the parameters. For our instance, we select the whisper-large-v3 checkpoint of the Whisper mannequin, utilizing the suffix to dynamically create the distinctive identifier for the mannequin.
# choose the specified mannequin measurement
#suffix="tiny"
#suffix="small"
#suffix="medium"
suffix="large-v3"
model_id=f"openai/whisper-{suffix}"
Next, we load the tokenizer and mannequin.
processor = WhisperProcessor.from_pretrained(model_id)
mannequin = WhisperForConditionalGeneration.from_pretrained(model_id, torchscript=True)
The batch measurement controls what number of recordsdata ought to be processed in parallel. In our answer, we’re processing one file at a time, so we’ll set the batch_size to 1.
batch_size=1
The output_attentions parameter is a flag that specifies whether or not the mannequin will return the eye weights for every layer of the mannequin. You want this if you wish to add timestamps or carry out debugging. You pay a penalty in latency for producing this output so we’ll set this to false.
output_attentions=False
The most decoder size specifies the utmost variety of tokens the mannequin will produce. Since we’re not involved with metering output tokens, we’ll set this to the utmost of 448.
max_dec_len=448
In the script file, you’ll discover that we simplify the encoder and decoder features to make them work with Neuron gadgets. These simplified features will change current strategies however are designed to be backwards suitable. We may even want a brand new variable known as forward_neuron to invoke the mannequin on inf2. For brevity, we’re solely exhibiting the encoder perform right here:
def enc_f(self, input_features, attention_mask, **kwargs):
if hasattr(self, 'forward_neuron'):
out = self.forward_neuron(input_features, attention_mask)
else:
out = self.forward_(input_features, attention_mask, return_dict=True)
return BaseModelOutput(**out)
We outline the identify of the mannequin artifact.
model_filename=f"whisper_{suffix}_{batch_size}_neuron_encoder.pt"
To export the mannequin, we have to run a hint utilizing the torch_neuronx library.
neuron_encoder = torch_neuronx.hint(
mannequin.mannequin.encoder,
inp,
compiler_args='--model-type=transformer --enable-saturate-infinity --auto-cast=all',
compiler_workdir='./enc_dir',
inline_weights_to_neff=False)
neuron_encoder.save(model_filename)
Similarly, we have to do the identical for the decoder.
model_filename=f"whisper_{suffix}_{batch_size}_{max_dec_len}_neuron_decoder.pt"
neuron_decoder = torch_neuronx.hint(
mannequin.mannequin.decoder,
inp,
compiler_args='--model-type=transformer --enable-saturate-infinity --auto-cast=all',
compiler_workdir='./dec_dir',
inline_weights_to_neff=True)
neuron_decoder.save(model_filename)
Once we save these .pt recordsdata to the native drive we will copy them to an Amazon S3 location designated for mannequin artifacts. The AWS CloudFormation template introduced within the subsequent part creates the Batch job with the encoder and decoder recordsdata referenced as setting variables (proven in Figure 4 beneath).
Figure 4. Configurable setting variables proven from the AWS Batch console
For a step-by-step information on creating these mannequin artifacts, confer with the README.md file of the Git repo.
Deploy the answer
You can use the CloudFormation template to speed up the deployment of this answer with these steps:
- Choose Launch Stack beneath to launch the answer within the us-east-1 Region:

- For Stack identify, enter a singular stack identify.
- Set the parameters.
Figure 5. Parameter values for the CFT
- Acknowledge the capabilities.
- Choose Create stack.
Before shifting on, let’s check out the inference.py script to know the way it processes the audio recordsdata.
Inference.py
First we’ll specify the variety of Neuron cores. For the inf2.8xlarge occasion, there’s one Neuron chip with 2 cores.
import os
os.environ['NEURON_RT_NUM_CORES']='2'
Using the torchaudio bundle, we’re in a position to generate waveforms from the audio and create chunks of 30 second clips.
import torchaudio
# copy from s3
s3_client.download_file(input_bucket_name, input_file_key, input_file_key.break up("/")[-1])
audio_path = input_file_key.break up("/")[-1]
# Load the audio file
waveform, sample_rate = torchaudio.load(audio_path)
# Ensure the audio is within the right format (mono, 16kHz)
if waveform.form[0] > 1:
waveform = torch.imply(waveform, dim=0, keepdim=True)
if sample_rate != 16000:
waveform = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)(waveform)
# chunk the audio
chunk_size = 30*16000 # 30 seconds * 16000 samples / second
chunks = waveform.break up(chunk_size, dim=1)
We ship every chunk to the mannequin for inference and append it to the transcriptions array object.
transcriptions = []
for chunk in chunks:
inputs = processor(chunk.squeeze().numpy(), sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
predicted_ids = mannequin.generate(inputs.input_features)
transcription = processor.decode(predicted_ids[0])
transcriptions.append(transcription)
Finally, we mix the transcriptions right into a textual content file and write it out to Amazon S3.
# Extract the file identify from the S3 object key
audio_path = input_file_key.break up("/")[-1]
# Combine the transcriptions
full_transcription = " ".be part of(transcriptions)
# Append txt to authentic file identify and write transcription file domestically
output_filename = audio_path + '.txt'
file = open(output_filename, 'w')
file.write(full_transcription)
file.shut()
# write to S3
s3_client.put_object(Body=full_transcription, Bucket=output_bucket_name, Key=output_file_prefix + output_filename)
Testing the answer
To check our audio transcription, we used audio recordsdata of interviews from NASA’s Expedition 46, which started in 2015. This was the 46th mission to the International Space Station (ISS) and the final expedition of the ISS year-long mission. These audio recordsdata had been launched into the general public area by NASA and can be found for obtain from the Internet Archive.
This mission included two Russian cosmonauts who had been interviewed within the preflight information convention. This additionally allowed us to check Whisper’s transcription for each English and Russian.
Upload audio recordsdata
We chosen 5 audio recordsdata totaling 3 GB and uploaded them to our audio-input folder of our Amaz$on S3 bucket.
Figure 6. Audio recordsdata uploaded to the Amazon S3 enter folder
As every add completes, occasion triggers from Amazon EventBridge added them to our AWS Batch job queue.
Monitor AWS Batch job processing
We can confirm that our jobs are being processed by monitoring the Batch dashboard.
Figure 7. AWS Batch job queue dashboard
While the roles are operating, we will monitor the utilization from the Compute Environments dashboard by enabling Container Insights.
Figure 8. Monitoring the utilization of our compute environments utilizing Container Insights
These metrics solely report the utilization of the CPU and the reminiscence within the CE. But we additionally want to observe the Inferentia2 Neuron cores themselves. To do that, we put in a config script utilizing a Batch Launch Template to push metrics to Amazon CloudWatch. This is an excerpt from the CloudFormation template.
# Configure Neuron Monitor
cat > /tmp/monitor.conf << EOF
{
"interval": "1s",
"neuron_runtimes": [
{
"tag_filter": ".*",
"metrics": [
{
"type": "neuroncore_counters"
},
{
"type": "memory_used"
},
{
"type": "neuron_runtime_vcpu_usage"
},
{
"type": "execution_stats"
}
]
}
],
"system_metrics": [
{
"type": "vcpu_usage"
},
{
"type": "memory_info"
},
{
"period": "2s",
"type": "neuron_hw_counters"
}
]
}
EOF
# Run Neuron Monitor and pipe the output to Neuron Monitor CloudWatch
/choose/aws/neuron/bin/neuron-monitor -c /tmp/monitor.conf
| /choose/aws/neuron/bin/neuron-monitor-cloudwatch.py
--namespace neuron_monitor -d instance_id --region us-east-1 &
Now when our Batch jobs run, we will view the utilization of the Neuron cores in CloudWatch.
Figure 9. Validating the output transcription recordsdata written to Amazon S3
Validate the transcription
When the roles full, we will verify that the output recordsdata with the transcriptions are written to our output folder in Amazon S3.
Figure 10. Validating the output transcription recordsdata written to Amazon S3
Viewing the preflight information convention transcription, we will see that our pipeline labored as anticipated, transcribing each English and Russian.
<|startoftranscript|><|en|><|transcribe|> The launch of Soyuz TMA-16M will return three veteran house flyers to the International Space Station, with two of them embarking on the first-ever year-long mission to this automobile. One-year expedition crew member, retired U.S. Navy Captain Scott Kelly, has collected 180 days in house throughout three missions. Kelly piloted Space Shuttle Discovery's service mission to the Hubble Space Telescope in 1999.<|endoftext|>
Further in our transcription file, we discover responses from cosmonaut Mikhail Korniyenko transcribed in Russian.
<|startoftranscript|><|ru|><|transcribe|><|notimestamps|> Как вы себя чувствуете? Я очень хорошо. Мои коллеги-клубники тоже. Мы рады, что мы здесь, завершили тренировку в США. И я уезжаю в Германию на неделю, а космонавты возвращаются в Россию на последние шесть недель тренировки перед завершением. Хорошо. Что еще?<|endoftext|>
The full transcript written to Amazon S3 demonstrates that our answer labored! The Whisper mannequin transcribed completely different spoken languages in the identical audio file mechanically.
Clean up
To keep away from additional expenses and to maintain your setting tidy, delete the sources created for this answer:
- From the AWS CloudFormation console, delete the stack.
- Delete the audio recordsdata, log recordsdata, and transcription recordsdata from the Amazon S3 buckets.
Conclusion
In this weblog publish, we explored a cost-efficient answer for batch audio transcription utilizing the Whisper mannequin on AWS. We demonstrated the right way to leverage AWS Batch and AWS Inferentia2 to course of audio recordsdata asynchronously, triggered by the arrival of audio recordsdata in Amazon S3. This strategy permits prospects who don’t require real-time or on-line inference to optimize prices by operating the Whisper mannequin in a batch processing setting.
If you’re utilizing AWS Batch and AWS Inferentia2 on your batch audio transcription workloads, e-mail us at [email protected] and inform us about your expertise!
HI-FI News
by way of AWS HPC Blog https://ift.tt/ksRbIrf
September 16, 2024 at 02:36PM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT









