File size: 13,243 Bytes
d16e9ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
"""
Plot histogram of ranks computed with >= comparison or from logit ranks.
"""

import pickle
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
import argparse
from tqdm import tqdm
from datetime import datetime


def compute_ranks_gte(data, sigma):
    """Compute ranks using >= comparison from Gumbel scores."""
    ranks = np.zeros(len(data), dtype=np.int32)

    for i, item in enumerate(tqdm(data, desc=f"Computing ranks (>=, sigma={sigma})")):
        sampled_score = item['sampled_gumbel_scores'][sigma]
        top_k_scores = item['top_k_gumbel_scores'][sigma]

        # Rank = number of tokens with score >= sampled_score
        num_higher_or_equal = np.sum(top_k_scores >= sampled_score)
        ranks[i] = num_higher_or_equal

    return ranks


def extract_logit_ranks(data):
    """Extract logit ranks directly from data."""
    ranks = np.zeros(len(data), dtype=np.int32)

    for i, item in enumerate(tqdm(data, desc="Extracting logit ranks")):
        ranks[i] = item['logit_rank']

    return ranks


def extract_gumbel_scores(data, sigma):
    """Extract Gumbel scores for sampled tokens."""
    scores = np.zeros(len(data), dtype=np.float32)

    for i, item in enumerate(tqdm(data, desc=f"Extracting GLS scores (sigma={sigma})")):
        scores[i] = item['sampled_gumbel_scores'][sigma]

    return scores


def plot_scores_and_ranks_comparison(gls_scores, gls_ranks, logit_ranks, output_path, sigma):
    """Create 3-panel comparison: GLS scores, GLS ranks, and logit ranks."""

    fig, axes = plt.subplots(1, 3, figsize=(20, 6))

    total = len(gls_scores)

    # Left panel: GLS scores histogram
    ax = axes[0]
    bins = np.linspace(-20, 0, 101)  # 100 bins from -20 to 0
    counts, bin_edges = np.histogram(gls_scores, bins=bins)
    percentages = (counts / total) * 100

    # Plot as bars
    bin_centers = (bin_edges[:-1] + bin_edges[1:]) / 2
    bin_width = bin_edges[1] - bin_edges[0]

    # Filter out zero counts for log scale
    non_zero_mask = percentages > 0
    ax.bar(bin_centers[non_zero_mask], percentages[non_zero_mask],
           width=bin_width, edgecolor='black', alpha=0.7)

    ax.set_xlabel('GLS Score', fontsize=12)
    ax.set_ylabel('Percentage (%) - Log Scale', fontsize=12)
    ax.set_title('GLS Scores Distribution')
    ax.set_yscale('log')
    ax.grid(alpha=0.3, which='both')
    ax.set_xlim(-20, 0)

    # Middle panel: GLS ranks histogram (grouped: 0, 1, 2, ..., 19, 20+)
    ax = axes[1]

    # Group ranks: 0-19 individually, 20+ together
    grouped_ranks = []
    grouped_labels = []
    for i in range(20):
        count = np.sum(gls_ranks == i)
        grouped_ranks.append(count)
        grouped_labels.append(str(i))

    # Add 20+ group
    count_20_plus = np.sum(gls_ranks >= 20)
    grouped_ranks.append(count_20_plus)
    grouped_labels.append('20+')

    grouped_percentages = (np.array(grouped_ranks) / total) * 100

    # Filter out zero counts for log scale
    non_zero_mask = grouped_percentages > 0
    x_positions = np.arange(21)[non_zero_mask]

    ax.bar(x_positions, grouped_percentages[non_zero_mask], edgecolor='black', alpha=0.7, width=0.8)
    ax.set_xlabel('GLS Rank (0=highest)', fontsize=12)
    ax.set_ylabel('Percentage (%) - Log Scale', fontsize=12)
    ax.set_title('GLS Ranks Distribution')
    ax.set_yscale('log')
    ax.set_xticks(range(21))
    ax.set_xticklabels(grouped_labels, rotation=0, fontsize=10)
    ax.grid(alpha=0.3, which='both', axis='y')

    # Right panel: Logit ranks histogram
    ax = axes[2]
    unique_ranks, counts = np.unique(logit_ranks, return_counts=True)
    percentages = (counts / total) * 100

    ax.bar(unique_ranks, percentages, edgecolor='black', alpha=0.7, width=0.8)
    ax.set_xlabel('Logit Rank (0=highest)', fontsize=12)
    ax.set_ylabel('Percentage (%) - Log Scale', fontsize=12)
    ax.set_title('Logit Ranks Distribution')
    ax.set_yscale('log')
    ax.grid(alpha=0.3, which='both')

    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches='tight')
    print(f"\nSaved comparison plot to {output_path}")
    plt.close()

    # Print statistics
    print("\n" + "="*80)
    print(f"GLS Scores, GLS Ranks, and Logit Ranks Comparison (sigma={sigma})")
    print("="*80)
    print(f"Total items: {total:,}")

    print(f"\nGLS Scores statistics:")
    print(f"  Min: {gls_scores.min():.4f}")
    print(f"  Max: {gls_scores.max():.4f}")
    print(f"  Mean: {gls_scores.mean():.4f}")
    print(f"  Median: {np.median(gls_scores):.4f}")
    print(f"  Std: {gls_scores.std():.4f}")

    print(f"\nGLS Ranks statistics:")
    print(f"  Min: {gls_ranks.min()}")
    print(f"  Max: {gls_ranks.max()}")
    print(f"  Mean: {gls_ranks.mean():.2f}")
    print(f"  Median: {np.median(gls_ranks):.2f}")

    print(f"\nLogit Ranks statistics:")
    print(f"  Min: {logit_ranks.min()}")
    print(f"  Max: {logit_ranks.max()}")
    print(f"  Mean: {logit_ranks.mean():.2f}")
    print(f"  Median: {np.median(logit_ranks):.2f}")

    print(f"\nTop 10 most common GLS ranks:")
    unique_gls_ranks, gls_counts = np.unique(gls_ranks, return_counts=True)
    top_10_idx = np.argsort(gls_counts)[-10:][::-1]
    for idx in top_10_idx:
        rank = unique_gls_ranks[idx]
        count = gls_counts[idx]
        pct = 100 * count / total
        print(f"  Rank {rank:3d}: {count:6,} ({pct:6.2f}%)")

    print(f"\nTop 10 most common logit ranks:")
    unique_logit_ranks, logit_counts = np.unique(logit_ranks, return_counts=True)
    top_10_idx = np.argsort(logit_counts)[-10:][::-1]
    for idx in top_10_idx:
        rank = unique_logit_ranks[idx]
        count = logit_counts[idx]
        pct = 100 * count / total
        print(f"  Rank {rank:3d}: {count:6,} ({pct:6.2f}%)")


