Workshop on Speech Perception, Part 1: Probing acoustic, phonemic and orthographic information in Wav2Vec2#

Interpretability & Explainability in AI, MSc A.I., University of Amsterdam, June 2024

This notebook includes contributions by: Marianne de Heer Kloots, Marta Grasa & Charlotte Pouw.

Probing Audio models#

In Week 1, you trained probes on the hidden states of a fine-tuned RoBERTa model, to gain insights into how sentiment is represented in this model across layers. In this notebook, you will perform similar analyses on an audio-based Transformer model: Wav2Vec2. This self-supervised model learns powerful representations of speech from raw audio data and can be applied to many downstream tasks, including Automatic Speech Recognition (ASR) — the conversion from spoken language audio signals into text transcriptions.

Before the rise of deep learning, ASR was performed using a pipeline of different components, each performing a subpart of the task. The ASR pipeline included the following steps:

  1. Feature extraction: extracting relevant time-frequency information from the raw audio signal.

  2. Acoustic modelling: mapping the extracted audio features to a sequence of phonemes, the smallest meaningful units in speech. [1]

  3. Language modelling: mapping the sequence of phonemes to a sequence of written words.

Self-supervised speech models such as Wav2Vec2 are able to perform all of the above steps in an end-to-end fashion. In this assignment, we will evaluate the model’s output performance on text transcription at the output layer as well as earlier layers, and we will compare this to the implicit encoding of other representations relevant to the ASR task, such as phonemes.

[1^] Phonemes are abstractions over speech sound variations — called (allo)phones — that are perceived as the same sound by native speakers of a language. For example, the /t/ phoneme in English is pronounced slightly differently at the start of a word vs. when it’s preceded by other consonants: <tone> [tʰoʊn] starts with the aspirated allophone [tʰ], whereas <stone> [stoʊn] includes the unaspirated allophone [t] (see this page for some visualizations). Phonetic transcriptions, written [bɪtʰwi:n skwɛəɹ bɹækʰɪts], capture such differences, whereas phonemic transcriptions, written /bɪtwin slæʃɪs/, only use the restricted set of symbols within a language’s phonological inventory — i.e., its phonemes. On the other hand, phonemes do refer to pronunciations, and do not necessarily match with orthographic characters. For example, the words <fit>, <phone>, and <laugh> all contain the same phoneme: /f/. Since this phoneme is written in several different ways (<f>, <ph>, <gh>), it can be useful for an ASR model to have (or learn) representations of phonemes at an intermediate stage between the audio signal and its text transcription. (As you may have noticed, orthographic transcriptions are written <between angle brackets>.)

# @title Some helper functions
phoneme_mapping = {
    'p': 'p',
    'b': 'b',
    't': 't',
    'd': 'd',
    'k': 'k',
    'g': 'g',
    'dx': 'dx',
    'f': 'f',
    'v': 'v',
    'dh': 'dh',
    'th': 'th',
    's': 's',
    'z': 'z',
    'r': 'r',
    'q': 'q',
    'w': 'w',
    'y': 'y',
    'jh': 'jh',
    'ch': 'ch',
    'iy': 'iy',
    'eh': 'eh',
    'ey': 'ey',
    'ae': 'ae',
    'aw': 'aw',
    'ay': 'ay',
    'oy': 'oy',
    'ow': 'ow',
    'uh': 'uh',
    'ah': 'ah',
    'ax': 'ah',
    'ax-h': 'ah',
    'aa': 'aa',
    'ao': 'aa',
    'er': 'er',
    'axr': 'er',
    'hh': 'hh',
    'hv': 'hh',
    'ih': 'ih',
    'ix': 'ih',
    'l': 'l',
    'el': 'l',
    'm': 'm',
    'em': 'm',
    'n': 'n',
    'en': 'n',
    'nx': 'n',
    'ng': 'ng',
    'eng': 'ng',
    'sh': 'sh',
    'zh': 'sh',
    'uw': 'uw',
    'ux': 'uw',
    'pcl': 'sil',
    'bcl': 'sil',
    'tcl': 'sil',
    'dcl': 'sil',
    'kcl': 'sil',
    'gcl': 'sil',
    'h#': 'sil',
    'pau': 'sil',
    'epi': 'sil'
}

def convert_phon_utterance(example, phoneme_mapping=phoneme_mapping):
  """
  Map phonetic annotations to a smaller set of phonemes (defined in the phoneme_mapping dict).
  """
  utterance = example['phonetic_detail']['utterance']
  new_utterance = [phoneme_mapping[phone] for phone in utterance]
  example['phonetic_detail']['utterance'] = new_utterance
  return example

def set_seed(seed):
    """Set random seed."""
    if seed == -1:
        seed = random.randint(0, 1000)
    np.random.seed(seed)
    random.seed(seed)
    torch.manual_seed(seed)

    # if you are using GPU
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.enabled = False
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True

