File size: 18,437 Bytes
29fc577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#!/usr/bin/env python3
"""
data/generate_repetition_preference.py β€” Self-play preference data targeting repetition.

Generates (prompt, chosen, rejected) pairs by:
  - rejected: greedy decoding (temp=0, rep_penalty=1.0) β†’ tends to repeat
  - chosen:   sampling with repetition penalty (temp=0.7, rep_penalty=1.2) β†’ cleaner

Only keeps pairs where rejected has strictly higher 3-gram repetition rate than chosen.

Usage:
    python3 data/generate_repetition_preference.py \
        --checkpoint checkpoints/3b_dpo/checkpoint-slerp

    python3 data/generate_repetition_preference.py \
        --checkpoint checkpoints/3b_dpo/checkpoint-slerp \
        --output data/preference/repetition_preference.jsonl \
        --num_prompts 100 \
        --max_tokens 256
"""

from __future__ import annotations

import argparse
import json
import math
import os
import sys
import time
from pathlib import Path
from typing import List, Optional

import torch
import torch.nn.functional as F

_PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(_PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(_PROJECT_ROOT))

from model import LLM  # noqa: E402
from tokenizers import Tokenizer  # noqa: E402

# ---------------------------------------------------------------------------
# Korean prompt bank β€” 100+ diverse prompts
# ---------------------------------------------------------------------------

# 15 existing eval prompts (completion style β†’ wrapped in chat template)
_EVAL_PROMPTS = [
    "λŒ€ν•œλ―Όκ΅­μ˜ μˆ˜λ„λŠ” 어디인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "인곡지λŠ₯μ΄λž€ 무엇인지 μžμ„Ένžˆ μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "ν•œκ΅­μ˜ 전톡 μŒμ‹ μ€‘μ—μ„œ λŒ€ν‘œμ μΈ 것듀을 μ†Œκ°œν•΄μ£Όμ„Έμš”.",
    "지ꡬ μ˜¨λ‚œν™”μ˜ μ£Όμš” 원인은 λ¬΄μ—‡μΈκ°€μš”?",
    "ν”„λ‘œκ·Έλž˜λ°μ„ 배우렀면 μ–΄λ–»κ²Œ μ‹œμž‘ν•΄μ•Ό ν•˜λ‚˜μš”?",
    "μ‘°μ„ μ‹œλŒ€μ—λŠ” μ–΄λ–€ 일듀이 μžˆμ—ˆλ‚˜μš”?",
    "λ¬Όλ¦¬ν•™μ—μ„œ μ—λ„ˆμ§€λž€ 무엇인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "ν•œκ΅­μ–΄λŠ” μ„Έκ³„μ—μ„œ μ–΄λ–€ νŠΉμ§•μ„ κ°€μ§€κ³  μžˆλ‚˜μš”?",
    "경제 μ„±μž₯을 μœ„ν•΄μ„œλŠ” 무엇이 ν•„μš”ν•œκ°€μš”?",
    "우주 νƒμ‚¬μ˜ 역사λ₯Ό κ°„λ‹¨νžˆ μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "λ¨Έμ‹ λŸ¬λ‹κ³Ό λ”₯λŸ¬λ‹μ˜ μ°¨μ΄λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "ν•œκ΅­ λ¬Έν•™μ˜ λŒ€ν‘œμ μΈ μž‘ν’ˆμœΌλ‘œλŠ” μ–΄λ–€ 것듀이 μžˆλ‚˜μš”?",
    "μ–‘μž μ»΄ν“¨ν„°λž€ 무엇인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "κ±΄κ°•ν•œ μ‹μŠ΅κ΄€μ„ μœ„ν•΄μ„œλŠ” μ–΄λ–»κ²Œ ν•΄μ•Ό ν•˜λ‚˜μš”?",
    "세계 2μ°¨ λŒ€μ „ 이후 μ„Έκ³„λŠ” μ–΄λ–»κ²Œ λ³€ν–ˆλ‚˜μš”?",
]