def plot_rank_histogram(ranks, output_path, title_suffix, max_rank_plot=30):
    """Create histogram of ranks."""

    fig, axes = plt.subplots(2, 2, figsize=(14, 10))
    fig.suptitle(f'Rank Distribution ({title_suffix})', fontsize=16, fontweight='bold')

    # Get rank distribution
    unique_ranks, counts = np.unique(ranks, return_counts=True)
    total = len(ranks)

    # Separate data for plotting (ranks 1-max_rank_plot) and ranks > max_rank_plot
    plot_mask = unique_ranks <= max_rank_plot
    plot_ranks = unique_ranks[plot_mask]
    plot_counts = counts[plot_mask]

    # Count ranks > max_rank_plot
    higher_ranks_mask = unique_ranks > max_rank_plot
    count_above_max = np.sum(counts[higher_ranks_mask])

    # Plot 1: Bar plot of rank distribution
    ax = axes[0, 0]
    ax.bar(plot_ranks, plot_counts, edgecolor='black', alpha=0.7, width=0.8)
    ax.set_xlabel('Rank', fontsize=12)
    ax.set_ylabel('Count', fontsize=12)
    ax.set_title(f'Rank Distribution (Linear Scale, ranks 1-{max_rank_plot})')
    ax.grid(alpha=0.3)

    # Add text annotation for ranks > max_rank_plot
    if count_above_max > 0:
        pct_above = 100 * count_above_max / total
        ax.text(0.98, 0.98, f'Rank > {max_rank_plot}: {count_above_max:,} ({pct_above:.2f}%)',
                transform=ax.transAxes, ha='right', va='top',
                bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5), fontsize=10)

    # Add percentages as text labels for top ranks
    for rank, count in zip(plot_ranks[:5], plot_counts[:5]):
        pct = 100 * count / total
        ax.text(rank, count, f'{pct:.2f}%', ha='center', va='bottom', fontsize=9)

    # Plot 2: Bar plot with log scale
    ax = axes[0, 1]
    ax.bar(plot_ranks, plot_counts, edgecolor='black', alpha=0.7, width=0.8)
    ax.set_xlabel('Rank', fontsize=12)
    ax.set_ylabel('Count (log scale)', fontsize=12)
    ax.set_yscale('log')
    ax.set_title(f'Rank Distribution (Log Scale, ranks 1-{max_rank_plot})')
    ax.grid(alpha=0.3)

    # Plot 3: Percentage distribution
    ax = axes[1, 0]
    plot_percentages = (plot_counts / total) * 100
    ax.bar(plot_ranks, plot_percentages, edgecolor='black', alpha=0.7, width=0.8)
    ax.set_xlabel('Rank', fontsize=12)
    ax.set_ylabel('Percentage (%)', fontsize=12)
    ax.set_title(f'Rank Distribution (Percentages, ranks 1-{max_rank_plot})')
    ax.grid(alpha=0.3)

    # Plot 4: Cumulative distribution (use all ranks for this)
    ax = axes[1, 1]
    percentages = (counts / total) * 100
    cumulative_pct = np.cumsum(percentages)

    # Only plot up to max_rank_plot
    plot_cumulative = cumulative_pct[plot_mask]
    ax.plot(plot_ranks, plot_cumulative, linewidth=2, marker='o', markersize=6)
    ax.set_xlabel('Rank', fontsize=12)
    ax.set_ylabel('Cumulative Percentage (%)', fontsize=12)
    ax.set_title(f'Cumulative Rank Distribution (ranks 1-{max_rank_plot})')
    ax.axhline(y=95, color='red', linestyle='--', alpha=0.5, label='95%')
    ax.axhline(y=99, color='orange', linestyle='--', alpha=0.5, label='99%')
    ax.legend()
    ax.grid(alpha=0.3)

    plt.tight_layout()
    plt.savefig(output_path, dpi=150, bbox_inches='tight')
    print(f"\nSaved histogram to {output_path}")
    plt.close()

    # Print statistics
    print("\n" + "="*80)
    print(f"Rank Statistics ({title_suffix})")
    print("="*80)
    print(f"Total items: {total:,}")
    print(f"\nRank distribution (ranks 1-{max_rank_plot}):")
    for rank, count in zip(plot_ranks, plot_counts):
        pct = 100 * count / total
        print(f"  Rank {rank:3d}: {count:6,} ({pct:6.2f}%)")

    # Print ranks > max_rank_plot
    if count_above_max > 0:
        print(f"\nRanks > {max_rank_plot}:")
        pct_above = 100 * count_above_max / total
        print(f"  Total count: {count_above_max:6,} ({pct_above:6.2f}%)")
        print(f"  Individual ranks:")
        for rank, count in zip(unique_ranks[higher_ranks_mask], counts[higher_ranks_mask]):
            pct = 100 * count / total
            print(f"    Rank {rank:3d}: {count:6,} ({pct:6.2f}%)")

    print(f"\nCumulative distribution:")
    cumsum = 0
    for rank, count in zip(unique_ranks, counts):
        cumsum += count
        pct = 100 * cumsum / total
        if rank <= max_rank_plot or rank == unique_ranks[-1]:  # Print up to max_rank and the last rank
            print(f"  Rank ≤ {rank:3d}: {cumsum:6,} ({pct:6.2f}%)")


