Download code/src/features.py from Arushhh/amlc-work: direct link, hf CLI and curl.
- Browser
- Download file 34.9 kB
-
https://huggingface.co/datasets/Arushhh/amlc-work/resolve/main/code/src/features.py
- Command line
-
hf download hf://datasets/Arushhh/amlc-work/code/src/features.py
-
curl -L -o features.py https://huggingface.co/datasets/Arushhh/amlc-work/resolve/main/code/src/features.py
34.9 kB
| """Pair features for the AMLC 2026 matcher (Stage B). | |
| build_idf_tables(s1_norm) -> {country: idf dicts} | |
| build_features(cands, s1_norm, pool_norm, idf_tables, ...) -> pd.DataFrame | |
| ``cands`` is the blocking output (src/blocking.py): s1_id, cand_id, country, src, sim_name, | |
| sim_nameaddr, sim_addr, sim_word, from_reverse [, f_*, rank_*]. ``s1_norm`` / ``pool_norm`` are | |
| the normalised record tables (ROOT/norm/*.parquet; pool = S2 and S3 concatenated) as a pyarrow | |
| Table, polars or pandas DataFrame. | |
| Output: one row per (deduplicated) candidate pair, in input order, with key columns | |
| ``s1_id, cand_id`` (Arrow strings), ``s1_row, pool_row`` (int32 row numbers in the two tables) | |
| followed by the numeric features (float32) and ``country`` (pandas category, categories = the | |
| values present in the data; never a fixed list). ``feature_columns(df)`` lists the model inputs. | |
| Missing-value convention: three-state features are 1 / 0 / -1 (agree / disagree / missing); | |
| similarity features are -1 when either side is empty; blocking sims NaN -> -1. Blocking ranks | |
| (when present) and the competition margins of single-candidate groups stay NaN. | |
| Execution model: the normalised tables are packed into ONE Python ``bytes`` object per table | |
| (one record per row: fields joined by \\x1e, list items by \\x1f) plus an int64 offset array. | |
| Worker processes are forked after packing, so they share those two buffers copy-on-write | |
| without touching per-row Python objects (a list-of-str representation of the 10M-row pool | |
| would be duplicated page by page in every worker by refcount writes). Each task decodes only | |
| the rows it needs. The per-pair loop is plain Python around rapidfuzz calls. | |
| Competition features need every candidate of an S1 record / pool record, so they are computed | |
| after the per-pair pass on the whole candidate table. With ``keep_s1`` (training on an S1 | |
| subsample) only the kept S1 records get the full feature pass; all other rows get a cheap | |
| base-score pass so the competition context (esp. how many S1 records compete for a pool record) | |
| is the one of the full candidate table. | |
| Throughput benchmark: python -m src.features --bench 200000 --workers 16 | |
| """ | |
| from __future__ import annotations | |
| import gc | |
| import math | |
| import multiprocessing as mp | |
| import os | |
| import sys | |
| import time | |
| import warnings | |
| from array import array | |
| import numpy as np | |
| import pandas as pd | |
| import pyarrow as pa | |
| import pyarrow.compute as pc | |
| import pyarrow.parquet as pq | |
| import polars as pl | |
| from rapidfuzz import fuzz | |
| from rapidfuzz.distance import JaroWinkler, Levenshtein | |
| warnings.filterwarnings("ignore", message=r".*fork.*") # polars at-fork warning: workers never call polars | |
| warnings.filterwarnings("ignore", message=r".*empty_as_null.*") | |
| __all__ = [ | |
| "PAIR_FEATURES", "KEY_COLUMNS", "NORM_COLUMNS", | |
| "load_norm", "build_idf_tables", "build_features", "feature_columns", "log", | |
| ] | |
| KEY_COLUMNS = ["s1_id", "cand_id", "s1_row", "pool_row"] | |
| # Columns read from ROOT/norm/*.parquet (missing ones are tolerated, see _FALLBACK). | |
| NORM_COLUMNS = [ | |
| "entity_id", "country", "name_core", "name_legal", "name_tokens", "name_spaceless", "name_alt_names", | |
| "name_is_domain_form", "name_has_indic_script", "name_full", "name_translit", "name_translit_tokens", | |
| "name_translit_unknown", "addr_tokens", "addr_tokens_translit", "addr_numbers", "addr_street_number", | |
| "addr_city", "addr_state", "addr_district", "addr_localities", "addr_street", | |
| ] | |
| _FALLBACK = {"name_translit": "name_core", "name_translit_tokens": "name_tokens", | |
| "addr_tokens_translit": "addr_tokens"} | |
| FS, LS = "\x1e", "\x1f" # field / list-item separators inside a packed record | |
| # (field, kind): s = string, l = list of strings, b = bool | |
| _S1_FIELDS = [("country", "s"), ("name_core", "s"), ("name_tokens", "l"), ("name_spaceless", "s"), | |
| ("name_full", "s"), ("name_legal", "s"), ("addr_tokens_translit", "l"), ("addr_numbers", "l"), | |
| ("addr_street_number", "s"), ("addr_city", "s"), ("addr_state", "s"), ("addr_district", "s"), | |
| ("addr_localities", "l"), ("addr_street", "s")] | |
| _POOL_FIELDS = [("country", "s"), ("name_translit", "s"), ("name_translit_tokens", "l"), ("name_spaceless", "s"), | |
| ("name_full", "s"), ("name_legal", "s"), ("addr_tokens_translit", "l"), ("addr_numbers", "l"), | |
| ("addr_street_number", "s"), ("addr_city", "s"), ("addr_state", "s"), ("addr_district", "s"), | |
| ("addr_localities", "l"), ("addr_street", "s"), ("name_alt_names", "l"), | |
| ("name_has_indic_script", "b")] | |
| _N_S1F, _N_POOLF = len(_S1_FIELDS), len(_POOL_FIELDS) | |
| PAIR_FEATURES = [ | |
| # name: S1 name_core vs pool name_translit (legal words dropped from transliterated Indic names) | |
| "n_ratio", "n_partial", "n_tsort", "n_tset", "n_wratio", "n_jw", "n_lev", | |
| "n_sp_ratio", # spaceless S1 core / full name vs pool spaceless (domain forms) | |
| "n_alt_best", # best ratio against the pool's former / trade names (f/k/a, dba), -1 none | |
| "n_jac", "n_idf_jac", "n_max_idf_shared", "n_shared", | |
| "n_ntok_s1", "n_ntok_pool", "n_ntok_delta", | |
| "n_legal3", "n_first_eq", "n_pfirst_in_s1", "n_s1first_in_pool", | |
| # address: S1 addr_tokens_translit vs pool addr_tokens_translit | |
| "a_jac", "a_idf_jac", "a_max_idf_shared", "a_tset", | |
| "a_stno3", "a_num_jac", "a_s1stno_in_pool", | |
| "a_city3", "a_loc_overlap", "a_city_in_pool", "a_state3", "a_district3", | |
| "a_pool_empty", "a_ntok_s1", "a_ntok_pool", "a_ntok_delta", "a_street_ratio", | |
| # cross (landmark / trade-name leakage) | |
| "x_s1name_paddr", "x_pname_s1addr", | |
| ] | |
| _N_PAIR = len(PAIR_FEATURES) | |
| _I_WRATIO, _I_ATSET = PAIR_FEATURES.index("n_wratio"), PAIR_FEATURES.index("a_tset") | |
| POOL_FLAG_FEATURES = ["p_is_domain", "p_has_indic", "p_translit_unknown"] | |
| CONTEXT_FEATURES = ["s1_name_freq", "s1_addr_freq", "pool_name_freq", | |
| "log_s1_name_freq", "log_s1_addr_freq", "log_pool_name_freq"] | |
| BLOCK_SIMS = ["sim_name", "sim_nameaddr", "sim_addr", "sim_word"] | |
| BLOCK_FLAGS = ["f_name", "f_nameaddr", "f_addr", "f_word"] # optional | |
| BLOCK_RANKS = ["rank_name", "rank_nameaddr", "rank_addr", "rank_word", "rank_rev"] # optional | |
| COMPETITION_FEATURES = [ | |
| "c_base", | |
| "c_s1_rank", "c_s1_gap", "c_s1_margin", "c_s1_n70", "c_s1_n", | |
| "c_p_n", "c_p_n_rel", "c_p_rank", "c_p_gap", "c_p_margin", | |
| ] | |
| BASE_HIGH = 70.0 | |
| # legal words that survive in transliterated Indic names (the lexicon maps the raw name) | |
| _LEGAL_STRIP = frozenset("private limited pvt ltd llp opc llc inc corp corporation incorporated".split()) | |
| _STATE_EQ = {"andhra pradesh": "telangana"} # the generator swaps these two freely | |
| _T0 = time.time() | |
| def log(msg: str) -> None: | |
| rss = "" | |
| try: | |
| import psutil | |
| rss = f" rss={psutil.Process().memory_info().rss / 1e9:.2f}GB" | |
| except Exception: # noqa: BLE001 | |
| pass | |
| print(f"[{time.time() - _T0:8.1f}s{rss}] {msg}", flush=True) | |
| # ---------------------------------------------------------------------------------------------- | |
| # Table helpers | |
| # ---------------------------------------------------------------------------------------------- | |
| def _to_arrow(t) -> pa.Table: | |
| if isinstance(t, pa.Table): | |
| return t | |
| if isinstance(t, pl.DataFrame): | |
| return t.to_arrow() | |
| if isinstance(t, pd.DataFrame): | |
| return pa.Table.from_pandas(t, preserve_index=False) | |
| raise TypeError(f"unsupported table type {type(t)}") | |
| def _to_polars(t) -> pl.DataFrame: | |
| if isinstance(t, pl.DataFrame): | |
| return t | |
| if isinstance(t, pa.Table): | |
| return pl.from_arrow(t) | |
| if isinstance(t, pd.DataFrame): | |
| return pl.from_pandas(t) | |
| raise TypeError(f"unsupported table type {type(t)}") | |
| def load_norm(paths, columns=None) -> pa.Table: | |
| """Read and concatenate normalised parquet tables (only the columns the matcher needs).""" | |
| if isinstance(paths, (str, os.PathLike)): | |
| paths = [paths] | |
| columns = columns or NORM_COLUMNS | |
| tabs = [] | |
| for p in paths: | |
| names = set(pq.ParquetFile(p).schema_arrow.names) | |
| tabs.append(pq.read_table(p, columns=[c for c in columns if c in names])) | |
| if len(tabs) == 1: | |
| return tabs[0] | |
| try: | |
| return pa.concat_tables(tabs, promote_options="permissive") # e.g. list<null> vs list<string> | |
| except TypeError: # pyarrow < 14 | |
| return pa.concat_tables(tabs, promote=True) | |
| def _col(t: pa.Table, name: str): | |
| if name in t.column_names: | |
| return t.column(name) | |
| alt = _FALLBACK.get(name) | |
| if alt and alt in t.column_names: | |
| return t.column(alt) | |
| return None | |
| def _join_list(c, sep: str): | |
| """list<str-ish> (also list<null> from all-empty columns, large_list) -> large_string, joined.""" | |
| c = pc.cast(c, pa.list_(pa.large_string())) | |
| return pc.binary_join(c, pa.scalar(sep, pa.large_string())) | |
| def _str_col(t: pa.Table, name: str, kind: str) -> pa.ChunkedArray: | |
| """One packed-record field as a large_string column.""" | |
| n = t.num_rows | |
| c = _col(t, name) | |
| if c is None: | |
| return pa.chunked_array([pa.array([""] * n, pa.large_string())]) if n else pa.chunked_array([], pa.large_string()) | |
| if kind == "l": | |
| c = _join_list(c, LS) | |
| elif kind == "b": | |
| c = pc.cast(pc.fill_null(c, False), pa.string()) | |
| return pc.fill_null(pc.cast(c, pa.large_string()), "") | |
| def _pack(t: pa.Table, fields) -> tuple[bytes, np.ndarray]: | |
| """Pack rows into one utf-8 buffer; record i = data[off[i]:off[i+1]].""" | |
| if t.num_rows == 0: | |
| return b"", np.zeros(1, dtype=np.int64) | |
| cols = [_str_col(t, f, k) for f, k in fields] | |
| rec = pc.binary_join_element_wise(*cols, pa.scalar(FS, pa.large_string())) | |
| rec = pc.cast(rec, pa.large_string()) | |
| rec = rec.combine_chunks() if isinstance(rec, pa.ChunkedArray) else rec | |
| bufs = rec.buffers() | |
| off = np.frombuffer(bufs[1], dtype=np.int64)[rec.offset: rec.offset + len(rec) + 1].copy() | |
| data = bufs[2].to_pybytes() if bufs[2] is not None else b"" | |
| return data, off | |
| def _np_col(t: pa.Table, name: str, dtype, fill=0) -> np.ndarray: | |
| c = _col(t, name) | |
| if c is None: | |
| return np.full(t.num_rows, fill, dtype=dtype) | |
| return np.asarray(pc.fill_null(c, fill).to_numpy(zero_copy_only=False)).astype(dtype, copy=False) | |
| def _list_len(t: pa.Table, name: str) -> np.ndarray: | |
| c = _col(t, name) | |
| if c is None: | |
| return np.zeros(t.num_rows, dtype=np.int32) | |
| return np.asarray(pc.fill_null(pc.list_value_length(c), 0).to_numpy(zero_copy_only=False)).astype(np.int32) | |
| def _freq_within_country(t: pa.Table, key_expr_col: str, is_list: bool = False) -> np.ndarray: | |
| """Count of rows sharing (country, value) in table t, per row.""" | |
| c = _col(t, key_expr_col) | |
| if c is None or t.num_rows == 0: | |
| return np.ones(t.num_rows, dtype=np.int32) | |
| val = _join_list(c, " ") if is_list else pc.cast(c, pa.large_string()) | |
| df = pl.from_arrow(pa.table({"c": pc.fill_null(_col(t, "country"), ""), "v": pc.fill_null(val, "")})) | |
| return df.select(pl.len().over(["c", "v"]).cast(pl.Int32)).to_series().to_numpy() | |
| # ---------------------------------------------------------------------------------------------- | |
| # IDF | |
| # ---------------------------------------------------------------------------------------------- | |
| def build_idf_tables(s1_norm) -> dict: | |
| """{country: {'n', 'name', 'addr', 'name_default', 'addr_default'}} from the S1 table. | |
| idf(t) = ln((N+1)/(df+1)) + 1 with df = number of S1 records of the country containing t; | |
| unseen tokens get the maximum ln(N+1) + 1. Address items holding spaces are split. | |
| """ | |
| t = _to_arrow(s1_norm) | |
| addr = _col(t, "addr_tokens_translit") | |
| df = pl.from_arrow(pa.table({ | |
| "c": pc.fill_null(_col(t, "country"), ""), | |
| "nt": pc.cast(_col(t, "name_tokens"), pa.list_(pa.large_string())), | |
| "at": pc.fill_null(_join_list(addr, " "), "") if addr is not None else pa.array([""] * t.num_rows), | |
| })) | |
| n_by_c = dict(df.group_by("c").len().iter_rows()) | |
| name_df = (df.select("c", pl.col("nt").list.unique()).explode("nt").drop_nulls("nt") | |
| .filter(pl.col("nt") != "").group_by(["c", "nt"]).len()) | |
| addr_df = (df.select("c", pl.col("at").str.split(" ").list.unique()).explode("at").drop_nulls("at") | |
| .filter(pl.col("at") != "").group_by(["c", "at"]).len()) | |
| out = {} | |
| for c, n in n_by_c.items(): | |
| top = math.log(n + 1) + 1.0 | |
| nd = name_df.filter(pl.col("c") == c) | |
| ad = addr_df.filter(pl.col("c") == c) | |
| out[c] = { | |
| "n": int(n), | |
| "name": dict(zip(nd.get_column("nt").to_list(), | |
| (np.log((n + 1) / (nd.get_column("len").to_numpy() + 1.0)) + 1.0).tolist())), | |
| "addr": dict(zip(ad.get_column("at").to_list(), | |
| (np.log((n + 1) / (ad.get_column("len").to_numpy() + 1.0)) + 1.0).tolist())), | |
| "name_default": top, | |
| "addr_default": top, | |
| } | |
| return out | |
| _EMPTY_IDF = {"n": 0, "name": {}, "addr": {}, "name_default": 1.0, "addr_default": 1.0} | |
| # ---------------------------------------------------------------------------------------------- | |
| # Worker side | |
| # ---------------------------------------------------------------------------------------------- | |
| _G: dict = {} # set in the parent before forking; read-only in workers | |
| def _split(s: str) -> list: | |
| return s.split(LS) if s else [] | |
| def _parse_s1(rec: str, idf_tables: dict): | |
| f = rec.split(FS) | |
| if len(f) != _N_S1F: | |
| f = [""] * _N_S1F | |
| idf = idf_tables.get(f[0], _EMPTY_IDF) | |
| toks = _split(f[2]) | |
| tset = set(toks) | |
| wn, dn = idf["name"], idf["name_default"] | |
| nw = {t: wn.get(t, dn) for t in tset} | |
| atoks = f[6].replace(LS, " ").split() | |
| aset = set(atoks) | |
| wa, da = idf["addr"], idf["addr_default"] | |
| aw = {t: wa.get(t, da) for t in aset} | |
| return ( | |
| f[1], tset, nw, sum(nw.values()), f[3], f[4].replace(" ", ""), f[5], # 0-6 | |
| " ".join(atoks), aset, aw, sum(aw.values()), set(_split(f[7])), f[8], # 7-12 | |
| f[9], _STATE_EQ.get(f[10], f[10]), f[11], set(_split(f[12])), f[13], # 13-17 | |
| len(toks), len(atoks), toks[0] if toks else "", # 18-20 | |
| ) | |
| def _parse_pool(rec: str, idf_tables: dict): | |
| f = rec.split(FS) | |
| if len(f) != _N_POOLF: | |
| f = [""] * _N_POOLF | |
| idf = idf_tables.get(f[0], _EMPTY_IDF) | |
| toks = _split(f[2]) | |
| indic = f[15] == "true" | |
| if indic: | |
| kept = [t for t in toks if t not in _LEGAL_STRIP] | |
| if kept: | |
| toks = kept | |
| core = " ".join(toks) | |
| sp = core.replace(" ", "") | |
| else: | |
| core = f[1] | |
| sp = f[3] | |
| tset = set(toks) | |
| wn, dn = idf["name"], idf["name_default"] | |
| atoks = f[6].replace(LS, " ").split() | |
| aset = set(atoks) | |
| wa, da = idf["addr"], idf["addr_default"] | |
| return ( | |
| core, tset, sum(wn.get(t, dn) for t in tset), sp, f[5], # 0-4 | |
| " ".join(atoks), aset, sum(wa.get(t, da) for t in aset), set(_split(f[7])), f[8], # 5-9 | |
| f[9], _STATE_EQ.get(f[10], f[10]), f[11], set(_split(f[12])), f[13], # 10-14 | |
| len(toks), len(atoks), toks[0] if toks else "", _split(f[14]), # 15-18 | |
| ) | |
| _ratio, _partial, _tsort, _tset = fuzz.ratio, fuzz.partial_ratio, fuzz.token_sort_ratio, fuzz.token_set_ratio | |
| _wratio, _jw, _lev = fuzz.WRatio, JaroWinkler.normalized_similarity, Levenshtein.normalized_similarity | |
| _NAME_MISSING = (-1.0,) * 7 | |
| def _pair(a, b) -> tuple: | |
| (a_core, a_tset, a_nw, a_nws, a_sp, a_fsp, a_legal, a_astr, a_aset, a_aw, a_aws, a_nums, a_stno, | |
| a_city, a_state, a_dist, a_locs, a_street, a_ntok, a_antok, a_first) = a | |
| (b_core, b_tset, b_nws, b_sp, b_legal, b_astr, b_aset, b_aws, b_nums, b_stno, | |
| b_city, b_state, b_dist, b_locs, b_street, b_ntok, b_antok, b_first, b_alts) = b | |
| # ---- name | |
| if b_core and a_core: | |
| nm = (_ratio(a_core, b_core), _partial(a_core, b_core), _tsort(a_core, b_core), _tset(a_core, b_core), | |
| _wratio(a_core, b_core), _jw(a_core, b_core), _lev(a_core, b_core)) | |
| else: | |
| nm = _NAME_MISSING | |
| if b_sp: | |
| sp = _ratio(a_sp, b_sp) | |
| if a_fsp != a_sp: | |
| sp = max(sp, _ratio(a_fsp, b_sp)) | |
| else: | |
| sp = -1.0 | |
| alt = max(_ratio(a_core, x) for x in b_alts) if b_alts else -1.0 | |
| inter = a_tset & b_tset | |
| nsh = len(inter) | |
| nun = len(a_tset) + len(b_tset) - nsh | |
| if nsh: | |
| ws = [a_nw[t] for t in inter] | |
| iw, mx = sum(ws), max(ws) | |
| else: | |
| iw = mx = 0.0 | |
| den = a_nws + b_nws - iw | |
| # ---- address | |
| if a_astr and b_astr: | |
| ai = a_aset & b_aset | |
| if ai: | |
| ws = [a_aw[t] for t in ai] | |
| aiw, amx = sum(ws), max(ws) | |
| else: | |
| aiw = amx = 0.0 | |
| aden = a_aws + b_aws - aiw | |
| ajac = len(ai) / (len(a_aset) + len(b_aset) - len(ai)) | |
| aijac = aiw / aden if aden > 0 else -1.0 | |
| atset = _tset(a_astr, b_astr) | |
| else: | |
| ajac = aijac = amx = atset = -1.0 | |
| if a_nums and b_nums: | |
| nj = len(a_nums & b_nums) / len(a_nums | b_nums) | |
| else: | |
| nj = -1.0 | |
| return nm + ( | |
| sp, alt, | |
| nsh / nun if nun else -1.0, iw / den if den > 0 else -1.0, mx, nsh, | |
| a_ntok, b_ntok, b_ntok - a_ntok, | |
| (1 if a_legal == b_legal else 0) if (a_legal and b_legal) else -1, | |
| (1 if a_first == b_first else 0) if (a_first and b_first) else -1, | |
| (1 if b_first in a_tset else 0) if b_first else -1, | |
| (1 if a_first in b_tset else 0) if a_first else -1, | |
| ajac, aijac, amx, atset, | |
| (1 if a_stno == b_stno else 0) if (a_stno and b_stno) else -1, | |
| nj, | |
| (1 if a_stno in b_nums else 0) if (a_stno and b_nums) else -1, | |
| (1 if a_city == b_city else 0) if (a_city and b_city) else -1, | |
| (len(a_locs & b_locs) / len(a_locs) if b_astr else -1.0) if a_locs else -1.0, | |
| (1 if (" " + a_city + " ") in (" " + b_astr + " ") else 0) if (a_city and b_astr) else -1, | |
| (1 if a_state == b_state else 0) if (a_state and b_state) else -1, | |
| (1 if a_dist == b_dist else 0) if (a_dist and b_dist) else -1, | |
| 0 if b_astr else 1, | |
| a_antok, b_antok, b_antok - a_antok, | |
| _ratio(a_street, b_street) if (a_street and b_street) else -1.0, | |
| _partial(a_core, b_astr) if (a_core and b_astr) else -1.0, | |
| _partial(b_core, a_astr) if (b_core and a_astr) else -1.0, | |
| ) | |
| def _base(a, b) -> float: | |
| w = _wratio(a[0], b[0]) if (a[0] and b[0]) else 0.0 | |
| t = _tset(a[7], b[5]) if (a[7] and b[5]) else 0.0 | |
| return 0.5 * w + 0.5 * t | |
| def _decode_rows(data: bytes, off: np.ndarray, rows: np.ndarray, parse, idf_tables) -> list: | |
| starts = off[rows].tolist() | |
| ends = off[rows + 1].tolist() | |
| return [parse(data[s:e].decode("utf-8"), idf_tables) for s, e in zip(starts, ends)] | |
| def _task(args): | |
| """(mode, lo, hi) over the global row arrays of that mode -> (mode, lo, hi, result).""" | |
| mode, lo, hi = args | |
| g = _G | |
| r1 = g[f"r1_{mode}"][lo:hi] | |
| r2 = g[f"r2_{mode}"][lo:hi] | |
| was = gc.isenabled() | |
| gc.disable() | |
| try: | |
| idf = g["idf"] | |
| u1, inv1 = np.unique(r1, return_inverse=True) | |
| u2, inv2 = np.unique(r2, return_inverse=True) | |
| A = _decode_rows(g["s1_data"], g["s1_off"], u1, _parse_s1, idf) | |
| B = _decode_rows(g["pool_data"], g["pool_off"], u2, _parse_pool, idf) | |
| if mode == "full": | |
| out = array("f") | |
| ext = out.extend | |
| for i, j in zip(inv1.tolist(), inv2.tolist()): | |
| ext(_pair(A[i], B[j])) | |
| res = np.frombuffer(out, dtype=np.float32).reshape(-1, _N_PAIR) | |
| else: | |
| res = np.fromiter((_base(A[i], B[j]) for i, j in zip(inv1.tolist(), inv2.tolist())), | |
| dtype=np.float32, count=hi - lo) | |
| finally: | |
| if was: | |
| gc.enable() | |
| return mode, lo, hi, res | |
| def _run_tasks(tasks, n_jobs: int, on_result, total_rows: int, label: str, verbose: bool): | |
| t0 = time.time() | |
| done = 0 | |
| last = t0 | |
| if n_jobs <= 1 or len(tasks) <= 1: | |
| it = map(_task, tasks) | |
| pool = None | |
| else: | |
| ctx = mp.get_context("fork") | |
| gc.collect() | |
| gc.freeze() # keep the GC from writing to every shared object's header after fork | |
| pool = ctx.Pool(n_jobs) | |
| it = pool.imap_unordered(_task, tasks, chunksize=1) | |
| try: | |
| for mode, lo, hi, res in it: | |
| on_result(mode, lo, hi, res) | |
| done += hi - lo | |
| now = time.time() | |
| if verbose and (now - last > 30 or done == total_rows): | |
| rate = done / max(now - t0, 1e-9) | |
| eta = (total_rows - done) / rate if rate > 0 else float("nan") | |
| log(f" {label}: {done:,}/{total_rows:,} rows, {rate:,.0f} rows/s " | |
| f"({rate / max(n_jobs, 1):,.0f}/worker), eta {eta:.0f}s") | |
| last = now | |
| finally: | |
| if pool is not None: | |
| pool.close() | |
| pool.join() | |
| gc.unfreeze() | |
| return done / max(time.time() - t0, 1e-9) | |
| # ---------------------------------------------------------------------------------------------- | |
| # Competition features (vectorised) | |
| # ---------------------------------------------------------------------------------------------- | |
| def _group_stats(key: np.ndarray, base: np.ndarray): | |
| """Per-row stats of ``base`` within groups of ``key``: rank (1 = best, ties -> min), gap to the | |
| group best, margin to the best OTHER row (NaN for single-row groups), count >= BASE_HIGH, size.""" | |
| n = len(key) | |
| if n == 0: | |
| z = np.zeros(0, np.float32) | |
| return z, z, z, z, z | |
| order = np.lexsort((-base, key)) | |
| k = key[order] | |
| b = base[order].astype(np.float64) | |
| new_g = np.empty(n, dtype=bool) | |
| new_g[0] = True | |
| np.not_equal(k[1:], k[:-1], out=new_g[1:]) | |
| starts = np.flatnonzero(new_g) | |
| gid = np.cumsum(new_g) - 1 | |
| size = np.diff(np.append(starts, n)) | |
| idx = np.arange(n) | |
| pos = idx - starts[gid] | |
| new_v = new_g.copy() | |
| new_v[1:] |= b[1:] != b[:-1] | |
| first_of_val = np.maximum.accumulate(np.where(new_v, idx, 0)) | |
| rank = first_of_val - starts[gid] + 1 | |
| top1 = b[starts] | |
| second = np.where(size > 1, b[np.minimum(starts + 1, n - 1)], np.nan) | |
| best_other = np.where(pos == 0, second[gid], top1[gid]) | |
| margin = b - best_other | |
| gap = top1[gid] - b | |
| n_high = np.add.reduceat((b >= BASE_HIGH).astype(np.int64), starts) | |
| out = [] | |
| for v in (rank, gap, margin, n_high[gid], size[gid]): | |
| o = np.empty(n, dtype=np.float32) | |
| o[order] = v | |
| out.append(o) | |
| return tuple(out) | |
| # ---------------------------------------------------------------------------------------------- | |
| # Main entry | |
| # ---------------------------------------------------------------------------------------------- | |
| def feature_columns(df: pd.DataFrame) -> list: | |
| return [c for c in df.columns if c not in KEY_COLUMNS] | |
| def _arrow_series(arr, name: str) -> pd.Series: | |
| arr = pc.cast(arr, pa.large_string()) | |
| if isinstance(arr, pa.ChunkedArray): | |
| arr = arr.combine_chunks() | |
| return pd.Series(pd.arrays.ArrowExtensionArray(arr), name=name) | |
| def build_features(cands, s1_norm, pool_norm, idf_tables: dict, *, n_jobs: int | None = None, | |
| task_rows: int = 50_000, keep_s1=None, verbose: bool = True) -> pd.DataFrame: | |
| """Feature table for candidate pairs (see module docstring). | |
| keep_s1 : optional iterable of S1 ids; only their rows are featurised and returned, while the | |
| competition features still see every row of ``cands`` (cheap base-score pass). | |
| n_jobs : worker processes (fork); default os.cpu_count(); 1 = in-process. | |
| """ | |
| t_start = time.time() | |
| n_jobs = int(n_jobs or os.cpu_count() or 1) | |
| s1t, pt = _to_arrow(s1_norm), _to_arrow(pool_norm) | |
| c = _to_polars(cands) | |
| present = set(c.columns) | |
| need = ["s1_id", "cand_id"] + [x for x in ["country", "src"] + BLOCK_SIMS + ["from_reverse"] | |
| + BLOCK_FLAGS + BLOCK_RANKS if x in present] | |
| c = c.select(need) | |
| # ---- entity id -> row number (vectorised join; order restored by the row index) | |
| n1, n2 = s1t.num_rows, pt.num_rows | |
| m1 = pl.DataFrame({"s1_id": pl.from_arrow(pc.cast(s1t.column("entity_id"), pa.large_string())), | |
| "s1_row": pl.int_range(0, n1, eager=True, dtype=pl.Int32)}).unique("s1_id", keep="first") | |
| m2 = pl.DataFrame({"cand_id": pl.from_arrow(pc.cast(pt.column("entity_id"), pa.large_string())), | |
| "pool_row": pl.int_range(0, n2, eager=True, dtype=pl.Int32)}).unique("cand_id", keep="first") | |
| c = (c.with_columns(pl.col("s1_id").cast(pl.Utf8), pl.col("cand_id").cast(pl.Utf8)).with_row_index("_i") | |
| .join(m1, on="s1_id", how="left").join(m2, on="cand_id", how="left").sort("_i")) | |
| bad = c.filter(pl.col("s1_row").is_null() | pl.col("pool_row").is_null()).height | |
| if bad: | |
| print(f"WARNING: {bad:,} candidate rows reference ids missing from the normalised tables; dropped", | |
| file=sys.stderr) | |
| c = c.filter(pl.col("s1_row").is_not_null() & pl.col("pool_row").is_not_null()) | |
| n_before = c.height | |
| c = c.unique(subset=["s1_row", "pool_row"], keep="first", maintain_order=True).drop("_i") | |
| if c.height < n_before: | |
| print(f"WARNING: {n_before - c.height:,} duplicate (s1_id, cand_id) rows dropped", file=sys.stderr) | |
| del m1, m2 | |
| N = c.height | |
| r1_all = c.get_column("s1_row").to_numpy().astype(np.int64) | |
| r2_all = c.get_column("pool_row").to_numpy().astype(np.int64) | |
| if keep_s1 is not None: | |
| keep_ids = (keep_s1.cast(pl.Utf8) if isinstance(keep_s1, pl.Series) | |
| else pl.Series("k", [str(x) for x in keep_s1], dtype=pl.Utf8)) | |
| keep = c.get_column("s1_id").is_in(keep_ids).to_numpy() | |
| else: | |
| keep = np.ones(N, dtype=bool) | |
| kpos = np.flatnonzero(keep) | |
| bpos = np.flatnonzero(~keep) | |
| NK = len(kpos) | |
| if verbose: | |
| log(f"build_features: {N:,} candidate rows ({NK:,} featurised, {len(bpos):,} base-only), " | |
| f"S1 table {n1:,}, pool table {n2:,}, workers {n_jobs}") | |
| # ---- pack tables, parent-side vectors | |
| t = time.time() | |
| s1_data, s1_off = _pack(s1t, _S1_FIELDS) | |
| pool_data, pool_off = _pack(pt, _POOL_FIELDS) | |
| p_dom = _np_col(pt, "name_is_domain_form", np.float32, False) | |
| p_ind = _np_col(pt, "name_has_indic_script", np.float32, False) | |
| p_unk = _np_col(pt, "name_translit_unknown", np.float32, 0) | |
| s1_nf = _freq_within_country(s1t, "name_core") | |
| s1_af = _freq_within_country(s1t, "addr_tokens_translit", is_list=True) | |
| p_nf = _freq_within_country(pt, "name_translit") | |
| s1_ck = pc.fill_null(_col(s1t, "country"), "").to_numpy(zero_copy_only=False) | |
| if verbose: | |
| log(f" packed tables: S1 {len(s1_data) / 1e6:.0f} MB, pool {len(pool_data) / 1e6:.0f} MB ({time.time() - t:.1f}s)") | |
| # ---- per-pair pass (workers) | |
| _G.clear() | |
| _G.update(s1_data=s1_data, s1_off=s1_off, pool_data=pool_data, pool_off=pool_off, idf=idf_tables, | |
| r1_full=r1_all[kpos], r2_full=r2_all[kpos], r1_base=r1_all[bpos], r2_base=r2_all[bpos]) | |
| num_cols = (PAIR_FEATURES + POOL_FLAG_FEATURES + CONTEXT_FEATURES + BLOCK_SIMS + ["from_reverse"] | |
| + [x for x in BLOCK_FLAGS + BLOCK_RANKS if x in present] + ["is_s2"] + COMPETITION_FEATURES) | |
| M = np.empty((NK, len(num_cols)), dtype=np.float32) | |
| base = np.empty(N, dtype=np.float32) | |
| tasks = [("full", lo, min(lo + task_rows, NK)) for lo in range(0, NK, task_rows)] | |
| tasks += [("base", lo, min(lo + task_rows, len(bpos))) for lo in range(0, len(bpos), task_rows)] | |
| def on_result(mode, lo, hi, res): | |
| if mode == "full": | |
| M[lo:hi, :_N_PAIR] = res | |
| w = np.maximum(res[:, _I_WRATIO], 0) | |
| ts = np.maximum(res[:, _I_ATSET], 0) | |
| base[kpos[lo:hi]] = 0.5 * w + 0.5 * ts | |
| else: | |
| base[bpos[lo:hi]] = res | |
| t = time.time() | |
| try: | |
| rate = _run_tasks(tasks, n_jobs, on_result, N, "pair features", verbose) | |
| finally: | |
| _G.clear() | |
| del s1_data, pool_data | |
| if verbose: | |
| log(f" pair pass: {N:,} rows in {time.time() - t:.1f}s ({rate:,.0f} rows/s overall)") | |
| # ---- parent-side features for the kept rows | |
| t = time.time() | |
| r1k, r2k = r1_all[kpos], r2_all[kpos] | |
| j = _N_PAIR | |
| for arr in (p_dom, p_ind, p_unk): | |
| M[:, j] = arr[r2k] | |
| j += 1 | |
| f1, f2, f3 = s1_nf[r1k], s1_af[r1k], p_nf[r2k] | |
| for arr in (f1, f2, f3, np.log1p(f1), np.log1p(f2), np.log1p(f3)): | |
| M[:, j] = arr | |
| j += 1 | |
| ck = c.filter(pl.Series(keep)) if NK < N else c | |
| for s in BLOCK_SIMS: | |
| if s in present: | |
| M[:, j] = ck.get_column(s).cast(pl.Float32).fill_nan(None).fill_null(-1.0).to_numpy() | |
| else: | |
| M[:, j] = -1.0 | |
| j += 1 | |
| M[:, j] = (ck.get_column("from_reverse").cast(pl.Float32).fill_null(0.0).to_numpy() | |
| if "from_reverse" in present else 0.0) | |
| j += 1 | |
| for s in BLOCK_FLAGS: | |
| if s in present: | |
| M[:, j] = ck.get_column(s).cast(pl.Float32).fill_null(0.0).to_numpy() | |
| j += 1 | |
| for s in BLOCK_RANKS: | |
| if s in present: | |
| M[:, j] = ck.get_column(s).cast(pl.Float32).to_numpy() # null -> NaN (not retrieved) | |
| j += 1 | |
| if "src" in present: | |
| M[:, j] = (ck.get_column("src") == "S2").cast(pl.Float32).fill_null(0.0).to_numpy() | |
| else: | |
| M[:, j] = ck.get_column("cand_id").str.starts_with("S2-").cast(pl.Float32).to_numpy() | |
| j += 1 | |
| # ---- competition features over the whole candidate table | |
| s_rank, s_gap, s_margin, s_n70, s_n = _group_stats(r1_all, base) | |
| p_rank, p_gap, p_margin, _, p_n = _group_stats(r2_all, base) | |
| # pool-side count relative to the country mean (the S1/pool ratio differs between train and test) | |
| s1_country_code, _ = pd.factorize(s1_ck) | |
| cc = s1_country_code[r1_all] if len(s1_country_code) else np.zeros(N, dtype=np.int64) | |
| first_of_pool = np.zeros(N, dtype=bool) | |
| _, first_idx = np.unique(r2_all, return_index=True) | |
| first_of_pool[first_idx] = True | |
| ncc = int(cc.max()) + 1 if N else 1 | |
| sums = np.bincount(cc[first_of_pool], weights=p_n[first_of_pool], minlength=ncc) | |
| cnts = np.bincount(cc[first_of_pool], minlength=ncc) | |
| mean_pn = np.where(cnts > 0, sums / np.maximum(cnts, 1), 1.0) | |
| p_n_rel = p_n / mean_pn[cc] | |
| for arr in (base, s_rank, s_gap, s_margin, s_n70, s_n, p_n, p_n_rel, p_rank, p_gap, p_margin): | |
| M[:, j] = arr[kpos] if NK < N else arr | |
| j += 1 | |
| assert j == len(num_cols), (j, len(num_cols)) | |
| # ---- assemble | |
| df = pd.DataFrame(M, columns=num_cols, copy=False) | |
| if "country" in present: | |
| cser = ck.get_column("country").cast(pl.Utf8).fill_null("") | |
| else: | |
| cser = pl.Series("country", s1_ck[r1k].tolist(), dtype=pl.Utf8) | |
| cats = sorted(cser.unique().to_list()) | |
| codes = cser.cast(pl.Enum(cats)).to_physical().to_numpy().astype(np.int32) if NK else np.zeros(0, np.int32) | |
| df["country"] = pd.Categorical.from_codes(codes, categories=cats) | |
| df.insert(0, "pool_row", r2k.astype(np.int32)) | |
| df.insert(0, "s1_row", r1k.astype(np.int32)) | |
| df.insert(0, "cand_id", _arrow_series(ck.get_column("cand_id").to_arrow(), "cand_id")) | |
| df.insert(0, "s1_id", _arrow_series(ck.get_column("s1_id").to_arrow(), "s1_id")) | |
| if verbose: | |
| log(f" features assembled: {df.shape[0]:,} rows x {len(num_cols) + 1} features " | |
| f"({M.nbytes / 1e9:.2f} GB float32), parent-side {time.time() - t:.1f}s, " | |
| f"total {time.time() - t_start:.1f}s") | |
| return df | |
| # ---------------------------------------------------------------------------------------------- | |
| # Throughput benchmark on synthetic normalised records | |
| # ---------------------------------------------------------------------------------------------- | |
| def _bench(n_pairs: int, workers: int, seed: int = 0) -> None: | |
| import random | |
| from src.normalize import normalize_record | |
| rng = random.Random(seed) | |
| A = ["holloway", "prime", "westbrook", "summit", "riverside", "oakridge", "maple", "cedar", "liberty", | |
| "shree", "krishna", "ganesh", "balaji", "durga", "sai", "vishnu", "maruti", "surya"] | |
| B = ["dental", "pediatric", "seafood", "consulting", "logistics", "realty", "marketing", "traders", | |
| "textiles", "pharma", "constructions", "motors", "foods", "primary care"] | |
| C = ["group", "llc", "inc", "services", "center", "private limited", "pvt ltd", "llp"] | |
| ST = ["elm", "oak", "main", "mg", "station", "lake", "hill", "pine", "sunset", "banjara hills", "civil lines"] | |
| CITY = ["phoenix, az", "fort worth, tx", "high point, nc", "hyderabad, telangana", "pune, maharashtra", | |
| "bengaluru, karnataka", "new delhi, delhi"] | |
| def rec(i): | |
| name = f"{rng.choice(A)} {rng.choice(B)} {rng.choice(C)}" | |
| addr = f"{rng.randint(1, 9999)} {rng.choice(ST)} road, {rng.choice(['sector 4, ', ''])}{rng.choice(CITY)}" | |
| r = normalize_record(name, addr, rng.choice(["US", "India"])) | |
| r["entity_id"] = i | |
| r["name_translit"], r["name_translit_tokens"], r["name_translit_unknown"] = r["name_core"], r["name_tokens"], 0 | |
| r["addr_tokens_translit"] = r["addr_tokens"] | |
| return r | |
| n1 = max(1000, n_pairs // 40) | |
| n2 = max(4000, n_pairs // 8) | |
| s1 = pa.Table.from_pylist([rec(f"S1-{i}") for i in range(n1)]) | |
| pool = pa.Table.from_pylist([rec(f"S{2 + i % 2}-{i}") for i in range(n2)]) | |
| nr = np.random.default_rng(seed) | |
| a = np.sort(nr.integers(0, n1, n_pairs)) | |
| b = nr.integers(0, n2, n_pairs) | |
| cands = pl.DataFrame({"s1_id": s1.column("entity_id").to_numpy(zero_copy_only=False)[a], | |
| "cand_id": pool.column("entity_id").to_numpy(zero_copy_only=False)[b], | |
| "country": "US", "src": "S2", | |
| **{s: nr.random(n_pairs).astype(np.float32) for s in BLOCK_SIMS}, | |
| "from_reverse": nr.random(n_pairs) < 0.1}) | |
| idf = build_idf_tables(s1) | |
| t = time.time() | |
| df = build_features(cands, s1, pool, idf, n_jobs=workers, task_rows=20_000) | |
| dt = time.time() - t | |
| print(f"bench: {len(df):,} pairs x {len(feature_columns(df))} features in {dt:.1f}s -> " | |
| f"{len(df) / dt:,.0f} pairs/s with {workers} workers ({len(df) / dt / workers:,.0f}/worker)") | |
| if __name__ == "__main__": | |
| import argparse | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--bench", type=int, default=200_000) | |
| ap.add_argument("--workers", type=int, default=os.cpu_count()) | |
| a = ap.parse_args() | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| _bench(a.bench, a.workers) | |