# Additional diverse prompts (~85 more)
_EXTRA_PROMPTS = [
    # 일상 λŒ€ν™”
    "였늘 날씨가 쒋은데 뭐 ν•˜λ©΄ μ’‹μ„κΉŒμš”?",
    "주말에 뭐 ν•˜λ©΄ 쒋을지 μΆ”μ²œν•΄μ£Όμ„Έμš”.",
    "쒋은 ν•˜λ£¨λ₯Ό μ‹œμž‘ν•˜λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "μ§‘μ—μ„œ ν•  수 μžˆλŠ” μ·¨λ―Έ ν™œλ™μ„ μΆ”μ²œν•΄μ£Όμ„Έμš”.",
    "μΉœκ΅¬μ™€ 싸웠을 λ•Œ μ–΄λ–»κ²Œ ν™”ν•΄ν•˜λ©΄ μ’‹μ„κΉŒμš”?",
    "μ™Έλ‘œμ›€μ„ λŠλ‚„ λ•Œ μ–΄λ–»κ²Œ 극볡할 수 μžˆλ‚˜μš”?",
    "μ‹œκ°„ 관리λ₯Ό 잘 ν•˜λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "μ•„μΉ¨ 일찍 μΌμ–΄λ‚˜λŠ” μŠ΅κ΄€μ„ λ§Œλ“€λ €λ©΄ μ–΄λ–»κ²Œ ν•΄μ•Ό ν•˜λ‚˜μš”?",
    "μƒˆλ‘œμš΄ λ„μ‹œλ‘œ μ΄μ‚¬ν–ˆμ„ λ•Œ μ μ‘ν•˜λŠ” 방법은?",
    "μΉ΄νŽ˜μ—μ„œ 혼자 μ‹œκ°„ λ³΄λ‚΄λŠ” κ²ƒμ˜ μž₯점은 λ¬΄μ—‡μΈκ°€μš”?",

    # 지식 β€” κ³Όν•™
    "DNAκ°€ 무엇인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "λΈ”λž™ν™€μ΄λž€ λ¬΄μ—‡μΈκ°€μš”?",
    "μ§„ν™”λ‘ μ΄λž€ 무엇인지 κ°„λ‹¨νžˆ μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "κΈ°ν›„ λ³€ν™”κ°€ μƒνƒœκ³„μ— λ―ΈμΉ˜λŠ” 영ν–₯은 λ¬΄μ—‡μΈκ°€μš”?",
    "인체의 λ©΄μ—­ μ‹œμŠ€ν…œμ€ μ–΄λ–»κ²Œ μž‘λ™ν•˜λ‚˜μš”?",
    "λΉ›μ˜ μ†λ„λŠ” μ™œ μ€‘μš”ν•œκ°€μš”?",
    "μ›μžμ™€ λΆ„μžμ˜ 차이점은 λ¬΄μ—‡μΈκ°€μš”?",
    "κ΄‘ν•©μ„±μ΄λž€ 무엇인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "쀑λ ₯νŒŒλž€ λ¬΄μ—‡μΈκ°€μš”?",
    "쀄기세포 μΉ˜λ£Œλž€ 무엇이며 μ–΄λ–»κ²Œ ν™œμš©λ˜λ‚˜μš”?",

    # 지식 β€” μ—­μ‚¬Β·μ‚¬νšŒ
    "ν•œκ΅­μ˜ μ—­μ‚¬μ—μ„œ κ°€μž₯ μ€‘μš”ν•œ 사건은 λ¬΄μ—‡μΈκ°€μš”?",
    "λ―Όμ£Όμ£Όμ˜λž€ 무엇인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "μ‚°μ—…ν˜λͺ…이 세계에 미친 영ν–₯은 λ¬΄μ—‡μΈκ°€μš”?",
    "λƒ‰μ „μ΄λž€ λ¬΄μ—‡μ΄μ—ˆλ‚˜μš”?",
    "ν•œκ΅­ μ „μŸμ˜ 원인과 κ²°κ³Όλ₯Ό μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "μ„Έκ³„ν™”λž€ 무엇이며 μ–΄λ–€ 영ν–₯을 λ―ΈμΉ˜λ‚˜μš”?",
    "μΈκΆŒμ΄λž€ 무엇이며 μ™œ μ€‘μš”ν•œκ°€μš”?",
    "μ‹€ν¬λ‘œλ“œκ°€ μ—­μ‚¬μ μœΌλ‘œ μ€‘μš”ν•œ μ΄μœ λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "λ₯΄λ„€μƒμŠ€ μ‹œλŒ€λŠ” μ–΄λ–€ μ‹œκΈ°μ˜€λ‚˜μš”?",
    "ν•œκ΅­μ˜ λ…λ¦½μš΄λ™μ— λŒ€ν•΄ μ„€λͺ…ν•΄μ£Όμ„Έμš”.",

    # μ‘°μ–Έ β€” μ§μ—…Β·ν•™μŠ΅
    "μ·¨μ—… λ©΄μ ‘ 잘 λ³΄λŠ” 방법은 λ¬΄μ—‡μΈκ°€μš”?",
    "이λ ₯μ„œλ₯Ό 잘 μ“°λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "λŒ€ν•™ μƒν™œμ„ μ•Œμ°¨κ²Œ λ³΄λ‚΄λŠ” 방법은?",
    "곡뢀 집쀑λ ₯을 λ†’μ΄λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "μ™Έκ΅­μ–΄λ₯Ό λΉ λ₯΄κ²Œ λ°°μš°λŠ” 방법은 λ¬΄μ—‡μΈκ°€μš”?",
    "직μž₯μ—μ„œ 상사와 잘 μ§€λ‚΄λŠ” 방법은?",
    "ν”„λ¦¬λžœμ„œλ‘œ μΌν•˜λ©΄ μ–΄λ–€ μž₯단점이 μžˆλ‚˜μš”?",
    "μžκΈ°μ†Œκ°œμ„œλ₯Ό 잘 μ“°λŠ” νŒμ„ μ•Œλ €μ£Όμ„Έμš”.",
    "λ…μ„œ μŠ΅κ΄€μ„ κΈ°λ₯΄λŠ” 방법은 λ¬΄μ—‡μΈκ°€μš”?",
    "μˆ˜ν•™μ„ μž˜ν•˜κΈ° μœ„ν•œ 곡뢀 방법은?",

    # μ‘°μ–Έ β€” 건강·심리
    "슀트레슀 ν•΄μ†Œ 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "μš°μšΈκ°μ„ κ·Ήλ³΅ν•˜λŠ” 방법은 λ¬΄μ—‡μΈκ°€μš”?",
    "κ·œμΉ™μ μΈ μš΄λ™ μŠ΅κ΄€μ„ λ§Œλ“œλŠ” 방법은?",
    "수면의 μ§ˆμ„ λ†’μ΄λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "λ²ˆμ•„μ›ƒμ„ μ˜ˆλ°©ν•˜λŠ” 방법은 λ¬΄μ—‡μΈκ°€μš”?",
    "마음의 평화λ₯Ό μ°ΎλŠ” 방법은?",
    "μžμ‘΄κ°μ„ λ†’μ΄λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "λͺ…상을 μ‹œμž‘ν•˜λ €λ©΄ μ–΄λ–»κ²Œ ν•΄μ•Ό ν•˜λ‚˜μš”?",
    "κ±΄κ°•ν•œ 체쀑을 μœ μ§€ν•˜λŠ” 방법은?",
    "λ””μ§€ν„Έ 쀑독을 κ·Ήλ³΅ν•˜λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",

    # μ°½μž‘
    "짧은 동화λ₯Ό ν•˜λ‚˜ λ§Œλ“€μ–΄μ£Όμ„Έμš”.",
    "봄에 λŒ€ν•œ μ‹œλ₯Ό μ¨μ£Όμ„Έμš”.",
    "미래 λ„μ‹œλ₯Ό 배경으둜 ν•œ 짧은 이야기λ₯Ό μ¨μ£Όμ„Έμš”.",
    "바닀에 κ΄€ν•œ 짧은 μˆ˜ν•„μ„ μ¨μ£Όμ„Έμš”.",
    "고양이λ₯Ό 주인곡으둜 ν•œ 짧은 이야기λ₯Ό λ§Œλ“€μ–΄μ£Όμ„Έμš”.",
    "가을 풍경을 λ¬˜μ‚¬ν•˜λŠ” 글을 μ¨μ£Όμ„Έμš”.",
    "μš°μ •μ— κ΄€ν•œ 짧은 μ‹œλ₯Ό μ¨μ£Όμ„Έμš”.",
    "μ—„λ§ˆμ—κ²Œ λ³΄λ‚΄λŠ” νŽΈμ§€λ₯Ό μ¨μ£Όμ„Έμš”.",
    "미래의 λ‚˜μ—κ²Œ μ“°λŠ” νŽΈμ§€λ₯Ό μž‘μ„±ν•΄μ£Όμ„Έμš”.",
    "μ–΄λ¦° μ‹œμ ˆ 좔얡에 κ΄€ν•œ 짧은 글을 μ¨μ£Όμ„Έμš”.",

    # 기술·IT
    "ν΄λΌμš°λ“œ μ»΄ν“¨νŒ…μ΄λž€ λ¬΄μ—‡μΈκ°€μš”?",
    "블둝체인이 무엇인지 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "사이버 λ³΄μ•ˆμ΄ μ™œ μ€‘μš”ν•œκ°€μš”?",
    "λΉ…λ°μ΄ν„°λž€ 무엇이며 μ–΄λ–»κ²Œ ν™œμš©λ˜λ‚˜μš”?",
    "5G 기술이 κ°€μ Έμ˜¬ λ³€ν™”λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "인터넷 검색 엔진은 μ–΄λ–»κ²Œ μž‘λ™ν•˜λ‚˜μš”?",
    "슀마트폰이 μƒν™œμ— 미친 영ν–₯은 λ¬΄μ—‡μΈκ°€μš”?",
    "κ°€μƒν˜„μ‹€κ³Ό μ¦κ°•ν˜„μ‹€μ˜ μ°¨μ΄λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "μžμœ¨μ£Όν–‰ μžλ™μ°¨ κΈ°μˆ μ€ μ–΄λ””κΉŒμ§€ μ™”λ‚˜μš”?",
    "μ˜€ν”ˆμ†ŒμŠ€ μ†Œν”„νŠΈμ›¨μ–΄λž€ λ¬΄μ—‡μΈκ°€μš”?",

    # λ¬Έν™”Β·μ˜ˆμˆ 
    "K-팝이 μ„Έκ³„μ μœΌλ‘œ 인기λ₯Ό 얻은 μ΄μœ λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "ν•œκ΅­ μ˜ν™”κ°€ 세계 μ‹œμž₯μ—μ„œ μ£Όλͺ©λ°›λŠ” μ΄μœ λŠ”?",
    "전톡 예술과 ν˜„λŒ€ 예술의 μ°¨μ΄λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "μŒμ•…μ΄ 감정에 λ―ΈμΉ˜λŠ” 영ν–₯은 λ¬΄μ—‡μΈκ°€μš”?",
    "λ…μ„œκ°€ 삢에 λ―ΈμΉ˜λŠ” 긍정적인 영ν–₯은?",
    "미술 감상을 잘 ν•˜λŠ” 방법을 μ•Œλ €μ£Όμ„Έμš”.",
    "ν•œκ΅­ 전톡 μŒμ•…μΈ κ΅­μ•…μ˜ νŠΉμ§•μ€ λ¬΄μ—‡μΈκ°€μš”?",
    "μ˜ν™” 비평을 잘 μ“°λŠ” 방법은?",
    "여행이 μ‚¬λžŒμ„ μ„±μž₯μ‹œν‚€λŠ” μ΄μœ λŠ” λ¬΄μ—‡μΈκ°€μš”?",
    "사진 찍기λ₯Ό 잘 ν•˜λŠ” νŒμ„ μ•Œλ €μ£Όμ„Έμš”.",

    # ν™˜κ²½Β·μ‚¬νšŒ
    "ν™˜κ²½ 보호λ₯Ό μœ„ν•΄ 개인이 ν•  수 μžˆλŠ” 일은?",
    "μž¬ν™œμš©μ˜ μ€‘μš”μ„±κ³Ό 방법을 μ„€λͺ…ν•΄μ£Όμ„Έμš”.",
    "μ±„μ‹μ£Όμ˜μ˜ μž₯단점은 λ¬΄μ—‡μΈκ°€μš”?",
    "동물 λ³΅μ§€λž€ 무엇이며 μ™œ μ€‘μš”ν•œκ°€μš”?",
    "지속 κ°€λŠ₯ν•œ λ°œμ „μ΄λž€ λ¬΄μ—‡μΈκ°€μš”?",
    "λ…Έλ Ήν™” μ‚¬νšŒκ°€ κ°€μ Έμ˜€λŠ” λ¬Έμ œμ μ€ λ¬΄μ—‡μΈκ°€μš”?",
    "ꡐ윑 λΆˆν‰λ“±μ„ ν•΄μ†Œν•˜λŠ” 방법은?",
    "빈곀 문제λ₯Ό ν•΄κ²°ν•˜κΈ° μœ„ν•œ 방법은?",
    "λ‹€λ¬Έν™” μ‚¬νšŒμ—μ„œ κ³΅μ‘΄ν•˜λŠ” 방법은?",
    "봉사 ν™œλ™μ΄ μ‚¬νšŒμ— λ―ΈμΉ˜λŠ” 영ν–₯은 λ¬΄μ—‡μΈκ°€μš”?",
]