def filter_timit_data(timit_split, N_speakers):
  SX_sentences = timit_split.filter(lambda x: x['sentence_type'] == 'SX')
  sentence_subset = [t for t, c in pd.Series(SX_sentences['text']).value_counts().items() if c == 7]
  timit_split = timit_split.filter(lambda x: x["text"] in sentence_subset)
  speaker_subset = [s for s, c in pd.Series(timit_split['speaker_id']).value_counts().items() if c == 5]
  male_speakers = [s for s in speaker_subset if s[0] == 'M']
  female_speakers = [s for s in speaker_subset if s[0] == 'F']
  balanced_N_speakers = min(len(male_speakers), len(female_speakers), N_speakers//2)
  male_speakers = list(np.random.choice(male_speakers, size=balanced_N_speakers, replace=False))
  female_speakers = list(np.random.choice(female_speakers, size=balanced_N_speakers, replace=False))
  speaker_subset = male_speakers + female_speakers
  timit_split = timit_split.filter(lambda x: x["speaker_id"] in speaker_subset)
  return timit_split

def create_timit_subset(full_timit_dataset, train_speakers=60, test_speakers=24):
  phon_converted_timit = full_timit_dataset.map(convert_phon_utterance).rename_column("phonetic_detail", "phonemic_detail")
  timit_subset_train = filter_timit_data(phon_converted_timit['train'], N_speakers=train_speakers)
  timit_subset_test = filter_timit_data(phon_converted_timit['test'], N_speakers=test_speakers)
  timit_subset = DatasetDict({"train": timit_subset_train, "test": timit_subset_test})
  return timit_subset

def plot_audio_annotations(raw_waveform, envelope, envelope_timepoints, word_start_times, word_end_times, words, phoneme_start_times, phoneme_end_times, phonemes, sampling_rate):
  fig, axs = plt.subplots(4, 1, figsize=(30,7.5), sharex=True, gridspec_kw={'height_ratios': [1, 1, .25, .25]})
  librosa.display.waveshow(raw_waveform, sr=sampling_rate, alpha=0.4, ax=axs[0])
  axs[0].plot(envelope_timepoints, envelope, color='red')
  axs[0].set_xlabel('')
  axs[0].set_xlim(0, len(raw_waveform)/sampling_rate)
  axs[0].tick_params(axis='y', which='major', labelsize=12)
  D = librosa.stft(raw_waveform)
  S_db = librosa.amplitude_to_db(np.abs(D), ref=np.max)
  librosa.display.specshow(S_db, ax=axs[1], y_axis='log', x_axis='time', sr=sampling_rate)
  for i, word in enumerate(words):
    start_time = word_start_times[i]
    end_time = word_end_times[i]
    word_position = ((start_time + end_time) / 2)
    axs[2].text(word_position, .45, word, fontweight='bold', ha='center', size=12)
    axs[2].axvline(start_time, color='grey')
    axs[2].axvline(end_time, color='grey')
    axs[2].set_ylabel('words', size=15, rotation=0, va='center', ha='right')
    axs[2].set_yticks([])
  for i, phoneme in enumerate(phonemes):
    start_time = phoneme_start_times[i]
    end_time = phoneme_end_times[i]
    phoneme_position = ((start_time + end_time) / 2)
    axs[3].text(phoneme_position, .45, phoneme, fontweight='bold', ha='center', size=12)
    axs[3].axvline(start_time, color='grey')
    axs[3].axvline(end_time, color='grey')
    axs[3].set_ylabel('phonemes', size=15, rotation=0, va='center', ha='right')
    axs[3].set_yticks([])
  plt.subplots_adjust(wspace=0, hspace=0)
  plt.xlabel("Time (s)", size=15)
  plt.tick_params(axis='x', which='major', labelsize=15)
  plt.show()

Configuration#

Don’t forget to enable the GPU runtime at the top! (Runtime -> Change runtime type)

Install and import packages:

%%capture
# we need an older version of the datasets library for loading the TIMIT dataset
!pip install -q datasets==1.18.3 transformers jiwer
import torch
from transformers import Wav2Vec2Processor, Wav2Vec2ForCTC
from datasets import load_dataset, load_metric, DatasetDict
import jiwer
from jiwer import wer, cer
import librosa
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd
import random
import string
import matplotlib.pyplot as plt
import IPython.display as ipd
import warnings
from collections import Counter
import gc
from tqdm import *

Connect to the GPU:

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

Set a random seed:

set_seed(42)

The TIMIT dataset#

We will use the TIMIT Acoustic-Phonetic Continuous Speech Corpus, which contains sentence recordings of 630 speakers of eight major American-English dialects. Each speaker read aloud ten sentences, which were designed to elicit a wide variety of speech sounds. The corpus includes time-aligned transcriptions, as well as the raw waveform for each spoken sentence, sampled at a rate of 16 kHz.

In this notebook we’ll work with an adjusted subset of the TIMIT corpus, using only the ‘phonetically compact’ (SX) sentences (see the TIMIT README for details), and a subset of 84 speakers in total (60 in our train set, 24 in our test set), where the number of recordings is balanced for speaker sex and id.

ToDo 1: TIMIT data#

Load the TIMIT corpus and our filtered subset by running the cell below.

Explore some examples in the train set: what does the audio signal look like?

# load & preprocess our TIMIT subset
timit = load_dataset("timit_asr", "clean")
timit_subset = create_timit_subset(timit)

# remove the original TIMIT dataset
del timit
gc.collect()

ToThink 1: Audio visualizations#

Look at the example below, which visualizes one recording out of the TIMIT subset, and try to understand it (open the image in a separate browser tab if you want to zoom in). This plot includes two visualizations of the audio signal: on top, the raw audio waveform in blue, with its (upper) amplitude envelope in red, and below it, the spectrogram. Although Wav2Vec2 takes the raw waveform as input, some speech models (such as Whisper) work based on derived features more like the spectrogram.

Make sure you know on a general level how to read these visualizations: what is on the y-axis of the waveform plot? What do the colors in the spectrogram plot mean?

timit_annotation_example.png

ToDo 2: Amplitude envelope#

To familiarize ourselves with audio data, we will compute the amplitude envelope ourselves. This is a very basic acoustic feature over the audio signal tracking the upper contour of the raw waveform, but nonetheless forms a useful basis for example for analyses of speech rhythm. Here, we will approximate the amplitude envelope by taking the maximum value over a sliding window throughout the waveform.

## TODO: complete the function below for computing the amplitude envelope over the waveform

def amplitude_envelope(audio_signal, sampling_rate, window_length=200, hop_length=160):
    """
    Compute the amplitude envelope for a given audio_signal using a sliding window.
    """
    signal_envelope = []

    # omit the last frame
    window_starts = range(0, len(audio_signal), hop_length)[:-1]

    for start in window_starts:
        # select the current window
        current_window = # YOUR CODE HERE

        # compute the maximum amplitude value in the current window
        envelope_value = # YOUR CODE HERE

        # append the maximum amplitude to the envelope array
        signal_envelope.append(envelope_value)

    idx = range(0, len(signal_envelope))
    envelope_timepoints = librosa.frames_to_time(idx, sr=sampling_rate, hop_length=hop_length)

    return np.array(signal_envelope), envelope_timepoints

ToSubmit 1: Visualizing a TIMIT example#

Now, we’ll recreate the visualizations above for another example out of our TIMIT subset. Retrieve all needed data for this example from timit_subset['train'] and include the resulting plot below in your report, together with the correct transcription provided in the dataset, and a transcription generated by Wav2Vec2 (we will do this in the next step below). You can simply save and downsize the image below to the page width of your report; don’t worry to much about readability for this plot.

Tip: Some details are available on the timit_asr Dataset Card on HuggingFace. For our subset, we have replaced the phonetic_detail column by a phonemic_detail one, where the original transcriptions are mapped to a smaller set (following Lee & Hon ‘89; see the phoneme_mapping dictionary for details).

# Select a data item you want to examine (different from 0)
item_index = 0

# Retrieve the waveform from the data
raw_waveform = # YOUR CODE HERE

# Sampling frequency
sampling_rate = # YOUR CODE HERE

# Listen to the audio
ipd.display(ipd.Audio(data=np.asarray(raw_waveform), autoplay=False, rate=sampling_rate))

# Print corresponding text
text = # YOUR CODE HERE
print("Text:", text)

# Compute the amplitude envelope
envelope, envelope_timepoints = # YOUR CODE HERE

# Word annotations (note: times should be in seconds!)
words = # YOUR CODE HERE
word_start_times = # YOUR CODE HERE (note: times should be in seconds!)
word_end_times = # YOUR CODE HERE (note: times should be in seconds!)

# Phoneme annotations (note: times should be in seconds!)
phonemes = # YOUR CODE HERE
phoneme_start_times = # YOUR CODE HERE (note: times should be in seconds!)
phoneme_end_times = # YOUR CODE HERE (note: times should be in seconds!)

plot_audio_annotations(raw_waveform, envelope, envelope_timepoints, word_start_times, word_end_times, words, phoneme_start_times, phoneme_end_times, phonemes, sampling_rate)

The Wav2Vec2 Model#

The Wav2Vec2 model was proposed in wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations by Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli.

The model takes raw audio waveforms as input and splits them into fixed-size frames of 25 milliseconds. During pre-training, some of these frames are masked and the model has to predict the correct speech unit for the masked position. In doing so, the model learns powerful speech representations in a self-supervised manner.

After pre-training, the model can be fine-tuned for several downstream tasks. We will investigate a model version that is fine-tuned for Automatic Speech Recognition, i.e. predicting written transcriptions that correspond to the spoken input. More specifically, the model was fine-tuned to predict a character for each of the 25ms-frames that we discussed above. These characters are then collapsed into well-formed transcriptions using Connectionist Temporal Classification.

ToThink 2: The Wav2Vec2 Architecture#

Read this blogpost about Wav2Vec2 and make sure you understand the different components inside the model.

ToDo 3: The Wav2Vec2 Architecture#

Load the model and processor by running the cell below. Examine the architecture carefully. What does the final lm_head component do?

Tip: you can also check the model card and uploaded files for this model on HuggingFace.

# Load model and processor
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")
processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")

# Set model to evaluation mode
model.eval()
model.to(DEVICE)

ToSubmit 1 (ctd): Generating a transcription#

We will now generate a transcription for the TIMIT example you selected above with Wav2Vec2. Complete the function for transcribing audio below and include the generated transcription in your report. Are there any mistakes?

def transcribe_audio(audio_waveforms, sampling_rate, model=model, processor=processor):
  """
  Returns a list of transcriptions (text strings) for a list of audio waveforms.
  """
  # preprocess audio
  inputs = processor(audio_waveforms, sampling_rate=sampling_rate, return_tensors="pt", padding=True).input_values.to(DEVICE)

  # retrieve model logits
  logits = # YOUR CODE HERE

  # find the predicted character ids and decode
  predicted_ids = # YOUR CODE HERE
  transcription = # YOUR CODE HERE

  return transcription

# make sure your function works for a list of waveforms (even though we pass only a single one here)
audio_waveforms = [raw_waveform]
transcribe_audio(audio_waveforms, sampling_rate)

Evaluating model transcriptions with WER and CER#

Once we are able to obtain a transcription for an audio segment from the model, we would like to know how accurate that transcription is. To measure this, we use two different metrics: Word Error Rate (WER) and Character Error Rate (CER). We use these to measure what proportion of the words (or characters) were not correctly transcribed. The word error rate is defined as:

\[WER = \frac{\text{Substitutions} + \text{Insertions} + \text{Deletions}}{\text{Total number of words}}\]

Where

  • Substitutions indicates the number of words in the audio which were substituted with another word in the transcript

  • Insertion indicates how many words which do not appear in the audio do appear in the transcript

  • Deletions indicates how many words are in the audio but do not appear in the transcription

  • Total number of words refers to the number of words in the correct transcription

CER is defined in the same way, but on a character level instead of a word level.

We will use implementations of the CER and WER metrics from the jiwer library.

ToDo 4: Exploring CER and WER with a toy example#

Familiarize yourself with WER and CER and their corresponding jiwer functions. Below is a toy example. What changes to transcribed_text make WER vs. CER go up or down?

correct_text = 'The quick brown fox jumps over the lazy dog.'
transcribed_text = 'the quik brown Fox jum ps ova th lazy dog'

print(wer(correct_text, transcribed_text))
print(cer(correct_text, transcribed_text))

print("\n Word-level analysis")
out_words = jiwer.process_words(correct_text, transcribed_text)
print(jiwer.visualize_alignment(out_words, show_measures=False))

print("\n Character-level analysis")
out_char = jiwer.process_characters(correct_text, transcribed_text)
print(jiwer.visualize_alignment(out_char, show_measures=False))

It is now time to apply these evaluation metrics to some generated model transcripts. For this purpose, we’ll take an even smaller sample of our TIMIT subset to evaluate the recorded sentences for only two speakers (our speaker_subset).

# Create a smaller subset of only two speakers
speaker_ids = list(np.unique(timit_subset['train']['speaker_id']))
speaker_subset = [speaker_ids[0], speaker_ids[-1]]
print('Speakers in subset:', speaker_subset)
timit_speaker_subset = timit_subset['train'].filter(lambda x: x["speaker_id"] in speaker_subset)

# Generate transcriptions for all sentences recorded by these speakers
model_transcriptions = {speaker_id: [] for speaker_id in speaker_subset}
correct_transcriptions = {speaker_id: [] for speaker_id in speaker_subset}
for speaker_id in speaker_subset:
  speaker_sentences = timit_speaker_subset.filter(lambda x: x["speaker_id"] == speaker_id)
  audio_waveforms = [a['array'] for a in speaker_sentences['audio']]
  correct_transcriptions[speaker_id] = speaker_sentences['text']
  model_transcriptions[speaker_id] = transcribe_audio(audio_waveforms, 16000)

print('MODEL TRANSCRIPTIONS:\n', model_transcriptions)
print('CORRECT TRANSCRIPTIONS:\n', correct_transcriptions)

You may have noticed that the formatting of the correct transcriptions does not correspond with the output of the model (the Wav2Vec2 output vocabulary does not include lowercase characters or punctuation marks).

To obtain fair error metrics, we make the formatting match:

formatted_correct_transcriptions = {}
for speaker in correct_transcriptions.keys():
    formatted_correct_transcriptions[speaker] = []
    for transcription in correct_transcriptions[speaker]:
        # make uppercase and remove punctuation (except for ')
        formatted_correct_transcriptions[speaker].append(transcription.upper().translate(str.maketrans('', '', string.punctuation.replace("'", ""))))

print('MODEL TRANSCRIPTIONS:\n', model_transcriptions)
print('CORRECT TRANSCRIPTIONS:\n', formatted_correct_transcriptions)

ToDo 5: WER and CER on the speaker_subset#

Compute the WER and CER for each of the transcripts you obtained using the model.

# YOUR CODE HERE

ToThink 3: Inspecting (mis)transcriptions#

Inspect a few of the mistranscriptions and listen to the corresponding audio. Can you think of a reason for these mistakes?

item_index = 6
print(timit_speaker_subset[item_index]['speaker_id'], timit_speaker_subset[item_index]['text'])
ipd.display(ipd.Audio(timit_speaker_subset[item_index]['audio']['array'], rate=timit_speaker_subset[item_index]['audio']['sampling_rate']))

Effect of noise#

Up until now, we have been only transcribing high-quality audio. This is not always the case, since there may be some noise in the recordings we want to transcribe. Ideally, ASR systems are robust to noise, so it is useful to identify what noise levels cause problems for transcriptions.

We can simulate noise by adding some gaussian noise to recordings from the TIMIT dataset. We will use a “noise factor” parameter to determine how much noise (in units of the standard deviation of the audio) we will add:

ToDo 6: Adding noise to audio#

Create a function to add gaussian noise to an audio array. The standard deviation of the noise should be noise_factortimes the standard deviation of the audio

def add_noise(audio_array, noise_factor):
    # YOUR CODE HERE
    raise NotImplementedError

    return noised_audio

sample_audio = np.asarray(raw_waveform)
noised_audio = add_noise(sample_audio,1)
ipd.display(ipd.Audio(noised_audio, rate=16000))

To analyze how the transcription quality changes when the audio is noisy, we’ll create transcriptions for audio with different levels of noise, and then evaluate them.

Note: Computing the results for each individual transcription and averaging them will give slightly different results from considering the whole set of transcriptions at once when counting insertions/deletions/substitutions and total number of words. In the function below, we use the latter.

def noisy_wer_cer(noise_factor):
    noisy_model_transcriptions = {speaker_id: [] for speaker_id in speaker_subset}

    # Generated transcriptions
    for speaker_id in speaker_subset:
        speaker_sentences = timit_speaker_subset.filter(lambda x: x["speaker_id"] == speaker_id)
        audio_waveforms = [add_noise(a['array'], noise_factor) for a in speaker_sentences['audio']]
        noisy_model_transcriptions[speaker_id] = transcribe_audio(audio_waveforms, 16000)

    # Evaluation
    all_correct = sum(formatted_correct_transcriptions.values(), [])
    all_model = sum(noisy_model_transcriptions.values(), [])
    return wer(all_correct, all_model), cer(all_correct, all_model)

random.seed(0)
np.random.seed(0)
avg_wer, avg_cer = noisy_wer_cer(0.25)

print('Average WER: ', avg_wer)
print('Average CER: ', avg_cer)

ToSubmit 2: WER and CER over noisy audio#

Compute the average WER and CER for different noise_factor values noise_factor = [0, 0.2, 0.4, 0.6, 0.8, 1], over all transcriptions from the speaker_subset. Save them to vectors called noisy_wer and noisy_cer, and use the code below to plot them. Add the plot to your submission, together with a brief (max. 2 sentence) description of the patterns you observe.

noise_factors = [0, 0.2, 0.4, 0.6, 0.8, 1]

# YOUR CODE HERE
fig, axes = plt.subplots(1, 1, figsize=(8,5))

axes.plot(noisy_wer, 'o-', lw=2, markersize=3, label='WER')
axes.plot(noisy_cer, 'o-', lw=2, markersize=3, label='CER')

axes.legend()
axes.set_ylim(0,1)
axes.set_xlabel("Noise factor")
axes.set_ylabel("Error rate")
axes.set_xticks(range(len(noise_factors)), noise_factors, minor=False)

plt.show()

Inspecting orthographic information over model layers using the CTC lens#

We have been looking at the transcriptions the model produces as its output, but we might want to know where in the model information associated with particular transcriptions arises. For a first rough probe of where orthography becomes encoded across layers of Wav2Vec2, we can use the model’s CTC head, which is normally applied to the last layer, as a ‘lens’ to inspect hidden states of earlier layers (a ‘CTC lens’).

Let’s test this on a single transcription:

# CTC lens
def CTC_lens_transcription(layer_hidden_states, model=model):
  layer_logits = model.lm_head(layer_hidden_states)
  layer_pred_ids = torch.argmax(layer_logits, dim=-1)
  layer_transcription = processor.batch_decode(layer_pred_ids)
  return layer_transcription

# an example sentence
example = timit_subset['train'][0]
correct_transcription = example['text']
print(correct_transcription)

# get all hidden states for this sentence
inputs = processor(example['audio']['array'], sampling_rate=16000, return_tensors="pt", padding=True).input_values.to(DEVICE)
with torch.no_grad():
  out = model(inputs, output_hidden_states=True)
for layer in range(model.config.num_hidden_layers + 1):
  print(f'layer {layer}')
  layer_transcription = CTC_lens_transcription(out.hidden_states[layer])
  print(layer_transcription)

ToThink 4: Inspecting layerwise transcriptions#

Does the CTC head produce legible transcriptions only for the output layer, or also for intermediate layers? What does this mean?

We can use the evaluation metrics introduced earlier (WER and CER) to see how the quality of the transcriptions changes through the layers. To do that, we will extract the hidden states for all layers for different recordings, and compute the WER and CER for all examples for each layer.

ToDo 7: Computing WER and CER on the layerwise transcriptions#

Fill in the code below to extract layerwise transcriptions for all sentences in the speaker_subset and measure how the average WER and CER change depending on the layer we extract the transcription from.

layer_wer = []
layer_cer = []

# YOUR CODE HERE
raise NotImplementedError
fig, axes = plt.subplots(1, 1, figsize=(8,5))

axes.plot(layer_wer, 'o-', lw=2, markersize=3, label='WER')
axes.plot(layer_cer, 'o-', lw=2, markersize=3, label='CER')

axes.legend()
axes.set_xlabel("Layer")
axes.set_ylabel("Error rate")

plt.show()

ToSubmit 3: Metrics for orthographic decoding accuracy#

Do you think the WER and CER metrics are equally suitable to examine the layerwise encoding of orthographic information in Wav2Vec2, and why? Add the plot with layerwise results over the speaker_subset to your report, with a brief (1 sentence) description.

Training probes on hidden states#

Phoneme probing classifiers#

With the CTC-lens we can create layerwise measures of orthographic information, which the ASR-finetuned version of Wav2Vec2 is trained to encode. However, we may also want to measure the encoding of other types of information which the model is not explicitly trained for, such as phonemic distinctions.

To do this we can train regression models to predict our features of interest from the hidden states of the model. Here, we will experiment with logistic regression probes to predict phoneme identity. We will first extract a corpus of hidden states to train our probes on.

Concretely, we will perform the following steps to achieve this:

  1. Prepare input: Retrieve the raw waveforms (i.e. audio arrays) from the TIMIT corpus and process them using the Wav2Vec2 processor.

  2. Forward pass: Pass the waveforms through the model with output_hidden_states set to True.

  3. Save hidden states: Save the hidden states in a dictionary, which is organized by Transformer layer index and waveform index. Each waveform will have list of frame-level hidden states.

  4. Sort hidden states per phoneme class: Sort the hidden states by phoneme class using the time-aligned transcriptions from TIMIT.

def extract_hidden_states(model, processor, inputs, num_layers):
    '''
    Extract hidden states from Wav2Vec 2.0 transformer layers.
    :param model: Wav2Vec 2.0 model
    :param processor: Wav2Vec 2.0 processor
    :param inputs: list of TIMIT instances (i.e. timit['train'] or timit['test'])
    :return: dictionary containing frame-level hidden states saved per transformer layer and per waveform
    '''

    # Get waveforms
    waveforms = [input["audio"]["array"] for input in inputs]

    # Here we will save all frame-level hidden states, sorted by layer and waveform
    frame_states = {
        layer_idx: {
            waveform_idx: []
            for waveform_idx in range(len(waveforms))
        }
        for layer_idx in range(num_layers)
    }

    for waveform_idx, waveform in enumerate(waveforms):

        print(f'Extracting hidden states from waveform {waveform_idx} out of {len(waveforms)} waveforms...')

        # Process waveform using the Wav2Vec2 processor
        processed_input = processor(waveform, sampling_rate=16000, return_tensors="pt", padding='longest').input_values

        with torch.no_grad():
            input_tensor = torch.tensor(processed_input, device=DEVICE)

            # forward pass
            model_output = model(input_tensor, output_hidden_states=True, output_attentions=False)

            # get all hidden outputs
            transformer_layers = model_output.hidden_states

        # Save frame-level hidden states, organized by layer and waveform
        for layer_idx, layer in enumerate(transformer_layers):
            for waveform in layer:
              for frame in waveform:
                  frame_states[layer_idx][waveform_idx].append(frame.cpu())

    return frame_states

Function to sort the hidden states by phoneme class using the time-aligned transcriptions from TIMIT:

def sort_states_per_phoneme(data, frame_states, num_layers):

    frame_states_per_phoneme = {
        layer_idx: defaultdict(list)
        for layer_idx in range(num_layers)
    }

    for layer_idx, layer in frame_states.items():

        for waveform_idx, waveform in layer.items():

            # retrieve phoneme annotation for the current waveform
            phonemes = data[waveform_idx]["phonemic_detail"]
            phoneme_indeces = defaultdict(list)

            for start, stop, phoneme in zip(phonemes['start'], phonemes['stop'], phonemes['utterance']):

                # divide start and stop point by sample rate (16000 hz) and frame length (0.020 sec)
                start_index = math.floor((start / 16000) / 0.020)
                stop_index = math.ceil((stop / 16000) / 0.020)

                phoneme_indeces[phoneme].extend(range(start_index, stop_index))

            # find hidden states corresponding to phoneme indeces and save them per layer and per phoneme
            for phoneme, indeces in phoneme_indeces.items():
                phoneme_states = [waveform[idx] for idx in indeces if idx < len(waveform)]
                frame_states_per_phoneme[layer_idx][phoneme].extend(phoneme_states)

    return frame_states_per_phoneme

ToDo 8: Retrieving model hidden states#

Extract the hidden states for training and testing our probes (this might take some time):

import math
from collections import defaultdict

# number of hidden layers of the transformer model + the input embeddings
num_layers = model.config.num_hidden_layers + 1

# Extract frame-level hidden states for training and testing the probes (make sure you pass the data subset)
frame_states_train = # YOUR CODE HERE
frame_states_test = # YOUR CODE HERE

# Sort the hidden states by phoneme (make sure you pass the data subset)
phoneme_states_train = # YOUR CODE HERE
phoneme_states_test = # YOUR CODE HERE

It is now time to train and evaluate our probes. We will define a probing classifier for each layer of the Wav2Vec2 model to see how phoneme information is represented across layers. We will be using Logistic Regression as our classification models (but feel free to experiment with other classifiers such as SVM).

warnings.filterwarnings("ignore")

# Define layer-wise probes, to be trained and tested on frame-level Wav2Vec2 embeddings
layer_probes = {
    layer_idx: LogisticRegression(solver="liblinear", penalty="l2", max_iter=10)
    for layer_idx in range(num_layers)
}

Helper functions for putting the data in the right format for Logistic Regression models, and for balancing the data:

def phoneme_data_loader(hidden_state_dict, layer_idx, target_phonemes=None):
    X = []
    y = []

    for phoneme, hidden_state_list in hidden_state_dict[layer_idx].items():
        for i in hidden_state_list:
            if i != None and phoneme != 'q':
                if target_phonemes == None:
                    X.append(np.array(i))
                    y.append(phoneme)
                else:
                    if phoneme in target_phonemes:
                        X.append(np.array(i))
                        y.append(phoneme)

    return X, y

def balance_classes(X_instances, y_labels):

    balanced_data_X = []
    balanced_data_y = []

    class_distribution = Counter(y_labels)
    num_instances_per_class = min(class_distribution.values())

    for label in class_distribution.keys():

        i = 1
        instances = []
        labels = []

        for x, y in zip(X_instances, y_labels):
            if y == label:
                instances.append(x)
                labels.append(y)
                if i == num_instances_per_class:
                    balanced_data_X.extend(instances)
                    balanced_data_y.extend(labels)
                    break
                i += 1

    return balanced_data_X, balanced_data_y

ToDo 9: Training & evaluating probes#

Train and evaluate the probing classifier for each layer (this will take some time). Examine the difference in probing accuracy when predicting different categories of phonemes (i.e. stops, fricatives, nasals, glides, vowels). The different categories are explained here.

phoneme_dict = {
    'stops': ['p', 't', 'k', 'b', 'd', 'g'],
    'fricatives': ['f', 'v', 'th', 'dh', 's', 'z', 'sh'],
    'nasals': ['m', 'n', 'ng'],
    'approximants': ['l', 'w', 'y', 'hh'],
    'vowels': ['aa', 'ow', 'iy', 'eh', 'uh']
}

# Save layer-wise accuracies for each phoneme category
accs_per_category = []

for phoneme_category, target_phonemes in phoneme_dict.items():

  print(f"Training layer-wise probes to predict {phoneme_category}...")
  accs = []

  # Train and test an individual probe for each layer
  for layer_idx in range(num_layers):

    # Put train data in the right format for our probing classifier + balance classes
    train_X, train_y = phoneme_data_loader(phoneme_states_train, layer_idx, target_phonemes=target_phonemes)
    train_X, train_y = balance_classes(train_X, train_y)

    if layer_idx == 0:
      print("Balanced class distribution TRAIN:", Counter(train_y))

    # Train model
    layer_probes[layer_idx].fit(train_X, train_y)

    # Put test data in the right format for our probing classifier + balance classes
    test_X, test_y = phoneme_data_loader(phoneme_states_test, layer_idx, target_phonemes=target_phonemes)
    test_X, test_y = balance_classes(test_X, test_y)

    if layer_idx == 0:
      print("Balanced class distribution TEST:", Counter(test_y))

    # Predict
    test_pred = layer_probes[layer_idx].predict(test_X)
    test_acc = accuracy_score(test_y, test_pred)
    print(f'Accuracy for layer {layer_idx}:', test_acc)
    accs.append(test_acc)

  accs_per_category.append(accs)

ToDo 10: Plotting layerwise phoneme probing accuracies#

Plot the layer-wise accuracies per phoneme category.

for accs in accs_per_category:

  # Plot layer-wise probing accuracy per phoneme category
  plt.plot(range(num_layers), accs, marker='.')
  plt.title(f'Representation of phonemes in Wav2Vec 2.0', fontsize=16)
  plt.xlabel('Wav2Vec 2.0 layer', fontsize=12)
  plt.xticks(range(num_layers), range(1, 14), fontsize=12)
  plt.ylabel('Probing accuracy', fontsize=12)
  plt.legend(list(phoneme_dict.keys()))
  plt.ylim((0.4, 1.0))

plt.show()

Probing acoustic information#

We can also train probes on simpler acoustic features, such as the amplitude envelope. The envelope is a continuous variable, so we can use simple linear regression probes instead of logistic regression.

ToDo 11: Decoding amplitude envelope from model hidden states#

Use the code below to train frame-wise probes decoding amplitude envelope values out of model hidden states. For evaluation, use the coefficient of determination (\(R^2\)) computed by the default sklearn score function for linear regressions.

train_envelopes = {
    waveform_idx: amplitude_envelope(timit_subset['train'][waveform_idx]["audio"]["array"], sampling_rate=16000, window_length=400, hop_length=320)[0]
    for waveform_idx in range(len(timit_subset['train']))
    }
test_envelopes = {
    waveform_idx: amplitude_envelope(timit_subset['test'][waveform_idx]["audio"]["array"], sampling_rate=16000, window_length=400, hop_length=320)[0]
    for waveform_idx in range(len(timit_subset['test']))
    }
def envelope_data_loader(frame_states, envelopes, layer_idx):
  for wi, ae in envelopes.items():
    # if envelope & frame states differ in length (usually by 1, due to rounding differences),
    # we cut them to the same length here
    if ae.shape[0] != np.array(frame_states[layer_idx][wi]).shape[0]:
      min_size = np.min([ae.shape[0], np.array(frame_states[layer_idx][wi]).shape[0]])-1
      envelopes[wi] = ae[:min_size]
      frame_states[layer_idx][wi] = frame_states[layer_idx][wi][:min_size]
  X = np.concatenate(list(frame_states[layer_idx].values()))
  y = np.concatenate(list(envelopes.values()))
  return X, y
envelope_probes = {
    layer: LinearRegression() for layer in range(num_layers)
}

envelope_probe_scores = []

# YOUR CODE HERE
  # Plot layer-wise probing accuracy for amplitude envelope
  plt.plot(range(num_layers), envelope_probe_scores, marker='.')
  plt.title(f'Representation of amplitude envelope in Wav2Vec 2.0', fontsize=16)
  plt.xlabel('Wav2Vec 2.0 layer', fontsize=12)
  plt.xticks(range(num_layers), range(1, 14), fontsize=12)
  plt.ylabel('Probing score ($R^2$)', fontsize=12)
  plt.ylim(0.4, 1)
  plt.show()

CTC-probing orthographic information#

Finally, we’ll compare the model’s layerwise encoding of acoustic and phonemic information to the orthographic accuracy we can obtain by decoding transcriptions out of the model’s hidden layers. Since we don’t train the CTC lens, we can just evaluate the character error rate on our timit_subset['test'] set.

ToDo 12: Computing layerwise CER on the timit_subset['test'] set#

Compute the CER over model layers using the CTC-lens for layerwise transcriptions of all sentences in the timit_subset['test'] set.

Hint: You can use the frame_states_test dictionary computed above, but you’ll need to reshape the states stored in there into a torch.Tensor with the right dimensions to be read by the CTC_lens_transcription function.

correct_transcriptions = # YOUR CODE HERE
formatted_correct_transcriptions = # YOUR CODE HERE
layerwise_transcriptions = {layer: [] for layer in range(num_layers)}
layerwise_cer = []
  # Plot layer-wise character error rate for test sentences
  plt.plot(range(num_layers), layerwise_cer, marker='.')
  plt.title(f'Representation of orthography in Wav2Vec 2.0', fontsize=16)
  plt.xlabel('Wav2Vec 2.0 layer', fontsize=12)
  plt.xticks(range(num_layers), range(1, 14), fontsize=12)
  plt.ylabel('Character error rate (CER)', fontsize=12)
  plt.show()

ToSubmit 4: Comparing layerwise probing results#

Submit the three plots of your probing results (evaluating on the timit_subset['test'] set). Can you make sense of the observed pattern of layerwise results in terms of the processing mechanisms of the Wav2Vec2 architecture? And in terms of the model’s training objective?

Include a brief caption describing differences in the layerwise representation of acoustic, phonemic and orthographic information in Wav2Vec2 and your explanation of this pattern.