"""Attribution of the family tree to organisations and countries, over time; concentration; licence drift; undeclared derivatives. Writes results/*.csv and results/summary.json.""" import json, os, re, sys import numpy as np import pandas as pd D = "data"; OUT = "results"; os.makedirs(OUT, exist_ok=True) N = pd.read_csv(f"{D}/nodes.csv.gz", low_memory=False) R = pd.read_csv(f"{D}/roots_of.csv.gz", low_memory=False, dtype={"id": str, "root": str}, keep_default_na=False) N["id"] = N.id.astype(str) # a few repos are literally named 'nan' / 'null' ORG = pd.read_csv("code/root_orgs.csv").drop_duplicates("author").set_index("author") REHOST = {"unsloth", "huihui-ai", "katuni4ka", "mlx-community", "bartowski", "TheBloke", "lmstudio-community", "NousResearch", "ModelCloud", "RedHatAI", "neuralmagic", "QuantFactory", "mradermacher", "MaziyarPanahi"} FAMILY = [(r"tinyllama", "TinyLlama"), (r"code-?llama", "codellama"), (r"qwen|qwq", "Qwen"), (r"llama", "meta-llama"), (r"mistral|mixtral|ministral|devstral|magistral|pixtral|codestral", "mistralai"), (r"gemma|paligemma", "google"), (r"deepseek", "deepseek-ai"), (r"(^|[-_/])phi[-_]?\d", "microsoft"), (r"flux", "black-forest-labs"), (r"stable-diffusion|sdxl|(^|[-_/])sd-?[123]", "stabilityai"), (r"gpt-oss|whisper", "openai"), (r"(^|[-_/])glm|chatglm", "zai-org"), (r"(^|[-_/])yi-", "01-ai"), (r"falcon", "tiiuae"), (r"granite", "ibm-granite"), (r"smollm", "HuggingFaceTB"), (r"^gpt2|^distilgpt2", "openai-community"), (r"^distilbert", "distilbert"), (r"^(xlm-)?roberta", "FacebookAI"), (r"^bert-", "google-bert"), (r"^t5-", "google-t5")] def resolve(root): a = root.split("/")[0] if "/" in root else "" name = root.split("/")[-1].lower() if a in ORG.index and a not in REHOST: return a, "declared" for pat, fam in FAMILY: if re.search(pat, name): return fam, "name-rule" if a in ORG.index: return a, "declared" return None, "unattributed" roots = pd.DataFrame({"root": R.root.unique()}) res = roots.root.map(resolve) roots["org_author"] = [r[0] for r in res]; roots["how"] = [r[1] for r in res] roots["country"] = roots.org_author.map(ORG.country) roots["organisation"] = (roots.org_author.map(ORG.organisation).str.replace(r"\s*\(.*\)$", "", regex=True) .replace({"Alibaba Cloud": "Alibaba", "Alibaba Group": "Alibaba"})) R = R.merge(roots, on="root", how="left") R["country"] = R.country.fillna("unattributed") N["created"] = pd.to_datetime(N.created, utc=True, errors="coerce") N["month"] = N.created.dt.strftime("%Y-%m") der_ids = set(R.loc[R.depth > 0, "id"]) DER = R[R.depth > 0].merge(N[["id", "month", "created", "downloads", "license", "pipeline", "author"]], on="id") S = {} S["models"] = int(len(N)); S["derivatives"] = len(der_ids); S["derivative_share"] = len(der_ids) / len(N) S["max_depth"] = int(R.depth.max()) S["depth_quantiles"] = {q: float(R[R.depth > 0].groupby("id").depth.max().quantile(q)) for q in (0.5, 0.9, 0.99)} S["roots_with_derivatives"] = int(DER.root.nunique()) S["derivative_weight_attributed"] = float(DER.loc[DER.country != "unattributed", "weight"].sum() / DER.weight.sum()) S["attribution_by_rule"] = DER.groupby("how").weight.sum().div(DER.weight.sum()).round(4).to_dict() # concentration by organisation org = DER.assign(o=DER.organisation.fillna("unattributed:" + DER.root.str.split("/").str[0])) \ .groupby("o").weight.sum().sort_values(ascending=False) org.rename("derivatives").to_csv(f"{OUT}/derivatives_by_organisation.csv") tot = org.sum() S["top_org_share"] = {k: float(org.head(k).sum() / tot) for k in (1, 3, 5, 10, 20)} x = np.sort(org.values); n = len(x) S["gini_organisations"] = float((2 * np.arange(1, n + 1) - n - 1).dot(x) / (n * x.sum())) rootw = DER.groupby("root").weight.sum().sort_values(ascending=False) rootw.rename("derivatives").head(200).to_csv(f"{OUT}/top_roots.csv") S["top_root_models"] = {r: float(v) for r, v in rootw.head(15).items()} # countries: all time, by month, download-weighted cty = DER.groupby("country").weight.sum().sort_values(ascending=False) S["country_share_all_time"] = (cty / cty.sum()).round(4).to_dict() DER["dlw"] = DER.weight * DER.downloads cdl = DER.groupby("country").dlw.sum().sort_values(ascending=False) S["country_share_downloads_30d"] = (cdl / cdl.sum()).round(4).to_dict() mon = DER[DER.month.notna()].pivot_table(index="month", columns="country", values="weight", aggfunc="sum").fillna(0) mon.to_csv(f"{OUT}/derivatives_by_month_country.csv") share = mon.div(mon.sum(1), axis=0) share.to_csv(f"{OUT}/derivative_share_by_month_country.csv") full = share[(share.index >= "2023-01") & (share.index <= "2026-10")] if "CN" in full and "US" in full: cross = full.index[(full.CN > full.US)] S["first_month_CN_above_US"] = cross[0] if len(cross) else None S["months_CN_above_US_since"] = int((full.CN > full.US).sum()) S["CN_US_share_by_year"] = {y: {"CN": float(mon.loc[mon.index.str[:4] == y, "CN"].sum() / mon.loc[mon.index.str[:4] == y].values.sum()), "US": float(mon.loc[mon.index.str[:4] == y, "US"].sum() / mon.loc[mon.index.str[:4] == y].values.sum())} for y in ("2022", "2023", "2024", "2025", "2026")} # robustness to mass uploaders: distinct uploader accounts per month and root country acc = DER[DER.month.notna()].groupby(["month", "country"]).author.nunique().unstack(fill_value=0) acc.to_csv(f"{OUT}/uploaders_by_month_country.csv") accy = DER[DER.month.notna()].assign(y=DER.month.str[:4]).groupby(["y", "country"]).author.nunique().unstack(fill_value=0) S["uploaders_by_year_country"] = accy[[c for c in ("US", "CN", "DE", "FR") if c in accy]].to_dict(orient="index") upl = DER.groupby("author").agg(models=("id", "nunique"), dl=("dlw", "sum"), top_root=("root", lambda s: s.value_counts().index[0])) upl = upl.sort_values("models", ascending=False) upl.head(50).to_csv(f"{OUT}/top_uploaders.csv") S["uploader_accounts"] = int(len(upl)) S["top10_uploaders_share_of_derivatives"] = float(upl.models.head(10).sum() / upl.models.sum()) S["top100_uploaders_share_of_derivatives"] = float(upl.models.head(100).sum() / upl.models.sum()) # capped count: each account counts at most 10 models per root family per month cap = (DER[DER.month.notna()].groupby(["month", "author", "org_author", "country"]).weight.sum() .clip(upper=10).groupby(["month", "country"]).sum().unstack(fill_value=0)) cap.to_csv(f"{OUT}/capped_by_month_country.csv") capy = cap.assign(y=cap.index.str[:4]).groupby("y").sum() capy = capy.div(capy.sum(1), axis=0) S["capped_share_by_year"] = capy[[c for c in ("US", "CN") if c in capy]].round(4).to_dict(orient="index") fam = DER[DER.month.notna()].pivot_table(index="month", columns="org_author", values="weight", aggfunc="sum").fillna(0) keep = fam.sum().sort_values(ascending=False).head(12).index fam[keep].to_csv(f"{OUT}/derivatives_by_month_top_families.csv") # relation types by country E = pd.read_csv(f"{D}/edges.csv.gz") rel = E.drop_duplicates("child").merge(DER.groupby("id").country.first(), left_on="child", right_index=True) S["relation_by_country"] = pd.crosstab(rel.country, rel.relation, normalize="index").round(3).loc[ [c for c in ("US", "CN", "FR", "DE", "GB") if c in set(rel.country)]].to_dict(orient="index") # licence drift (replication): restrictive-licence roots whose descendants declare an OSI-permissive licence PERM = {"apache-2.0", "mit", "bsd-3-clause", "bsd-2-clause", "bsd", "cc0-1.0", "unlicense", "cc-by-4.0", "isc"} rootlic = N.set_index("id").license DER["root_license"] = DER.root.map(rootlic) lic = DER[DER.root_license.notna()].copy() lic["root_class"] = np.where(lic.root_license.isin(PERM), "permissive", "restrictive") lic["child_class"] = np.where(lic.license.isna(), "none", np.where(lic.license.isin(PERM), "permissive", "restrictive")) tab = lic.groupby(["root_license", "child_class"]).weight.sum().unstack(fill_value=0) tab["n"] = tab.sum(1); tab = tab.sort_values("n", ascending=False) tab.head(25).to_csv(f"{OUT}/licence_drift.csv") r = lic[lic.root_class == "restrictive"] S["restrictive_root_children"] = float(r.weight.sum()) S["restrictive_root_children_relabelled_permissive"] = float(r.loc[r.child_class == "permissive", "weight"].sum() / r.weight.sum()) S["restrictive_root_children_no_licence"] = float(r.loc[r.child_class == "none", "weight"].sum() / r.weight.sum()) S["relabelled_downloads_30d"] = float((r.loc[r.child_class == "permissive", "weight"] * r.loc[r.child_class == "permissive", "downloads"]).sum()) for fam_l in ("llama3", "llama3.1", "llama3.2", "llama2", "gemma", "other"): rr = r[r.root_license == fam_l] if len(rr): S[f"relabel_{fam_l}"] = {"children": float(rr.weight.sum()), "permissive": float(rr.loc[rr.child_class == "permissive", "weight"].sum() / rr.weight.sum())} # undeclared derivatives: no parent declared, family name in the repo name, uploaded by someone else noparent = N[N.n_parents == 0].copy() def fam_of(mid): nm = mid.split("/")[-1].lower() for pat, f in FAMILY[:17]: if re.search(pat, nm): return f return None noparent["fam"] = noparent.id.map(fam_of) und = noparent[noparent.fam.notna() & (noparent.author != noparent.fam)] S["undeclared_family_named_models"] = int(len(und)) S["undeclared_share_of_family_named"] = float(len(und) / (len(und) + DER[DER.org_author.isin(set(f for _, f in FAMILY[:17]))].id.nunique())) S["undeclared_downloads_30d"] = int(und.downloads.sum()) und.groupby("fam").size().sort_values(ascending=False).to_csv(f"{OUT}/undeclared_by_family.csv") # hub totals S["hub_downloads_30d"] = int(N.downloads.sum()) S["derivative_downloads_30d_share"] = float(N.loc[N.id.isin(der_ids), "downloads"].sum() / N.downloads.sum()) S["crawl_window"] = {"first_created": str(N.created.min()), "last_created": str(N.created.max())} json.dump(S, open(f"{OUT}/summary.json", "w"), indent=1, default=str) print(json.dumps(S, indent=1, default=str))