Download source/src/evm_bert/tokenizer.py from willynilly-fr/evm-positions-scratch-20ep: direct link, hf CLI and curl.
- Browser
- Download file 8.27 kB
-
https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/src/evm_bert/tokenizer.py
- Command line
-
hf download hf://willynilly-fr/evm-positions-scratch-20ep/source/src/evm_bert/tokenizer.py
-
curl -L -o tokenizer.py https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/src/evm_bert/tokenizer.py
8.27 kB
| """Lossless BPE over actual transaction bytes, with a reversible symbol alphabet. | |
| HF tokenizers consumes Unicode strings. Mapping byte b to U+E000+b makes every | |
| input character exactly one byte, including non-UTF-8 data. No text normalizer, | |
| UTF-8 conversion, or pre-tokenizer is applied. BPE merges adjacent byte symbols. | |
| Use encode_raw_hex/decode_raw_hex rather than passing hexadecimal text directly. | |
| """ | |
| import hashlib | |
| import json | |
| import re | |
| from pathlib import Path | |
| from datasets import load_from_disk | |
| from tokenizers import Tokenizer, decoders, models, processors, trainers | |
| from transformers import PreTrainedTokenizerFast | |
| from .model import config_value | |
| SPECIAL_TOKENS = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"] | |
| BYTE_SYMBOL_OFFSET = 0xE000 | |
| def normalize_raw_hex(raw_hex): | |
| if not isinstance(raw_hex, str): | |
| raise ValueError("raw_hex must be a hexadecimal string") | |
| value = raw_hex[2:] if raw_hex.startswith(("0x", "0X")) else raw_hex | |
| if not value or len(value) % 2 or re.fullmatch(r"[0-9a-fA-F]+", value) is None: | |
| raise ValueError("raw_hex must contain a nonempty, even number of hexadecimal digits") | |
| return "0x" + value.lower() | |
| def hex_to_symbols(raw_hex): | |
| return "".join( | |
| chr(BYTE_SYMBOL_OFFSET + byte) for byte in bytes.fromhex(normalize_raw_hex(raw_hex)[2:]) | |
| ) | |
| def symbols_to_hex(symbols): | |
| try: | |
| return "0x" + bytes(ord(char) - BYTE_SYMBOL_OFFSET for char in symbols).hex() | |
| except ValueError as error: | |
| raise ValueError("Decoded content is not in the transaction byte alphabet") from error | |
| def encode_raw_hex(tokenizer, raw_hex, add_special_tokens=True): | |
| # The caller windows the complete sequence; suppress the irrelevant model- | |
| # length warning for an intentionally untruncated transaction. | |
| return tokenizer.encode( | |
| hex_to_symbols(raw_hex), add_special_tokens=add_special_tokens, verbose=False | |
| ) | |
| def decode_raw_hex(tokenizer, token_ids, skip_special_tokens=True): | |
| tokens = tokenizer.convert_ids_to_tokens(list(token_ids)) | |
| if skip_special_tokens: | |
| tokens = [token for token in tokens if token not in tokenizer.all_special_tokens] | |
| return symbols_to_hex("".join(tokens)) | |
| def load_tokenizer(config_or_path): | |
| path = ( | |
| config_or_path | |
| if isinstance(config_or_path, (str, Path)) | |
| else config_value(config_or_path, "tokenizer.output_dir", "artifacts/tokenizer") | |
| ) | |
| tokenizer = PreTrainedTokenizerFast.from_pretrained(str(path), local_files_only=True) | |
| metadata_path = Path(path) / "byte_encoding.json" | |
| if not metadata_path.exists(): | |
| raise ValueError(f"Missing byte alphabet metadata: {metadata_path}") | |
| metadata = json.loads(metadata_path.read_text()) | |
| if metadata.get("byte_symbol_offset") != BYTE_SYMBOL_OFFSET: | |
| raise ValueError("Unsupported transaction byte alphabet") | |
| return tokenizer | |
| def corpus_digest(dataset): | |
| digest = hashlib.sha256() | |
| for raw_hex in dataset["raw_hex"]: | |
| # Length framing prevents ambiguous concatenations of transactions. | |
| raw = bytes.fromhex(normalize_raw_hex(raw_hex)[2:]) | |
| digest.update(len(raw).to_bytes(8, "big")) | |
| digest.update(raw) | |
| return digest.hexdigest() | |
| def train_tokenizer(config): | |
| dataset = load_from_disk( | |
| str(Path(config_value(config, "data.output_dir", "data/transactions")) / "dataset") | |
| ) | |
| if "train" not in dataset or not len(dataset["train"]): | |
| raise ValueError("A nonempty train split is required") | |
| requested_size = int(config_value(config, "tokenizer.vocab_size", 8192)) | |
| if requested_size < 256 + len(SPECIAL_TOKENS): | |
| raise ValueError("vocab_size must accommodate all 256 bytes and five special tokens") | |
| backend = Tokenizer(models.BPE(unk_token="[UNK]")) | |
| backend.decoder = decoders.Fuse() | |
| backend.train_from_iterator( | |
| (hex_to_symbols(value) for value in dataset["train"]["raw_hex"]), | |
| trainer=trainers.BpeTrainer( | |
| vocab_size=requested_size, | |
| min_frequency=int(config_value(config, "tokenizer.min_frequency", 2)), | |
| initial_alphabet=[chr(BYTE_SYMBOL_OFFSET + byte) for byte in range(256)], | |
| special_tokens=SPECIAL_TOKENS, | |
| show_progress=False, | |
| ), | |
| length=len(dataset["train"]), | |
| ) | |
| actual_size = backend.get_vocab_size() | |
| if actual_size != requested_size: | |
| raise ValueError( | |
| f"Corpus produced {actual_size:,} tokens, requested {requested_size:,}. " | |
| "Collect more training transactions or reduce tokenizer.min_frequency; " | |
| "unused padding tokens are not an 8k learned vocabulary." | |
| ) | |
| backend.post_processor = processors.TemplateProcessing( | |
| single="[CLS] $A [SEP]", | |
| special_tokens=[ | |
| ("[CLS]", backend.token_to_id("[CLS]")), | |
| ("[SEP]", backend.token_to_id("[SEP]")), | |
| ], | |
| ) | |
| tokenizer = PreTrainedTokenizerFast( | |
| tokenizer_object=backend, | |
| pad_token="[PAD]", | |
| unk_token="[UNK]", | |
| cls_token="[CLS]", | |
| sep_token="[SEP]", | |
| mask_token="[MASK]", | |
| model_max_length=int(config_value(config, "model.max_position_embeddings", 512)), | |
| clean_up_tokenization_spaces=False, | |
| ) | |
| output_dir = Path(config_value(config, "tokenizer.output_dir", "artifacts/tokenizer")) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| metadata = { | |
| "format": "evm-byte-symbol-bpe-v1", | |
| "byte_symbol_offset": BYTE_SYMBOL_OFFSET, | |
| "byte_alphabet_size": 256, | |
| "vocab_size": actual_size, | |
| "training_split": "train", | |
| "train_examples": len(dataset["train"]), | |
| "train_corpus_sha256": corpus_digest(dataset["train"]), | |
| "min_frequency": int(config_value(config, "tokenizer.min_frequency", 2)), | |
| "input_contract": "Map each raw byte b to chr(0xE000+b) before tokenization. No UTF-8 conversion.", | |
| } | |
| tokenizer.save_pretrained(str(output_dir)) | |
| (output_dir / "byte_encoding.json").write_text(json.dumps(metadata, indent=2) + "\n") | |
| reloaded = load_tokenizer(output_dir) | |
| checks = {} | |
| for split, records in dataset.items(): | |
| byte_count = token_count = 0 | |
| for raw_hex in records["raw_hex"]: | |
| token_ids = encode_raw_hex(reloaded, raw_hex, add_special_tokens=False) | |
| if reloaded.unk_token_id in token_ids or decode_raw_hex( | |
| reloaded, token_ids | |
| ) != normalize_raw_hex(raw_hex): | |
| raise AssertionError(f"Tokenizer roundtrip failed in {split}") | |
| byte_count += (len(normalize_raw_hex(raw_hex)) - 2) // 2 | |
| token_count += len(token_ids) | |
| checks[split] = { | |
| "examples": len(records), | |
| "bytes": byte_count, | |
| "tokens": token_count, | |
| "roundtrip_failures": 0, | |
| "unknown_tokens": 0, | |
| "bytes_per_token": byte_count / token_count if token_count else 0, | |
| } | |
| # Explicitly cover every possible unseen byte, independent of the corpus. | |
| alphabet_hex = "0x" + bytes(range(256)).hex() | |
| assert decode_raw_hex(reloaded, encode_raw_hex(reloaded, alphabet_hex)) == alphabet_hex | |
| report = {**metadata, "roundtrip": checks, "all_256_bytes_roundtrip": True} | |
| (output_dir / "report.json").write_text(json.dumps(report, indent=2) + "\n") | |
| (output_dir / "README.md").write_text( | |
| "---\nlibrary_name: tokenizers\ntags:\n- ethereum\n- byte-level-bpe\n---\n\n" | |
| "# Ethereum transaction byte BPE\n\n" | |
| f"A {actual_size:,}-token BPE vocabulary trained only on the training split. " | |
| "Each raw byte maps bijectively to Unicode U+E000 + its numeric value; " | |
| "BPE merges those symbols. All 256 byte symbols are included initially.\n\n" | |
| "**Input contract:** use `evm_bert.tokenizer.encode_raw_hex` and " | |
| "`decode_raw_hex`. Passing a hexadecimal string directly to this tokenizer " | |
| "does not perform the required byte mapping. There is no text normalization " | |
| "or UTF-8 expansion. The model vocabulary includes five BERT special tokens.\n\n" | |
| "See `byte_encoding.json` and `report.json` for corpus provenance and full " | |
| "roundtrip verification across every split.\n" | |
| ) | |
| return report | |