--- pretty_name: URLs (tokenized) license: other license_name: per-source-see-card license_link: https://huggingface.co/datasets/ks46/urls-sampled#licensing-and-attribution language: - multilingual task_categories: - text-generation tags: - urls - web - common-crawl - tokenized - bpe - memmap size_categories: - 100B] ++ ids`: a leading end-of-sequence token, then the URL's tokens. `` is id **0** and is the only special token. ``` [0] t t t t [0] t t t [0] t t t t t ... ^ URL 1 ^ URL 2 ^ URL 3 ``` The leading `` is the conditioning prefix: at inference the model is shown `` and the log-probabilities of what follows give that URL's code length. It also delimits URLs, so boundaries are recoverable by scanning for zeros without needing an index. Training that slices fixed-size blocks can ignore boundaries entirely. ## Reading the data ```python import json import numpy as np from huggingface_hub import hf_hub_download bin_path = hf_hub_download("ks46/urls-tokenized", "data/tokens-s00000.bin", repo_type="dataset") meta = json.load(open(hf_hub_download("ks46/urls-tokenized", "data/tokens-s00000.json", repo_type="dataset"))) tokens = np.memmap(bin_path, dtype=np.uint16, mode="r") # zero-copy assert len(tokens) == meta["tokens"] # A fixed-size training block, nanoGPT style block = tokens[1_000_000 : 1_000_512].astype(np.int64) # Or split back into individual URLs starts = np.flatnonzero(tokens == meta["eos_token_id"]) first_url_ids = tokens[starts[0] + 1 : starts[1]] ``` ## Ordering URLs within each shard are ordered by **`xxh3_64(url)` ascending**, not in the source file's order. The source stores each shard sorted by `surt(url)`, so neighbouring URLs share a host. Left that way, a fixed-size training block is a few dozen *related* URLs — one cluster sample rather than many independent ones — and an optimizer step averages far fewer effective examples than its batch size suggests. Hash order fixes that and, unlike a shuffle, is a pure function of the URL set: there is no seed to carry, no RNG whose implementation must stay stable, and the exact order is recomputable by anyone holding the URLs. It is also the same function the source uses to assign shards, so nothing new is introduced. Shard *membership* is unchanged — that depends only on the URL — so every guarantee of the source dataset still holds. As a consequence, for shard *n* every URL satisfies `floor(xxh3_64(url) * 2048 / 2^64) == n`, and the build asserts exactly that for all ~36.6M URLs before writing a shard. **`url` here means the ORIGINAL URL, not the canonical form.** Both the shard assignment and the ordering key hash the URL as it appears in the source corpus. Decoding a bin yields canonical text, so you must apply `canonical()` once — and only once — to recover the value these hashes are computed over. Hashing the canonical form instead is an easy mistake and gives neither the right order nor the right chunk: ```python original = canonical(tok.decode(ids)) # what the hashes are over assert (xxh3_64(original.encode()) * 2048) >> 64 == shard_index ``` ## Recovering the original URL — read this before decoding Decoding gives **canonical** text, not the original URL. Host labels were reordered TLD-first before tokenization, so `https://www.example.com/a` is stored as `https://com.example.www/a`. To get the original back, apply the same function again — it is an involution, so one function serves both directions: ```python from tokenizers import Tokenizer tok = Tokenizer.from_file(hf_hub_download("ks46/urls-tokenized", "tokenizer/tokenizer.json", repo_type="dataset")) url = canonical(tok.decode(first_url_ids.tolist())) # canonical() below ``` The full function, which is all you need: ```python _SCHEMES = ("https://", "http://") _AUTH_END = ("/", "?", "#") def _is_ipv4(host: str) -> bool: parts = host.split(".") if len(parts) != 4: return False return all(p.isascii() and p.isdigit() and len(p) <= 3 and int(p) < 256 for p in parts) def canonical(url: str) -> str: """Reverse the host's label order. Self-inverse: canonical(canonical(u)) == u.""" for scheme in _SCHEMES: if url.startswith(scheme): break else: return url # unrecognised scheme: pass through untouched rest = url[len(scheme):] cut = len(rest) for ch in _AUTH_END: i = rest.find(ch) if i != -1 and i < cut: cut = i authority, tail = rest[:cut], rest[cut:] userinfo, at, hostport = authority.rpartition("@") host, colon, port = hostport.rpartition(":") if not colon or not (port.isascii() and port.isdigit()): host, colon, port = hostport, "", "" # Bracketed IPv6 holds ':' and no meaningful labels; dotted quads reverse # into other dotted quads, so both are left exactly as they are. if not (host.startswith("[") or _is_ipv4(host)): host = ".".join(reversed(host.split("."))) return f"{scheme}{userinfo}{at}{host}{colon}{port}{tail}" if __name__ == "__main__": cases = [ "https://www.example.com/blog/2024/01/post.html?utm_source=x&id=42#top", "http://example.com", "https://a.b.c.d.e.f/", "https://user:pass@www.example.com:8443/p?q=1", "https://1.2.3.4/path", # IPv4: untouched "https://[::1]:8080/x", # IPv6: untouched "https://example.com./trailing", # trailing dot "https://example..com/empty", # empty label "https://localhost/", # single label "https:///no-host", # empty authority "ftp://weird.example.com/x", # unknown scheme: untouched "http://129.222.104.0/25,US,US-CA,San", "not a url at all", "https://xn--80ak6aa92e.com/é中", # punycode + raw UTF-8 "https://WWW.Example.COM/Case", ] print(f"{'input':<58} {'canonical':<58} involution") ok = True for u in cases: c = canonical(u) inv = canonical(c) == u ok &= inv print(f"{u:<58.57} {c:<58.57} {'OK' if inv else 'FAIL'}") raise SystemExit(0 if ok else 1) ``` The pipeline is lossless: `canonical(decode(encode(canonical(u)))) == u`. Both implementations (this one and the Rust one that wrote the bins) were checked against each other on 5,000,000 real URLs, byte-for-byte, and every shard has 1,000 URLs each from its head, middle and tail decoded back out of the finished file and compared to the source before it is published. ## How the tokenizer works Byte-level BPE, vocabulary 8,192, `max_token_length` 24. The initial alphabet is all 256 bytes, so **every** URL is encodable — percent-escapes, punycode, raw UTF-8 in paths — and there is no `` and no fallback path. There is no normalizer, because one would break byte-exact round-tripping. Unlike a general-purpose BPE, URLs are **structurally pre-split** before any merge is applied. Each delimiter below becomes its own piece, and BPE can never merge across one: | set | source | characters | |---|---|---| | gen-delims | RFC 3986 §2.2 | `:/?#[]@` | | sub-delims | RFC 3986 §2.2 | `!$&'()*+,;=` | | unwise | RFC 2396 §2.4.3 + backtick | `` {}|\^`~ `` | | unreserved punctuation | RFC 3986 §2.3, split anyway | `.-_` | | pct-encoding marker | RFC 3986 §2.1 | `%` | Two things are kept whole: `http://` and `https://`, which open nearly every URL, and well-formed percent-escapes (`%[0-9A-Fa-f]{2}`), so `%C3` is one piece. A bare `%` not followed by two hex digits is not an escape, so `100%` splits into `100` + `%`. What survives as content is exactly a run of alphanumerics. The full pattern: ``` https?://|%[0-9A-Fa-f]{2}|[!#$%&'()*+,\-./:;=?@\[\\\]\^_`{|}~] ``` Host labels are then reordered TLD-first so the vocabulary's host hierarchy matches the naming tree — `com` is learned once and shared by every `.com`. `news.bbc.co.uk` becomes `uk` · `.` · `co` · `.` · `bbc` · `.` · `news`, each a single token. ## Intended use Language modelling over URLs, and lossless URL compression in particular: the byte-exact round-trip means a model's log-probabilities over this stream are a valid code length for the original URL. ## Limitations and biases - Inherits every bias of the source corpus, which is Common Crawl derived. It is a sample of what crawlers reached, not of the web as it exists. - Malformed URLs are **kept, not filtered** — stray quotes, literal spaces, commas, bare IP literals with junk paths. Any consumer must handle them. - Tokenization is tuned for compression, not for semantics. Aggressive structural splitting costs roughly 35 tokens per URL, which is more than an unsplit BPE would use. - A shard is an unbiased sample of the corpus, but a **prefix of a shard is not**: shards are stored SURT-sorted, so the first rows are alphabetically-first hosts — IP literals and malformed junk. Sample by stride or shuffle; never take the head. ## Reproduction Built by [linklet](https://huggingface.co/datasets/ks46/urls-sampled) — `rust/urltok` tokenizes a shard in ~94 s on 32 cores: ``` urltok tokenize --parquet part-00000.parquet \ --tokenizer tokenizer/ --out tokens-s00000.bin ``` ## Licensing and attribution Same terms as the source corpus. See [ks46/urls-sampled](https://huggingface.co/datasets/ks46/urls-sampled#licensing-and-attribution). This dataset adds no new content — it is a reversible re-encoding of URLs that are already published there.