""" Plot the threshold curve: average number of tokens above threshold vs. threshold. """ import pickle import numpy as np import matplotlib.pyplot as plt import argparse def main(): parser = argparse.ArgumentParser( description="Plot threshold curve from analysis results" ) parser.add_argument( "--input", type=str, default="threshold_analysis.pkl", help="Path to threshold analysis pickle file" ) parser.add_argument( "--output", type=str, default="threshold_curve.png", help="Path to save plot" ) args = parser.parse_args() # Load data print(f"Loading {args.input}...") with open(args.input, "rb") as f: stats = pickle.load(f) # Extract data avg_count_above = stats["avg_count_above"] # [max_tokens, n_thresholds] thresholds = stats["thresholds"] # [n_thresholds] print(f"Data shape: {avg_count_above.shape}") print(f"Token positions: {stats['max_tokens']}") print(f"Thresholds: {stats['n_thresholds']}") print(f"Prompts: {stats['n_prompts']}") print(f"Vocab size: {stats['vocab_size']}") # Average across all token positions avg_across_positions = np.nanmean(avg_count_above, axis=0) # [n_thresholds] # Convert to "below threshold" (vocab_size - count_above) vocab_size = stats['vocab_size'] avg_count_below = vocab_size - avg_across_positions # [n_thresholds] print(f"\nAveraged curve shape: {avg_count_below.shape}") print(f"Sample values:") print(f" threshold=0: {avg_count_below[0]:.1f} tokens below") print(f" threshold=50: {avg_count_below[len(thresholds)//2]:.1f} tokens below") print(f" threshold=100: {avg_count_below[-1]:.1f} tokens below") # Create plot plt.figure(figsize=(10, 6)) plt.semilogy(thresholds, avg_count_below, linewidth=2) plt.xlabel("Threshold", fontsize=12) plt.ylabel("Average # of tokens below threshold (log scale)", fontsize=12) plt.title(f"Gumbel Score Threshold Curve\n({stats['n_prompts']} prompts, vocab size={stats['vocab_size']})", fontsize=14) plt.grid(True, alpha=0.3, which='both') plt.tight_layout() # Save plt.savefig(args.output, dpi=150, bbox_inches='tight') print(f"\nSaved plot to {args.output}") # Also show some statistics print(f"\nStatistics:") print(f" Max count below: {avg_count_below.max():.1f}") print(f" Min count below: {avg_count_below.min():.1f}") if __name__ == "__main__": main()