def main():
    parser = argparse.ArgumentParser(
        description="Plot histogram of ranks computed with >= comparison or from logit ranks"
    )
    parser.add_argument(
        "--input",
        type=str,
        required=True,
        help="Path to all_prompts.pkl file"
    )
    parser.add_argument(
        "--plot-type",
        type=str,
        choices=["detailed", "comparison"],
        default="comparison",
        help="Type of plot: 'detailed' (4-panel rank histogram) or 'comparison' (2-panel GLS vs ranks) (default: comparison)"
    )
    parser.add_argument(
        "--rank-type",
        type=str,
        choices=["gumbel", "logit"],
        default="logit",
        help="Type of rank to plot for detailed view: 'gumbel' or 'logit' (default: logit, only used with --plot-type detailed)"
    )
    parser.add_argument(
        "--sigma",
        type=float,
        default=1.0,
        help="Sigma value to use for GLS scores (default: 1.0)"
    )
    parser.add_argument(
        "--output",
        type=str,
        default=None,
        help="Output path for histogram (default: auto-generated based on plot type)"
    )
    parser.add_argument(
        "--max-rank-plot",
        type=int,
        default=30,
        help="Maximum rank to plot in detailed view (default: 30)"
    )

    args = parser.parse_args()

    # Load data
    print(f"Loading data from {args.input}...")
    with open(args.input, 'rb') as f:
        data = pickle.load(f)
    print(f"Loaded {len(data):,} items")

    input_path = Path(args.input)
    output_dir = input_path.parent

    if args.plot_type == "comparison":
        # Extract GLS scores, GLS ranks, and logit ranks
        gls_scores = extract_gumbel_scores(data, args.sigma)
        gls_ranks = compute_ranks_gte(data, args.sigma)
        logit_ranks = extract_logit_ranks(data)

        # Generate output filename
        if args.output is None:
            datestr = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_path = output_dir / f"scores_vs_ranks_comparison_sigma{args.sigma}_{datestr}.pdf"
        else:
            output_path = Path(args.output)

        # Plot comparison
        plot_scores_and_ranks_comparison(gls_scores, gls_ranks, logit_ranks, output_path, args.sigma)

    else:  # detailed
        # Compute ranks based on type
        if args.rank_type == "gumbel":
            ranks = compute_ranks_gte(data, args.sigma)
            title_suffix = f"Gumbel scores, sigma={args.sigma}"
            default_filename = f"ranks_histogram_gumbel_sigma{args.sigma}.pdf"
        else:  # logit
            ranks = extract_logit_ranks(data)
            title_suffix = "Raw logit ranks (0=highest logit)"
            default_filename = "ranks_histogram_logit.pdf"

        # Generate output filename
        if args.output is None:
            output_path = output_dir / default_filename
        else:
            output_path = Path(args.output)

        # Plot histogram
        plot_rank_histogram(ranks, output_path, title_suffix, args.max_rank_plot)


if __name__ == "__main__":
    main()