ALL_PROMPTS = _EVAL_PROMPTS + _EXTRA_PROMPTS  # 15 + 85 = 100

CHAT_TEMPLATE = "<|user|>\n{prompt}\n<|assistant|>\n"

EOS_TOKEN_ID = 2


# ---------------------------------------------------------------------------
# Repetition metric
# ---------------------------------------------------------------------------

def compute_ngram_repetition_rate(tokens: List[int], n: int = 3) -> float:
    """Fraction of n-gram positions that are repeats of an earlier occurrence."""
    if len(tokens) < n:
        return 0.0
    ngrams = [tuple(tokens[i: i + n]) for i in range(len(tokens) - n + 1)]
    if not ngrams:
        return 0.0
    seen: set = set()
    repeated = 0
    for ng in ngrams:
        if ng in seen:
            repeated += 1
        seen.add(ng)
    return repeated / len(ngrams)


# ---------------------------------------------------------------------------
# Generation
# ---------------------------------------------------------------------------

@torch.inference_mode()
def generate(
    model: torch.nn.Module,
    input_ids: torch.Tensor,
    max_new_tokens: int,
    temperature: float,
    repetition_penalty: float,
    eos_token_id: int,
) -> List[int]:
    """Auto-regressive generation with optional repetition penalty.

    Args:
        model: LLM instance already on device
        input_ids: (1, T) prompt token ids
        max_new_tokens: max tokens to generate
        temperature: sampling temperature (0 = greedy)
        repetition_penalty: penalty > 1 reduces prob of previously seen tokens
        eos_token_id: stop generation when this token is produced

    Returns:
        List of generated token ids (not including the prompt).
    """
    device = input_ids.device
    generated: List[int] = []
    current_ids = input_ids.clone()  # (1, T)

    for _ in range(max_new_tokens):
        with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
            logits, _ = model(current_ids)  # (1, T, V)

        next_logits = logits[0, -1, :].float()  # (V,)

        # Repetition penalty: discount logits for already-generated tokens
        if repetition_penalty != 1.0:
            all_seen_ids = current_ids[0].tolist() + generated
            for token_id in set(all_seen_ids):
                if token_id < next_logits.shape[0]:
                    if next_logits[token_id] < 0:
                        next_logits[token_id] *= repetition_penalty
                    else:
                        next_logits[token_id] /= repetition_penalty

        # Sample / greedy
        if temperature == 0.0:
            next_token = int(next_logits.argmax())
        else:
            next_logits = next_logits / temperature
            probs = F.softmax(next_logits, dim=-1)
            next_token = int(torch.multinomial(probs, num_samples=1).item())

        generated.append(next_token)

        if next_token == eos_token_id:
            break

        # Append to context
        next_tensor = torch.tensor([[next_token]], dtype=torch.long, device=device)
        current_ids = torch.cat([current_ids, next_tensor], dim=1)

    return generated


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Generate self-play repetition preference data"
    )
    parser.add_argument(
        "--checkpoint",
        type=Path,
        default=Path("checkpoints/3b_dpo/checkpoint-slerp"),
        help="Path to model checkpoint directory",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=Path("data/preference/repetition_preference.jsonl"),
        help="Output JSONL path",
    )
    parser.add_argument(
        "--num_prompts",
        type=int,
        default=None,
        help="How many prompts to use (default: all ~100)",
    )
    parser.add_argument(
        "--max_tokens",
        type=int,
        default=256,
        help="Max new tokens per generation",
    )
    parser.add_argument(
        "--tokenizer",
        type=Path,
        default=None,
        help="Path to tokenizer.json (default: auto-resolve)",
    )
    parser.add_argument(
        "--device",
        type=str,
        default="cuda:0",
        help="Torch device string",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="Random seed for reproducibility",
    )
    parser.add_argument(
        "--min_rep_diff",
        type=float,
        default=0.0,
        help="Minimum difference (rejected_rep - chosen_rep) to keep a pair (default: >0)",
    )
    return parser.parse_args()


