Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
30 lines
980 B
Python
30 lines
980 B
Python
"""Offline helper (experiments only): decode captured prompt ids to text with the pinned vocab.json (byte-level BPE alphabet)."""
|
|
import json, os
|
|
|
|
def _byte_alphabet():
|
|
bs = list(range(0x21, 0x7f)) + list(range(0xa1, 0xad)) + list(range(0xae, 0x100))
|
|
cs = bs[:]
|
|
n = 0
|
|
for b in range(256):
|
|
if b not in bs:
|
|
bs.append(b); cs.append(256 + n); n += 1
|
|
return {chr(c): b for b, c in zip(bs, cs)}
|
|
|
|
class Vocab:
|
|
def __init__(self, directory):
|
|
vocab = json.load(open(os.path.join(directory, "vocab.json"), encoding="utf-8"))
|
|
self.tokens = [None] * len(vocab)
|
|
for t, i in vocab.items():
|
|
self.tokens[i] = t
|
|
self.rev = _byte_alphabet()
|
|
|
|
def decode_bytes(self, ids):
|
|
out = bytearray()
|
|
for i in ids:
|
|
for ch in self.tokens[i]:
|
|
out.append(self.rev[ch])
|
|
return bytes(out)
|
|
|
|
def decode(self, ids):
|
|
return self.decode_bytes(ids).decode("utf-8")
|