Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

word-level timestamps in transcribe() #869

Merged
merged 26 commits into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
8f9357f
word-level timestamps in `transcribe()`
jongwook Jan 20, 2023
46ea501
moving to `timing.py`
jongwook Jan 21, 2023
cfd2b81
Merge branch 'main' into word-level-timestamps
jongwook Jan 21, 2023
742d2f4
numba implementation for dtw, replacing dtw-python
jongwook Jan 22, 2023
fb12414
Merge branch 'main' into word-level-timestamps
jongwook Jan 22, 2023
80331c0
triton implementation for dtw
jongwook Jan 23, 2023
1d2ed66
add test for dtw implementations
jongwook Jan 23, 2023
b61e8f4
triton implementation of median_filter
jongwook Jan 24, 2023
54f2901
a simple word-level timestamps test
jongwook Jan 24, 2023
8ce6277
add scipy as dev dependency
jongwook Jan 24, 2023
812f446
Merge branch 'main' into word-level-timestamps
jongwook Jan 24, 2023
cd5191f
installs an older version of Triton if CUDA < 11.4
jongwook Jan 24, 2023
f64d8bc
Merge branch 'main' into word-level-timestamps
jongwook Jan 24, 2023
89133bd
Merge branch 'main' into word-level-timestamps
jongwook Jan 24, 2023
d4f9399
fix broken merge
jongwook Jan 24, 2023
040aa04
Merge branch 'main' into word-level-timestamps
jongwook Jan 24, 2023
8e2756b
loosen nvcc version match regex
jongwook Jan 25, 2023
6c431c4
find_alignment() function
jongwook Jan 25, 2023
ff6cbfd
Merge branch 'main' into word-level-timestamps
jongwook Feb 2, 2023
5fa4356
miscellaneous improvements
jongwook Feb 2, 2023
48537aa
skip median filtering when the input is too small
jongwook Feb 2, 2023
8eb29c3
Expose punctuation options in cli and transcribe() (#973)
ryanheise Feb 16, 2023
6ed4c11
Merge branch 'main' into word-level-timestamps
jongwook Mar 6, 2023
31cd418
fix merge error
jongwook Mar 6, 2023
145f325
fix merge error 2
jongwook Mar 6, 2023
2b079c4
annotating that word_timestamps is experimental
jongwook Mar 6, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
find_alignment() function
  • Loading branch information
jongwook committed Jan 25, 2023
commit 6c431c41b1ac57161060f23d7fd4438690674d22
77 changes: 51 additions & 26 deletions whisper/timing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import List, TYPE_CHECKING

from dataclasses import dataclass
import numba
import numpy as np
import torch
Expand Down Expand Up @@ -113,18 +113,34 @@ def dtw(x: torch.Tensor) -> np.ndarray:
return dtw_cpu(x.double().cpu().numpy())


def add_word_timestamps(
@dataclass
class Alignment:
words: List[str]
word_tokens: List[List[int]]
start_times: np.ndarray
end_times: np.ndarray


def find_alignment(
model: "Whisper",
tokenizer: Tokenizer,
text_tokens: List[int],
mel: torch.Tensor,
num_frames: int,
segments: List[dict],
*,
max_qk_layers: int = 6,
medfilt_width: int = 7,
qk_scale: float = 1.0,
):
if len(segments) == 0:
return
) -> Alignment:
tokens = torch.tensor(
[
*tokenizer.sot_sequence,
tokenizer.timestamp_begin,
*text_tokens,
tokenizer.timestamp_begin + num_frames // 2,
tokenizer.eot,
]
).to(model.device)

# install hooks on the cross attention layers to retrieve the attention weights
QKs = [None] * model.dims.n_text_layer
Expand All @@ -135,23 +151,13 @@ def add_word_timestamps(
for i, block in enumerate(model.decoder.blocks)
]

tokens = torch.tensor(
[
*tokenizer.sot_sequence,
tokenizer.timestamp_begin,
*[t for segment in segments for t in segment["tokens"]],
tokenizer.timestamp_begin + mel.shape[-1] // 2,
tokenizer.eot,
]
).to(model.device)

with torch.no_grad():
model(mel.unsqueeze(0), tokens.unsqueeze(0))

for hook in hooks:
hook.remove()

weights = torch.cat(QKs[-6:]) # layers * heads * tokens * frames
weights = torch.cat(QKs[-max_qk_layers:]) # layers * heads * tokens * frames
weights = weights[:, :, :, : num_frames // 2]
weights = median_filter(weights, medfilt_width)
weights = (weights * qk_scale).softmax(dim=-1)
Expand All @@ -167,24 +173,43 @@ def add_word_timestamps(
# These languages don't typically use spaces, so it is difficult to split words
# without morpheme analysis. Here, we instead split words at any
# position where the tokens are decoded as valid unicode points
split_tokens = tokenizer.split_tokens_on_unicode
words, word_tokens = tokenizer.split_tokens_on_unicode(tokens[1:].tolist())
else:
split_tokens = tokenizer.split_tokens_on_spaces
words, word_tokens = tokenizer.split_tokens_on_spaces(tokens[1:].tolist())

words, word_tokens = split_tokens(tokens[1:].tolist())
word_boundaries = np.pad(np.cumsum([len(t) for t in word_tokens]), (1, 0))
start_times = jump_times[word_boundaries[:-1]]
end_times = jump_times[word_boundaries[1:]]

token_sources = np.repeat(np.arange(len(segments)), [len(s["tokens"]) for s in segments])
token_sources = [None] * len(tokenizer.sot_sequence) + list(token_sources)
return Alignment(words, word_tokens, start_times, end_times)


def add_word_timestamps(
segments: List[dict],
model: "Whisper",
tokenizer: Tokenizer,
mel: torch.Tensor,
num_frames: int,
**hyperparams,
):
if len(segments) == 0:
return

text_tokens = [t for segment in segments for t in segment["tokens"]]
alignment = find_alignment(model, tokenizer, text_tokens, mel, num_frames, **hyperparams)

time_offset = segments[0]["seek"] * HOP_LENGTH / SAMPLE_RATE
word_boundaries = np.pad(np.cumsum([len(t) for t in word_tokens]), (1, 0))
start_times = time_offset + jump_times[word_boundaries[:-1]]
end_times = time_offset + jump_times[word_boundaries[1:]]
alignment.start_times = time_offset + alignment.start_times
alignment.end_times = time_offset + alignment.end_times

token_sources = np.repeat(np.arange(len(segments)), [len(s["tokens"]) for s in segments])
token_sources: List[int] = [None] * len(tokenizer.sot_sequence) + list(token_sources)

for segment in segments:
segment["words"] = []

for i, (word, start, end) in enumerate(zip(words, start_times, end_times)):
word_boundaries = np.pad(np.cumsum([len(t) for t in alignment.word_tokens]), (1, 0))
for i, (word, start, end) in enumerate(zip(alignment.words, alignment.start_times, alignment.end_times)):
if word.startswith("<|") or word.strip() in ".,!?、。": # TODO: expand
continue

Expand Down
9 changes: 6 additions & 3 deletions whisper/transcribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ def transcribe(
task: str = decode_options.get("task", "transcribe")
tokenizer = get_tokenizer(model.is_multilingual, language=language, task=task)

if word_timestamps and task == "translate":
warnings.warn("Word-level timestamps on translations may not be reliable.")

def decode_with_fallback(segment: torch.Tensor) -> DecodingResult:
temperatures = [temperature] if isinstance(temperature, (int, float)) else temperature
decode_result = None
Expand Down Expand Up @@ -257,11 +260,11 @@ def add_segment(
if word_timestamps:
current_segments = all_segments[last_segment_index:]
add_word_timestamps(
model,
tokenizer,
segments=current_segments,
model=model,
tokenizer=tokenizer,
mel=mel_segment,
num_frames=segment_size,
segments=current_segments,
)
word_end_timestamps = [w["end"] for s in current_segments for w in s["words"]]
if len(consecutive) > 0 and len(word_end_timestamps) > 0:
Expand Down