|
| 1 | +import numpy as np |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +from pathlib import Path |
| 4 | +from transformers import WhisperProcessor |
| 5 | +from os import path |
| 6 | + |
| 7 | +# --- Configuration --- |
| 8 | +# This must match the model used to generate the data |
| 9 | +MODEL_ID = "onnx-community/lite-whisper-large-v3-ONNX" |
| 10 | +# MODEL_ID = "onnx-community/whisper-large-v3-turbo" |
| 11 | + |
| 12 | +# Directory where the .npy files are stored |
| 13 | +INPUT_DIR = Path("verification_data") |
| 14 | + |
| 15 | +# Number of top tokens to show in the logits plot |
| 16 | +TOP_K_LOGITS = 20 |
| 17 | + |
| 18 | +def plot_mel_spectrogram(features, output_path): |
| 19 | + """Generates and saves a plot of the mel spectrogram.""" |
| 20 | + if features.ndim == 3 and features.shape[0] == 1: |
| 21 | + features = features.squeeze(0) # Remove batch dimension |
| 22 | + |
| 23 | + fig, ax = plt.subplots(figsize=(12, 6)) |
| 24 | + im = ax.imshow(features, aspect='auto', origin='lower', cmap='viridis', interpolation='none') |
| 25 | + fig.colorbar(im, ax=ax, format='%+2.0f dB') |
| 26 | + ax.set_title("Input Mel Spectrogram") |
| 27 | + ax.set_xlabel("Time Steps") |
| 28 | + ax.set_ylabel("Mel Bins") |
| 29 | + plt.tight_layout() |
| 30 | + plt.savefig(output_path) |
| 31 | + print(f"Saved spectrogram plot to {output_path}") |
| 32 | + return fig |
| 33 | + |
| 34 | +def plot_encoder_output(hidden_states, output_path): |
| 35 | + """Generates and saves a plot of the encoder hidden states.""" |
| 36 | + if hidden_states.ndim == 3 and hidden_states.shape[0] == 1: |
| 37 | + hidden_states = hidden_states.squeeze(0) # Remove batch dimension |
| 38 | + |
| 39 | + fig, ax = plt.subplots(figsize=(12, 6)) |
| 40 | + im = ax.imshow(hidden_states, aspect='auto', origin='lower', cmap='viridis', interpolation='none') |
| 41 | + fig.colorbar(im, ax=ax) |
| 42 | + ax.set_title("Encoder Hidden States") |
| 43 | + ax.set_xlabel("Sequence Length") |
| 44 | + ax.set_ylabel("Hidden Dimension") |
| 45 | + plt.tight_layout() |
| 46 | + plt.savefig(output_path) |
| 47 | + print(f"Saved encoder output plot to {output_path}") |
| 48 | + return fig |
| 49 | + |
| 50 | +def plot_logits(logits, tokenizer, output_path): |
| 51 | + """Generates and saves a bar chart of the top K logits.""" |
| 52 | + # Logits shape is (batch, sequence, vocab_size). We want the logits for the *next* token. |
| 53 | + # In the first step, the input sequence has 3 tokens, so we take the logits from the last position. |
| 54 | + last_token_logits = logits[0, -1, :] |
| 55 | + |
| 56 | + # Find the top K tokens and their corresponding logit values |
| 57 | + top_k_indices = np.argsort(last_token_logits)[-TOP_K_LOGITS:] |
| 58 | + top_k_values = last_token_logits[top_k_indices] |
| 59 | + |
| 60 | + # Decode the token IDs to human-readable strings |
| 61 | + top_k_tokens = [tokenizer.decode([idx]) for idx in top_k_indices] |
| 62 | + |
| 63 | + # Find the token that was actually chosen (the one with the highest logit) |
| 64 | + chosen_token_index = np.argmax(top_k_values) |
| 65 | + |
| 66 | + fig, ax = plt.subplots(figsize=(10, 8)) |
| 67 | + bars = ax.barh(np.arange(TOP_K_LOGITS), top_k_values, color='skyblue') |
| 68 | + |
| 69 | + # Highlight the chosen token in a different color |
| 70 | + bars[chosen_token_index].set_color('salmon') |
| 71 | + |
| 72 | + ax.set_yticks(np.arange(TOP_K_LOGITS)) |
| 73 | + ax.set_yticklabels(top_k_tokens) |
| 74 | + ax.invert_yaxis() # Display the highest value at the top |
| 75 | + ax.set_xlabel("Logit Value") |
| 76 | + ax.set_title(f"Top {TOP_K_LOGITS} Predicted Tokens (First Decoder Step)") |
| 77 | + |
| 78 | + # Add the logit values as text on the bars |
| 79 | + for bar in bars: |
| 80 | + width = bar.get_width() |
| 81 | + label_x_pos = width if width > 0 else 1 # Position label correctly for negative logits |
| 82 | + ax.text(label_x_pos, bar.get_y() + bar.get_height()/2, f' {width:.2f}', |
| 83 | + va='center', ha='left') |
| 84 | + |
| 85 | + plt.tight_layout() |
| 86 | + plt.savefig(output_path) |
| 87 | + print(f"Saved logits plot to {output_path}") |
| 88 | + return fig |
| 89 | + |
| 90 | + |
| 91 | +def main(): |
| 92 | + """Loads data and generates all visualizations.""" |
| 93 | + # Ensure the input directory exists |
| 94 | + if not INPUT_DIR.is_dir(): |
| 95 | + print(f"Error: Directory '{INPUT_DIR}' not found. Please run the data generation script first.") |
| 96 | + return |
| 97 | + |
| 98 | + # --- Load Data --- |
| 99 | + try: |
| 100 | + input_features = np.load(INPUT_DIR / f"{path.basename(MODEL_ID)}_input_features.npy") |
| 101 | + encoder_output = np.load(INPUT_DIR / f"{path.basename(MODEL_ID)}_encoder_output.npy") |
| 102 | + step_0_logits = np.load(INPUT_DIR / f"{path.basename(MODEL_ID)}_step_0_logits.npy") |
| 103 | + except FileNotFoundError as e: |
| 104 | + print(f"Error: Missing data file - {e}. Please ensure all .npy files exist in '{INPUT_DIR}'.") |
| 105 | + return |
| 106 | + |
| 107 | + print("Successfully loaded all .npy files.") |
| 108 | + |
| 109 | + # --- Load Tokenizer --- |
| 110 | + # The tokenizer is needed to decode the logit indices into text |
| 111 | + print(f"Loading tokenizer for {MODEL_ID}...") |
| 112 | + processor = WhisperProcessor.from_pretrained(MODEL_ID) |
| 113 | + tokenizer = processor.tokenizer |
| 114 | + print("Tokenizer loaded.") |
| 115 | + |
| 116 | + # --- Generate Plots --- |
| 117 | + # Create a directory to save the plots |
| 118 | + plots_dir = Path("plots") |
| 119 | + plots_dir.mkdir(exist_ok=True) |
| 120 | + |
| 121 | + plot_mel_spectrogram(input_features, plots_dir / "mel_spectrogram.png") |
| 122 | + plot_encoder_output(encoder_output, plots_dir / "encoder_output.png") |
| 123 | + plot_logits(step_0_logits, tokenizer, plots_dir / "step_0_logits.png") |
| 124 | + |
| 125 | + # --- Show Plots --- |
| 126 | + # This will open interactive windows for each plot. |
| 127 | + print("\nDisplaying plots. Close the plot windows to exit the script.") |
| 128 | + plt.show() |
| 129 | + |
| 130 | + |
| 131 | +if __name__ == "__main__": |
| 132 | + # You will need matplotlib: pip install matplotlib |
| 133 | + main() |
0 commit comments