Loading model... This may take some time.
You are attempting to use Flash Attention 2.0 with a model not initialized on GPU. Make sure to move the model to GPU after initializing it on CPU with model.to('cuda').
find where this complaint is coming from and fix it. return entire script.
import io
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from transformers import pipeline
import torch
import soundfile as sf
import numpy as np
- audio_file: audio file (wav, mp3, etc)
- task: "transcribe" or "translate"
"""
if task not in ("transcribe", "translate"):
raise HTTPException(status_code=400, detail="Invalid task parameter")
contents = await audio_file.read()
try:
audio_bytes = io.BytesIO(contents)
waveform, sample_rate = sf.read(audio_bytes, dtype='float32')
except Exception as e:
raise HTTPException(status_code=400, detail=f"Could not read audio file: {e}")
if waveform.ndim > 1:
# Convert to mono by averaging channels if needed
waveform = waveform.mean(axis=1)
# Whisper expected sample rate is 16000 Hz; resample if necessary
target_sr = 16000
if sample_rate != target_sr:
import torchaudio.transforms as T
waveform_tensor = torch.from_numpy(waveform).unsqueeze(0) # shape [1, n_samples]
resampler = T.Resample(orig_freq=sample_rate, new_freq=target_sr)
waveform = resampler(waveform_tensor).squeeze(0).numpy()
sample_rate = target_sr
# The transformer pipeline accepts numpy array audio in waveform form
print(f"Starting {task} task for file: {audio_file.filename}")
try:
with torch.inference_mode():
outputs = pipe(
waveform,
chunk_length_s=30,
generate_kwargs={"task": task},
return_timestamps=False,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
text = outputs.get('text', '').strip()
print("Finished transcription task")
return {"text": text}
The warning:
code
You are attempting to use Flash Attention 2.0 with a model not initialized on GPU. Make sure to move the model to GPU after initializing it on CPU with `model.to('cuda')`.
indicates that the model pipeline's underlying model was initialized on CPU first, then Flash Attention 2.0 was requested (which requires the model on GPU), but the .to('cuda') call was not made properly or at the right time.
In the transformers pipeline, the device=0 parameter instructs it to move the model to GPU, but when model_kwargs includes attn_implementation="flash_attention_2", sometimes this can break the automatic device placement or the model loading logic if that argument is passed incorrectly to the pipeline instantiation.
How to fix this?
Load the model explicitly on CPU first,
Then move the model to GPU using .to('cuda'),
Then create the pipeline using that model (or set device but avoid passing model_kwargs that confuse device placement).
Alternatively:
Some versions of the transformers pipeline don't handle model_kwargs fully, so you may want to explicitly load the model and tokenizer, move to cuda, then build the pipeline with the model.
Given this, I will do the following fixes:
Import AutoModelForCTC or WhisperForConditionalGeneration and AutoTokenizer explicitly.
Load the model with attn_implementation="flash_attention_2" on CPU first.
Move model to CUDA.
Create the pipeline with the model, tokenizer, and device CUDA.
Remove the model_kwargs={"attn_implementation": ...} from the pipeline constructor.
If the model is openai/whisper-large-v3-turbo, it should be loaded as a Whisper model from transformers.
The official transformers Whisper model class is WhisperForConditionalGeneration.
Here is the entire corrected script.
python
import io
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from transformers import pipeline, WhisperForConditionalGeneration, WhisperProcessor
import torch
import soundfile as sf
import numpy as np
app = FastAPI(
title="Fast Whisper Turbo HTTP API",
description="Ultra-fast Whisper V3 Turbo inference HTTP server"
)
# Allow CORS for testing from WinForms if needed
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Enable cudnn autotuner to find best algorithm for your hardware & input sizes
torch.backends.cudnn.benchmark = True
print("Loading model... This may take some time.")
# Explicitly load model and processor (tokenizer + feature extractor)
model_name = "openai/whisper-large-v3-turbo"
# Load processor first
processor = WhisperProcessor.from_pretrained(model_name)
# Load model on CPU with attn_implementation set to "flash_attention_2"
model = WhisperForConditionalGeneration.from_pretrained(
model_name,
torch_dtype=torch.float16,
attn_implementation="flash_attention_2",
device_map=None, # Load CPU first
)
# Move model to GPU
model.to("cuda")
# Create pipeline with model and processor, set device=0 for GPU
pipe = pipeline(
task="automatic-speech-recognition",
model=model,
tokenizer=processor,
device=0, # Device 0 == cuda:0
)
print("Model loaded on GPU.")
@app.post("/transcribe")
async def transcribe(
audio_file: UploadFile = File(...),
task: str = Form("transcribe")
):
"""
Transcribe or translate audio file.
- audio_file: audio file (wav, mp3, etc)
- task: "transcribe" or "translate"
"""
if task not in ("transcribe", "translate"):
raise HTTPException(status_code=400, detail="Invalid task parameter")
contents = await audio_file.read()
try:
audio_bytes = io.BytesIO(contents)
waveform, sample_rate = sf.read(audio_bytes, dtype='float32')
except Exception as e:
raise HTTPException(status_code=400, detail=f"Could not read audio file: {e}")
if waveform.ndim > 1:
# Convert to mono by averaging channels if needed
waveform = waveform.mean(axis=1)
# Whisper expected sample rate is 16000 Hz; resample if necessary
target_sr = 16000
if sample_rate != target_sr:
import torchaudio.transforms as T
waveform_tensor = torch.from_numpy(waveform).unsqueeze(0) # shape [1, n_samples]
resampler = T.Resample(orig_freq=sample_rate, new_freq=target_sr)
waveform = resampler(waveform_tensor).squeeze(0).numpy()
sample_rate = target_sr
# The transformer pipeline accepts numpy array audio in waveform form
print(f"Starting {task} task for file: {audio_file.filename}")
try:
with torch.inference_mode():
outputs = pipe(
waveform,
chunk_length_s=30,
generate_kwargs={"task": task},
return_timestamps=False,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
text = outputs.get('text', '').strip()
print("Finished transcription task")
return {"text": text}
Summary of changes:
Load WhisperProcessor and WhisperForConditionalGeneration explicitly.
Load model on CPU with attn_implementation="flash_attention_2".
Move model to CUDA using model.to("cuda") (this fixes the flash attention complaint).
Pass model and processor to the pipeline.
Set device=0 for the pipeline.
Removed model_kwargs from pipeline constructor, because we set attn_implementation at model load time.
This guarantees the model is on GPU before inference and supports Flash Attention 2.0.
If you don't want to explicitly load model and processor, another (less robust) way would be: