null
feat: deploy BotPsy local WebGPU static Space
1cc8d34
Raw History Blame Contribute Delete
1.51 kB
/**
* GPT-2/Qwen byte-level alphabet. Every UTF-8 byte is mapped to a printable
* code point so the BPE vocabulary can be represented as strings.
*/
const byteToChar = new Map<number, string>();
const charToByte = new Map<string, number>();
{
const direct: number[] = [];
for (let b = 0x21; b <= 0x7e; b++) direct.push(b);
for (let b = 0xa1; b <= 0xac; b++) direct.push(b);
for (let b = 0xae; b <= 0xff; b++) direct.push(b);
const used = new Set(direct);
let extra = 0;
for (let b = 0; b < 256; b++) {
if (used.has(b)) continue;
direct.push(b);
extra++;
}
for (let i = 0; i < direct.length; i++) {
const byte = direct[i]!;
const codePoint = i < used.size ? byte : 256 + (i - used.size);
const ch = String.fromCodePoint(codePoint);
byteToChar.set(byte, ch);
charToByte.set(ch, byte);
}
}
export function byteLevelEncode(bytes: Uint8Array): string {
let out = '';
for (const byte of bytes) out += byteToChar.get(byte)!;
return out;
}
export function byteLevelDecode(text: string): Uint8Array {
const bytes = new Uint8Array(text.length);
let length = 0;
for (const ch of text) {
const byte = charToByte.get(ch);
if (byte === undefined) throw new Error(`token is not valid byte-level text: ${JSON.stringify(ch)}`);
bytes[length++] = byte;
}
return bytes.subarray(0, length);
}
export const GPT2_BYTE_TO_CHAR: ReadonlyMap<number, string> = byteToChar;
export const GPT2_CHAR_TO_BYTE: ReadonlyMap<string, number> = charToByte;