Download code/multi-hop/check_single_tokenization.py from fhyfhy/Implicit-Reasoning-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 5.98 kB
-
https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/check_single_tokenization.py
- Command line
-
hf download hf://fhyfhy/Implicit-Reasoning-checkpoints/code/multi-hop/check_single_tokenization.py
-
curl -L -o check_single_tokenization.py https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/check_single_tokenization.py
5.98 kB
| #!/usr/bin/env python3 | |
| """ | |
| Check whether entities and relations are single tokens for a given tokenizer. | |
| Example: | |
| python check_single_tokenization.py --tokenizer gpt2 | |
| python check_single_tokenization.py --tokenizer gpt2 --num-entities 50 --num-relations 200 --seed 42 | |
| python check_single_tokenization.py --tokenizer path/to/checkpoint --output-json token_report.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| from pathlib import Path | |
| from typing import Dict, List | |
| from transformers import AutoTokenizer | |
| from generate_data import DataGenerator | |
| def encode_info(tokenizer, text: str) -> Dict: | |
| ids = tokenizer.encode(text, add_special_tokens=False) | |
| pieces = tokenizer.convert_ids_to_tokens(ids) | |
| return { | |
| "ids": ids, | |
| "pieces": pieces, | |
| "n_tokens": len(ids), | |
| "is_single": len(ids) == 1, | |
| } | |
| def build_rows(tokenizer, tokens: List[str], kind: str) -> List[Dict]: | |
| rows: List[Dict] = [] | |
| for token in tokens: | |
| bare = encode_info(tokenizer, token) | |
| with_space = encode_info(tokenizer, f" {token}") | |
| rows.append( | |
| { | |
| "kind": kind, | |
| "token": token, | |
| "bare_n_tokens": bare["n_tokens"], | |
| "bare_is_single": bare["is_single"], | |
| "bare_ids": bare["ids"], | |
| "bare_pieces": bare["pieces"], | |
| "leading_space_n_tokens": with_space["n_tokens"], | |
| "leading_space_is_single": with_space["is_single"], | |
| "leading_space_ids": with_space["ids"], | |
| "leading_space_pieces": with_space["pieces"], | |
| } | |
| ) | |
| return rows | |
| def summarize(rows: List[Dict], label: str) -> None: | |
| total = len(rows) | |
| single_bare = sum(1 for r in rows if r["bare_is_single"]) | |
| single_space = sum(1 for r in rows if r["leading_space_is_single"]) | |
| single_both = sum(1 for r in rows if r["bare_is_single"] and r["leading_space_is_single"]) | |
| print(f"{label}: total={total}") | |
| print(f" single token (bare): {single_bare}/{total} ({single_bare / max(total, 1):.2%})") | |
| print(f" single token (leading space): {single_space}/{total} ({single_space / max(total, 1):.2%})") | |
| print(f" single in both forms: {single_both}/{total} ({single_both / max(total, 1):.2%})") | |
| def print_examples(rows: List[Dict], title: str, show: int) -> None: | |
| bad = [r for r in rows if not r["bare_is_single"] or not r["leading_space_is_single"]] | |
| if not bad: | |
| print(f"{title}: all are single tokens in both forms.") | |
| return | |
| print(f"{title}: showing up to {show} non-single examples") | |
| for row in bad[:show]: | |
| print( | |
| f" {row['token']}\n" | |
| f" bare: n={row['bare_n_tokens']} pieces={row['bare_pieces']}\n" | |
| f" leading-space: n={row['leading_space_n_tokens']} pieces={row['leading_space_pieces']}" | |
| ) | |
| def save_json(path: Path, payload: Dict) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(payload, indent=2)) | |
| print(f"Saved JSON report to {path}") | |
| def save_csv(path: Path, rows: List[Dict]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with path.open("w", newline="", encoding="utf-8") as f: | |
| writer = csv.DictWriter( | |
| f, | |
| fieldnames=[ | |
| "kind", | |
| "token", | |
| "bare_n_tokens", | |
| "bare_is_single", | |
| "bare_ids", | |
| "bare_pieces", | |
| "leading_space_n_tokens", | |
| "leading_space_is_single", | |
| "leading_space_ids", | |
| "leading_space_pieces", | |
| ], | |
| ) | |
| writer.writeheader() | |
| for row in rows: | |
| writer.writerow(row) | |
| print(f"Saved CSV report to {path}") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description="Check whether entities/relations are single tokens.") | |
| parser.add_argument("--tokenizer", type=str, default="gpt2", help="Tokenizer name or local path.") | |
| parser.add_argument("--trust-remote-code", action="store_true") | |
| parser.add_argument("--num-entities", type=int, default=50) | |
| parser.add_argument("--num-relations", type=int, default=200) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--show", type=int, default=20, help="How many non-single examples to print.") | |
| parser.add_argument("--output-json", type=Path, default=None, help="Optional JSON output path.") | |
| parser.add_argument("--output-csv", type=Path, default=None, help="Optional CSV output path.") | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| tokenizer = AutoTokenizer.from_pretrained(args.tokenizer, trust_remote_code=args.trust_remote_code) | |
| generator = DataGenerator( | |
| num_entities=args.num_entities, | |
| num_relations=args.num_relations, | |
| seed=args.seed, | |
| ) | |
| entities = sorted(generator.entities) | |
| relations = sorted(generator.relations) | |
| entity_rows = build_rows(tokenizer, entities, "entity") | |
| relation_rows = build_rows(tokenizer, relations, "relation") | |
| all_rows = entity_rows + relation_rows | |
| print(f"Tokenizer: {args.tokenizer}") | |
| print(f"Entity count: {len(entities)} | Relation count: {len(relations)}") | |
| summarize(entity_rows, "Entities") | |
| summarize(relation_rows, "Relations") | |
| print_examples(entity_rows, "Entities", args.show) | |
| print_examples(relation_rows, "Relations", args.show) | |
| if args.output_json: | |
| payload = { | |
| "tokenizer": args.tokenizer, | |
| "num_entities": len(entities), | |
| "num_relations": len(relations), | |
| "entities": entity_rows, | |
| "relations": relation_rows, | |
| } | |
| save_json(args.output_json, payload) | |
| if args.output_csv: | |
| save_csv(args.output_csv, all_rows) | |
| if __name__ == "__main__": | |
| main() | |