def _resolve_tokenizer(args: argparse.Namespace) -> Path:
    if args.tokenizer is not None:
        return Path(args.tokenizer)
    # Try checkpoint dir first
    ckpt_tok = args.checkpoint / "tokenizer.json"
    if ckpt_tok.exists():
        return ckpt_tok
    # Fall back to project default
    default_tok = _PROJECT_ROOT / "tokenizer" / "korean_sp" / "tokenizer.json"
    if default_tok.exists():
        return default_tok
    raise FileNotFoundError(
        "Cannot find tokenizer.json β€” specify with --tokenizer"
    )


def main() -> None:
    args = parse_args()

    # Reproducibility
    torch.manual_seed(args.seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(args.seed)

    # Prompts
    prompts = ALL_PROMPTS
    if args.num_prompts is not None:
        prompts = prompts[: args.num_prompts]
    print(f"[INFO] Using {len(prompts)} prompts")

    # Device
    device = torch.device(args.device if torch.cuda.is_available() else "cpu")
    print(f"[INFO] Device: {device}")

    # Tokenizer
    tokenizer_path = _resolve_tokenizer(args)
    print(f"[INFO] Loading tokenizer from {tokenizer_path}")
    tokenizer = Tokenizer.from_file(str(tokenizer_path))

    # Model
    checkpoint_path = _PROJECT_ROOT / args.checkpoint if not args.checkpoint.is_absolute() else args.checkpoint
    if not checkpoint_path.exists():
        raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")
    print(f"[INFO] Loading model from {checkpoint_path} ...")
    t0 = time.perf_counter()
    model = LLM.from_pretrained(checkpoint_path)
    model = model.to(device=device, dtype=torch.bfloat16)
    model.eval()
    print(f"[INFO] Model loaded in {time.perf_counter() - t0:.1f}s")

    # Output dir
    output_path = _PROJECT_ROOT / args.output if not args.output.is_absolute() else args.output
    output_path.parent.mkdir(parents=True, exist_ok=True)

    # Stats
    valid_pairs = 0
    skipped = 0
    total_rejected_rep = 0.0
    total_chosen_rep = 0.0

    t_start = time.perf_counter()

    with open(output_path, "w", encoding="utf-8") as fout:
        for idx, prompt_text in enumerate(prompts):
            prompt_str = CHAT_TEMPLATE.format(prompt=prompt_text)

            # Tokenize prompt
            encoding = tokenizer.encode(prompt_str)
            prompt_ids = encoding.ids
            if not prompt_ids:
                print(f"  [{idx+1}/{len(prompts)}] SKIP: empty tokenization for prompt")
                skipped += 1
                continue

            input_ids = torch.tensor([prompt_ids], dtype=torch.long, device=device)

            # --- Generate REJECTED: greedy, no rep penalty ---
            rej_tokens = generate(
                model=model,
                input_ids=input_ids,
                max_new_tokens=args.max_tokens,
                temperature=0.0,
                repetition_penalty=1.0,
                eos_token_id=EOS_TOKEN_ID,
            )

            # --- Generate CHOSEN: sampling + rep penalty ---
            cho_tokens = generate(
                model=model,
                input_ids=input_ids,
                max_new_tokens=args.max_tokens,
                temperature=0.7,
                repetition_penalty=1.2,
                eos_token_id=EOS_TOKEN_ID,
            )

            # Decode (strip EOS)
            rej_clean = [t for t in rej_tokens if t != EOS_TOKEN_ID]
            cho_clean = [t for t in cho_tokens if t != EOS_TOKEN_ID]

            rej_text = tokenizer.decode(rej_clean)
            cho_text = tokenizer.decode(cho_clean)

            # Compute 3-gram repetition rates on generated tokens
            rej_rep = compute_ngram_repetition_rate(rej_clean, n=3)
            cho_rep = compute_ngram_repetition_rate(cho_clean, n=3)

            # Filter: only keep if rejected is more repetitive than chosen
            diff = rej_rep - cho_rep
            if diff <= args.min_rep_diff:
                status = "SKIP"
                skipped += 1
            else:
                status = "KEEP"
                valid_pairs += 1
                total_rejected_rep += rej_rep
                total_chosen_rep += cho_rep
                record = {
                    "prompt": prompt_str,
                    "chosen": cho_text,
                    "rejected": rej_text,
                }
                fout.write(json.dumps(record, ensure_ascii=False) + "\n")

            elapsed = time.perf_counter() - t_start
            print(
                f"  [{idx+1:3d}/{len(prompts)}] {status:4s} "
                f"rej_rep={rej_rep:.3f} cho_rep={cho_rep:.3f} diff={diff:+.3f} "
                f"| rej_len={len(rej_clean)} cho_len={len(cho_clean)} "
                f"| elapsed={elapsed:.1f}s"
            )

    # Summary
    elapsed_total = time.perf_counter() - t_start
    print()
    print("=" * 60)
    print(f"Generation complete in {elapsed_total:.1f}s")
    print(f"  Total prompts processed : {len(prompts)}")
    print(f"  Valid pairs kept        : {valid_pairs}")
    print(f"  Skipped (rep filter)    : {skipped}")
    if valid_pairs > 0:
        avg_rej = total_rejected_rep / valid_pairs
        avg_cho = total_chosen_rep / valid_pairs
        print(f"  Avg rejected 3-gram rep : {avg_rej:.4f}")
        print(f"  Avg chosen  3-gram rep  : {avg_cho:.4f}")
        print(f"  Avg improvement         : {avg_rej - avg_cho:+.4f}")
    print(f"  Output saved to         : {output_path}")
    print("=" * 60)


if __name__ == "__main__":
    main()