oss-ecosystem-data / code /hfeco /classify.py
saladday1's picture
code: sync from git
ff88a82 verified
Raw History Blame Contribute Delete
31.9 kB
"""Decide, for each candidate, which official model of a family it belongs to and how.
lineage a member lineage of the family (e.g. H3 | H3-Image | H3-Image-PE), or
unrelated | unknown
relation official | adapter | finetune | merge | quantized | repackage | mirror |
component | tool | no-weights | app (Space) | dataset
family True when the repo is about the family at all (even if the member is unknown)
Evidence is tiered. Tier 1 is structural and decides on its own; tier 2 (declared base,
repo content, dates) decides only when tier 1 is silent; names alone (tier 3) give at
most low confidence. Every decision keeps its reasons in `evidence`. All family-specific
facts come from the Family object (hfeco/families/*.py).
"""
import json
import re
import numpy as np
from .enrich import is_weight
from .family import Arch
VERSION = "2026-11-20.1"
DERIVED = {"adapter", "finetune", "merge", "quantized", "repackage", "mirror", "component"}
HF_RELATIONS = {"adapter", "finetune", "merge", "quantized"}
SAME = 1e-3 # probe distance below this = same weights (bf16 -> fp16 copies land at ~0)
LORA_KEY = re.compile(r"lora_[ABab]\b|lora_down|lora_up|lora\.(down|up)|\.lokr_|\.hada_|\.alpha$|\.diff(_b)?$",
re.I)
QUANT_NAME = re.compile(r"fp8|int8|int4|int6|nf4|nvfp4|mxfp|fp4|w4a\d|w6a8|w8a8|gptq|awq|svdq|nunchaku|"
r"q[2-8]_[0k]|q[2-8]_k|iq[1-4]|bnb|sdnq|convrot|[2-8]-?bit\b|gguf|exl2|hqq|quant", re.I)
MERGE_NAME = re.compile(r"merge|merged|mix\b|fused|\bfuse\b|blend|hybrid|graft", re.I) # not "mixed": mixed precision
REPACK_NAME = re.compile(r"comfy|diffusers|single[-_ ]?file|repack|split|bf16|fp16|fp32|pruned|mlx", re.I)
TUNED_NAME = re.compile(r"finetun|fine-tun|\bft\b|turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|fast|"
r"lcm|dmd|pdmd|singularity|eros|nsfw|uncensor|heretic|abliterat", re.I)
DISTILL_NAME = re.compile(r"turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|lcm|dmd|pdmd|fast", re.I)
# Adult content is counted like anything else but never named on the (public) dashboard, so
# these lean towards hiding. Names: explicit words, also inside compounds ("epiccum", "Tit_Fuck").
NSFW = re.compile(r"nsfw|porn|hentai|nude|nudity|naked|sex|dildo|cum(?![a-z])|cumshot|blowj|blow[-_ ]?job|"
r"deep[-_ ]?throat|pussy|vagina|penis|dick(?![a-z])|cock(?![a-z])|tits?(?![a-z])|titty|"
r"titties|tiddies|boob|breast|nipple|anal(?![a-z])|orgasm|squirt|creampie|bukkake|milf|"
r"futa|bdsm|bondage|fetish|lewd|ecchi|ahegao|fuck|erotic|xxx|uncensor|strip(?:tease|per)|"
r"onlyfans|topless|undress|lingerie|bikini|r18|moan|pleasure|writh|cowgirl|doggy|missionary|"
r"panties|underwear|masturbat|handjob|footjob|grop(?:e|ing)|jiggl|booty|twerk|thicc|seduc|"
r"sensual|horny|slut|whore|bimbo|busty|cleavage|upskirt|voyeur|"
r"(?:(?<=\d)|(?<=ten))eros|(?:\b|(?<=_))eros(?![a-z])", re.I) # "10ErosMax", "TenEros"
# Cards only count when they describe the model itself as adult: derivatives copy the official
# license ("unlawful, pornographic, or ...") and many cards say "does not contain NSFW content".
NSFW_CARD = re.compile(r"\bnsfw[- ](?:lora|model|version|finetune|fine-tune|merge|capable|focused|checkpoint)s?\b|"
r"trained on .{0,30}\bporn|\bhentai\b|\bnudity\b|explicit sexual|not-for-all-audiences",
re.I)
# Training/merge tools describe merges in prose; quantizers have a bare "merge" field for a compute step.
META_MERGE = re.compile(r"lora[ _-]?merg|merged|graft|merge[ _](of|from|method|ratio|weights)|linear merge|"
r"consensus merge|baked", re.I)
LORA_NAME = re.compile(r"lora|lycoris|locon|loha|lokr|adapter", re.I)
AUTHORS = {} # family key -> authors who publish family repos (filled by classify_all)
COMMUNITY = {} # family key -> weight-file index over all probed repos (for whole-repo copies)
TEXT_LLM_TYPES = re.compile(r"^(qwen|llama|mistral|gemma|phi|glm|deepseek|minimax_m)", re.I)
def declared_graph(raw):
"""child -> list of (relation, parent) as parsed by HF from each card."""
return {r.repo_id: [tuple(p.split(":", 1)) for p in r.hf_parents] for r in raw.itertuples()}
def declared_member(rid, g, fam, seen=None):
"""Nearest family base reached by following declared parents."""
lob = fam.lineage_of_base()
if rid in lob:
return lob[rid]
seen = seen or set()
if rid in seen:
return None
seen.add(rid)
best = None
for _, p in g.get(rid, []):
if p in lob:
return lob[p]
best = best or declared_member(p, g, fam, seen)
return best
def probe_match(probe, fam):
"""Compare a probed tensor slice with the official ones -> (lineage, rel_distance, source)."""
if not probe or not probe.get("values"):
return None
v = np.array(probe["values"], dtype=np.float64)
best = None
for ref in fam.ref["probes"]:
r = np.array(ref["values"][:len(v)], dtype=np.float64)
if len(r) != len(v):
continue
d = float(np.linalg.norm(v - r) / (np.linalg.norm(r) + 1e-12))
if best is None or d < best[1]:
best = (ref["lineage"], d, ref["source"])
return best
def sha_mirror(files, fam):
wb = [f for f in files or [] if f.get("sha256") and f.get("size", 0) > 1_000_000
and is_weight(f["name"])] # tokenizers etc. are shared widely
if not wb:
return None
total = sum(f["size"] for f in wb)
hit, any_b = {}, 0
for f in wb:
ref = fam.ref["sha256"].get(f["sha256"])
if ref:
any_b += f["size"]
for lin in ref.get("lineages") or [ref.get("lineage")]:
hit[lin] = hit.get(lin, 0) + f["size"]
if not hit:
return None
lin = max(hit.items(), key=lambda x: x[1])[0]
return lin, any_b / total
def architecture(ev, fam):
"""The family layout a repo ships, from config.json or the GGUF header: (Arch, why); ("other",
why) when the repo names another model's architecture; None when it names none."""
if not fam.archs:
return None
kv = (ev.get("gguf") or {}).get("kv") or {}
ga = kv.get("general.architecture")
names = " ".join(str(x) for c in (ev.get("config") or {}, ev.get("file_config") or {})
for x in [c.get("model_type"), *(c.get("architectures") or [])] if x)
names = " ".join(x for x in [names, ga] if x)
if not names:
return None
size = {"hidden": ev.get("hidden_size") or kv.get(f"{ga}.embedding_length"),
"vocab": ev.get("vocab_size") or kv.get(f"{ga}.vocab_size") or kv.get("tokenizer.ggml.tokens.count")}
near = None
for a in fam.archs:
if not a.names.search(names):
continue
want = [(k, v) for k, v in (("hidden", a.hidden), ("vocab", a.vocab)) if v]
if a.strict and any(not size[k] for k, _ in want):
continue
off = [f"{k} {size[k]},官方是 {v}" for k, v in want if size[k] and int(size[k]) != v]
if not off:
return a, f"模型结构是 {a.label}({names.split()[0]})"
near = near or f"结构名和 {a.label} 一样,但尺寸不对({';'.join(off)}),不是我们的权重"
return "other", near or f"模型结构是 {names.split()[0]},不是这个家族的"
def _header_names(ev):
"""What a GGUF header says about where it came from (general.name, base_model ...)."""
kv = (ev.get("gguf") or {}).get("kv") or {}
return {k: v for k, v in kv.items() if k.startswith(("general.name", "general.basename", "general.base_model",
"general.finetune", "general.source"))}
def _res(lineage, relation, family, confidence, evidence, flags):
return dict(lineage=lineage, relation=relation, family=family, confidence=confidence,
evidence=evidence, flags=flags, copy_of=None)
def classify_model(r, ev, g, cutoff, fam):
rid = r["repo_id"]
E, tier1 = [], {}
score = {k: 0.0 for k in fam.lineages}
name = rid.split("/")[1]
readme = (ev or {}).get("readme") or ""
text = " ".join([name, " ".join(r["tags"]), readme])
flags = ["nsfw"] if ("not-for-all-audiences" in r["tags"] or NSFW.search(rid) or NSFW_CARD.search(readme)) else []
lob = fam.lineage_of_base()
if rid in lob:
return _res(lob[rid], "official", True, "high", ["官方仓库"], flags)
if rid.startswith("MiniMaxAI/"):
return _res("unrelated", None, False, "high", ["MiniMax 其他模型的官方仓库"], flags)
decl = declared_member(rid, g, fam)
if ev is None:
return _res("unrelated", None, False, "medium",
["名字里的关键词是别的词的一部分,且没有任何相关信号"], flags)
if any(e.startswith("fatal") for e in ev.get("errors", [])):
return _res(decl or "unknown", None, bool(decl), "low",
["仓库读不到(可能已删除或设了访问限制)"] + ([f"声明底模属于 {decl}"] if decl else []), flags)
weight_ev = [] # tier-1 hits that come from the weights themselves
def t1(lin, why, from_weights=False):
tier1[lin] = tier1.get(lin, 0) + 1
E.append(why)
if from_weights:
weight_ev.append(lin)
files = ev.get("files", [])
keys = ev.get("st_keys") or (ev.get("gguf") or {}).get("tensor_names") or {}
markers = " ".join(keys.get("markers", []))
sig = ev.get("dit_sig") or {}
hits = sig.get("sig_hits", sig.get("h3_dim_hits", 0))
is_dit = hits >= 8
other_dit = sig.get("block_tensors", 0) >= 20 and hits == 0
is_lora = bool(LORA_KEY.search(markers)) or bool(ev.get("has_adapter_config"))
meta = json.dumps(ev.get("st_meta") or {}).lower()
cfg = ev.get("config") or {}
cfg_s = f'{cfg.get("model_type") or ""} {" ".join(cfg.get("architectures") or [])}'
gguf_arch = str(((ev.get("gguf") or {}).get("kv") or {}).get("general.architecture") or "")
patterns = " ".join(keys.get("patterns", []))
is_text_llm = (bool(TEXT_LLM_TYPES.search(str(cfg.get("model_type") or ""))) or "ForCausalLM" in cfg_s
or bool(TEXT_LLM_TYPES.search(gguf_arch))
or (not is_dit and bool(re.search(r"layers\.N\.(self_attn|mlp|linear_attn)", patterns))))
readable = bool(keys.get("n")) or bool(ev.get("gguf"))
mi = json.dumps(ev.get("model_index") or {})
ctx = {"markers": markers, "sig": sig, "is_dit": is_dit, "is_lora": is_lora}
arch, arch_why = architecture(ev, fam) or (None, None)
own = isinstance(arch, Arch) # the family's own layout (config / GGUF header)
other_arch = arch == "other"
# ---- Tier 1: structural evidence --------------------------------------------------
mirror = sha_mirror(files, fam)
if mirror and mirror[1] >= 0.5:
t1(mirror[0], f"{mirror[1]:.0%} 的权重文件与官方 {mirror[0]} 逐字节相同", True)
for rx, lin, why, full_only in fam.marker_rules:
if rx.search(markers) and not (full_only and is_lora):
t1(lin, why, not is_lora)
if fam.extra_structural:
for lin, why in fam.extra_structural(ev, ctx):
t1(lin, why, True)
pm = probe_match(ev.get("probe"), fam)
if pm:
lin, d, src = pm
if d < SAME:
t1(lin, f"抽查的权重数值与官方 {src} 完全相同", True)
elif d < 0.6:
t1(lin, f"抽查的权重数值最接近官方 {lin}(相对差异 {d:.1%}),是在它上面改过的", True)
for sub, lin in fam.index_rules:
if sub in mi:
t1(lin, f"model_index.json 是 {lin} 的管线")
break
if own and len(arch.members) == 1:
t1(arch.members[0], arch_why, True)
elif own: # shared by several members: rules the others out
E.append(arch_why)
for lin in fam.lineages:
if lin not in arch.members:
score[lin] -= 20
created = str(r.get("created_at") or "")
if meta not in ("{}", ""):
for rx, lin, why in fam.meta_rules:
m = rx.search(meta)
# Metadata strings can echo a repo name; a member released after the repo was
# created cannot be its training base, so skip such a match.
if m and not (created and cutoff.get(lin) and created < cutoff[lin]):
t1(lin, f"{why}({m.group(0)})")
break
# A text model belongs to the text member only on weight evidence, a declaration, or the
# member's own name; "does prompt expansion" alone describes a tool, not a derivative.
name_tags = name + " " + " ".join(r["tags"])
pe_like = bool(fam.text_member and is_text_llm and (
(fam.text_member_name and fam.text_member_name.search(name_tags))
or (mirror and mirror[0] == fam.text_member and mirror[1] >= 0.5) or decl == fam.text_member)
and not (created and cutoff.get(fam.text_member) and created < cutoff[fam.text_member]))
if pe_like:
t1(fam.text_member, f"是文本大模型,且标明是 {fam.text_member}")
# ---- Tier 2: declared base, repo content, dates ------------------------------------
if decl:
score[decl] += 5
E.append(f"声明的 base_model 指向 {decl}")
header = json.dumps(_header_names(ev)).lower() if fam.header_rules else ""
for rx, lin, why in fam.header_rules:
m = rx.search(header)
if m and not (created and cutoff.get(lin) and created < cutoff[lin]):
score[lin] += 3
E.append(f"{why}({m.group(0)})")
break
video_member = next((m.lineage for m in fam.members if m.modality == "video"), None)
if video_member and ev.get("has_video_media") and not is_text_llm:
score[video_member] += 3
E.append("仓库里有视频样例")
member_hit = False
for rx, lin, w, why, skip_text in fam.card_rules:
if rx.search(readme) and not (skip_text and is_text_llm):
score[lin] += w
E.append(why)
member_hit = member_hit or lin != fam.default_member
if fam.default_member and fam.family_text and fam.family_text.search(readme) and not member_hit:
score[fam.default_member] += 2
pt = r.get("pipeline_tag") or ""
for m in fam.members:
if m.modality in ("video", "audio") and m.modality in pt:
score[m.lineage] += 2
if is_dit:
for m in fam.members:
if m.modality != "text":
score[m.lineage] += 2
for lin, day in cutoff.items():
if created and day and created < day:
score[lin] -= 20
if lin != fam.text_member:
E.append(f"创建于 {created[:10]},早于 {lin} 发布,不可能基于 {lin}")
# ---- Tier 3: names -----------------------------------------------------------------
for m in fam.members:
if m.text_hint and m.text_hint.search(name):
score[m.lineage] += 1.5
if fam.default_member and fam.family_text and fam.family_text.search(name):
score[fam.default_member] += 1
# ---- Family gate -------------------------------------------------------------------
fam_text = bool(fam.family_text and fam.family_text.search(text)) or any(
m.text_hint and m.text_hint.search(text) for m in fam.members if m.lineage != fam.text_member)
name_fam = bool(fam.family_text and fam.family_text.search(name)) or any(
m.text_hint and m.text_hint.search(name) for m in fam.members)
if other_dit and is_lora and not tier1 and not decl:
return _res("unrelated", None, False, "high", ["是别的 DiT 模型的 LoRA(层的尺寸不对)"], flags)
component_for_family = bool(fam_text and fam.component_names and fam.component_names.search(name))
if other_dit and not tier1 and not decl and not name_fam and not component_for_family:
return _res("unrelated", None, False, "high", ["是别的模型的权重(层的尺寸不对),名字也没提到这个家族"], flags)
if other_arch and not tier1 and not decl and not name_fam:
return _res("unrelated", None, False, "high", [arch_why + ",名字也没提到这个家族"], flags)
author_hint = bool(fam.name_hint and fam.name_hint.search(name) and r["author"] in AUTHORS.get(fam.key, ()))
if not (decl or tier1 or is_dit or own or fam_text or author_hint):
return _res("unrelated", None, False, "medium", ["没有任何相关信号"], flags)
if author_hint and not (decl or tier1 or is_dit or own or fam_text):
E.append("作者发布过这个家族的衍生模型,名字里也有家族关键词")
if fam.default_member:
score[fam.default_member] += 1
# ---- Decide lineage ----------------------------------------------------------------
shaped = (list(arch.members) if own else
[m.lineage for m in fam.members if m.modality != "text"] if is_dit else [])
possible = [lin for lin in shaped if score[lin] > -10]
if tier1:
if len(tier1) == 1:
lineage, conf = next(iter(tier1)), "high"
else:
# Collections hold files of several members; let the repo's own framing choose.
ranked = sorted(tier1, key=lambda k: -score[k])
if score[ranked[0]] - score[ranked[1]] >= 2:
lineage, conf = ranked[0], "medium"
E.append("仓库里同时有 " + "、".join(tier1) + " 的权重,按仓库名和声明归到 " + ranked[0])
else:
lineage, conf = "unknown", "low"
E.append("结构证据互相矛盾:" + " / ".join(tier1))
elif shaped and len(possible) == 1:
lineage, conf = possible[0], "medium"
E.append(f"结构是这个家族的 {'DiT' if not own else arch.label},且创建时只有 {possible[0]} 已发布")
else:
ranked = sorted(score.items(), key=lambda x: -x[1]) + [(None, 0.0)] # a one-member family
(l1, s1), (_, s2) = ranked[0], ranked[1]
if s1 >= 4 and s1 - s2 >= 3:
lineage, conf = l1, "medium"
elif s1 > 0 and s1 - s2 >= 1:
lineage, conf = l1, "low"
else:
lineage, conf = "unknown", "low"
E.append("看得出属于这个家族,但分不清是哪个模型")
pe_like = pe_like or (lineage == fam.text_member and is_text_llm)
copy_of = community_mirror(r, ev, fam)
if copy_of:
flags.append("copy")
E.append(f"整仓权重与更早的 {copy_of} 逐字节相同,是重新上传")
outside_llm = is_text_llm and not own and (other_arch or not fam.own_llm)
family_weights = is_dit or own or bool(weight_ev) or (is_text_llm and fam.own_llm and not other_arch)
rel = relation(r, ev, is_lora, family_weights, outside_llm, mirror, pm, name,
E, pe_like, fam, readable, other_dit or other_arch, lineage)
if rel == "tool" and not (decl or name_fam or component_for_family):
# Weights from another model and only the card mentions the family: an ad, a comparison,
# or training data made with it. Not part of the ecosystem count.
return _res("unrelated", None, False, "medium", ["权重来自别的模型,只在模型卡里提到这个家族"], flags)
if rel == "tool":
E.append("权重来自别的模型,是用这个家族的输出蒸馏出来的" if other_arch and DISTILL_NAME.search(name)
else "权重不是来自这个家族,是给它用的周边工具")
if DISTILL_NAME.search(name) and rel in ("finetune", "adapter", "merge", "quantized"):
flags.append("distilled")
out = _res(lineage, rel, True, conf, E, flags)
out["copy_of"] = copy_of
return out
def relation(r, ev, is_lora, is_family_weights, is_text_llm, mirror, pm, name, E, pe_like, fam,
readable, other_dit, lineage):
wbytes = ev.get("weight_bytes", 0)
card = ev.get("card") or {}
main = ev.get("main_weight") or ""
if (ev.get("n_weight_files", 0) == 0 or wbytes < 1_000_000) and re.search(r"exl[23]", name, re.I):
E.append("EXL2/EXL3 仓库把每档量化放在各自的分支里,主分支只有说明")
return "quantized"
if ev.get("n_weight_files", 0) == 0 or wbytes < 1_000_000:
return "no-weights"
if mirror and mirror[1] >= 0.9:
return "mirror"
if is_text_llm and not pe_like:
if fam.text_component and fam.text_component.search(name + " " + json.dumps(ev.get("config"))):
E.append(fam.text_component_why)
return "component"
return "tool"
if not is_family_weights and not pe_like:
if fam.component_names and (fam.component_names.search(name) or fam.component_names.search(main)):
return "component"
# "tool" needs positive evidence that the weights come from another model;
# unreadable weights (gated, .bin, unparsed) fall through to the name rules below.
if (other_dit or (readable and not is_lora)) and not is_lora:
return "tool"
if is_lora or (not readable and LORA_NAME.search(name + " " + main)):
return "adapter"
bm = card.get("base_model")
multi = [b for b in bm if isinstance(b, str)] if isinstance(bm, list) else []
same = pm and pm[1] < SAME
meta_merge = bool(META_MERGE.search(json.dumps(ev.get("st_meta") or {})))
if (card.get("base_model_relation") == "merge" or len(multi) >= 2 or meta_merge or MERGE_NAME.search(name)
or any(p.startswith("merge:") for p in r["hf_parents"])) and not (same and not MERGE_NAME.search(name)):
return "merge"
if same:
return "repackage"
st_d = ev.get("st_dtypes") or {}
low = sum(v for k, v in st_d.items() if k in ("F8_E4M3", "F8_E5M2", "I8", "U8", "I4", "U4"))
quant = (ev.get("has_gguf") or (st_d and low / max(1, sum(st_d.values())) >= 0.25)
or QUANT_NAME.search(name) or QUANT_NAME.search(main)
or "quantization_config" in json.dumps(ev.get("config") or {}))
if quant:
native = fam.native_quant.get(lineage) if fam.native_quant else None
if native and not ev.get("has_gguf") and native.search(name + " " + main) \
and not re.search(r"gguf|mlx|[2-8]-?bit|int[48]|awq|gptq", name, re.I):
E.append(f"官方 {lineage} 本身就是这种量化格式,这里只是换了打包方式")
return "repackage"
return "quantized"
if MERGE_NAME.search(name):
return "merge"
if pm:
return "finetune"
if REPACK_NAME.search(name) and not TUNED_NAME.search(name):
return "repackage"
return "finetune"
def _weights(ev):
return {f["sha256"]: f["size"] for f in (ev or {}).get("files", [])
if f.get("sha256") and f.get("size", 0) > 1_000_000 and is_weight(f["name"])}
def community_mirror(r, ev, fam):
"""Whole-repo copy of an earlier community repo: each covers >= 90% of the other's
weight bytes. Being collected into a bigger repo, or copying part of one, does not count."""
c = COMMUNITY.get(fam.key)
if not c:
return None
mine = _weights(ev)
total = sum(mine.values())
if not total:
return None
me = str(r.get("created_at") or "")
shared = {}
for sha, size in mine.items():
for other in c["by_sha"].get(sha, ()):
if other != r["repo_id"]:
shared[other] = shared.get(other, 0) + size
for other, b in sorted(shared.items(), key=lambda x: -x[1]):
if b / total < 0.9:
break
o_total = c["total"][other]
if o_total and b / o_total >= 0.9 and c["created"].get(other, "9999") < me:
return other
return None
def classify_space(r, model_labels, fam):
lins, E = set(), []
for m in r["space_models"]:
lab = model_labels.get(m)
if lab and lab["family"] and lab["lineage"] in fam.lineages:
lins.add(lab["lineage"])
if lins:
E.append("调用的模型:" + "、".join(sorted(lins)))
text = r["repo_id"] + " " + " ".join(r["tags"])
if not lins:
lins = _text_members(text, r, fam)
if lins:
E.append("名字或说明里提到这个家族")
if not lins:
return _res("unrelated", "app", False, "medium", ["没有调用这个家族的模型,名字里的关键词另有所指"], [])
lineage = fam.default_member if fam.default_member in lins else sorted(lins)[0]
return _res(lineage, "app", True, "high" if r["space_models"] else "low", E, [])
def classify_dataset(r, fam):
lins = _text_members(r["repo_id"] + " " + " ".join(r["tags"]), r, fam)
if not lins:
return _res("unrelated", "dataset", False, "medium", ["名字里的关键词另有所指"], [])
lin = sorted(lins)[0]
return _res(lin, "dataset", True, "low", ["名字或数据卡提到 " + lin], [])
def _text_members(text, r, fam):
for m in fam.members:
if m.text_hint and m.lineage != fam.text_member and m.text_hint.search(text):
return {m.lineage}
if (fam.family_text and fam.family_text.search(text)) or any(s.startswith("fulltext") for s in r["sources"]):
return {fam.default_member or "unknown"}
# The author publishes family models and the name carries the family keyword as a token.
if fam.name_hint and fam.name_hint.search(r["repo_id"].split("/")[1]) and r["author"] in AUTHORS.get(fam.key, ()):
return {fam.default_member or "unknown"}
return set()
def classify_all(raw_today, cache, fam):
"""raw_today: one day's raw frame for this family. Returns a list of label dicts."""
g = declared_graph(raw_today)
created = dict(zip(raw_today.repo_id, raw_today.created_at))
AUTHORS[fam.key] = {r.author for r in raw_today.itertuples() if r.kind == "model" and not
r.repo_id.startswith("MiniMaxAI/") and (declared_member(r.repo_id, g, fam)
or fam.family_text.search(r.repo_id))}
by_sha, total = {}, {}
for rid, ev in cache.items():
w = _weights(ev)
total[rid] = sum(w.values())
for sha in w:
by_sha.setdefault(sha, []).append(rid)
COMMUNITY[fam.key] = {"by_sha": by_sha, "total": total,
"created": {k: str(v or "9999") for k, v in created.items()}}
# A derivative cannot predate its base repo; the default member never needs the check.
cutoff = {m.lineage: min((str(created[x]) for x in m.repos if created.get(x)), default="")
for m in fam.members if m.lineage != fam.default_member}
out, mlabels = [], {}
rows = raw_today.to_dict("records")
for r in rows:
if r["kind"] != "model":
continue
lab = classify_model(r, cache.get(r["repo_id"]), g, cutoff, fam)
lab.update(declared_status(r, lab, g, fam))
mlabels[r["repo_id"]] = lab
out.append({"kind": "model", "repo_id": r["repo_id"], **lab})
_nsfw_spread(mlabels, g, fam)
for r in rows:
if r["kind"] == "space":
out.append({"kind": "space", "repo_id": r["repo_id"], **classify_space(r, mlabels, fam)})
elif r["kind"] == "dataset":
out.append({"kind": "dataset", "repo_id": r["repo_id"], **classify_dataset(r, fam)})
for o in out:
o["classifier_version"] = VERSION
o["family_key"] = fam.key
return out
CONFIDENCE = {"high": 3, "medium": 2, "low": 1}
def resolve_overlaps(by_family, others=None):
"""One repo counts in one family. Where several families claim the same repo as a derived
model, the strongest claim keeps it (confidence, then family order: h3, m, music); in the
other families it gets the flag "other_family" and family=False, so it is not counted twice.
`others`: labels of families not run today, which take part but are not changed.
Returns {repo: family that keeps it} for the repos that moved."""
order = list(by_family) + [k for k in (others or {}) if k not in by_family]
from . import families as registry
order.sort(key=lambda k: list(registry.FAMILIES).index(k) if k in registry.FAMILIES else 99)
claims = {}
for key in order:
for x in by_family.get(key) or (others or {}).get(key) or []:
if x["kind"] == "model" and x["family"] and x["relation"] in DERIVED:
claims.setdefault(x["repo_id"], []).append((-CONFIDENCE.get(x["confidence"], 0), order.index(key), key))
moved = {}
for key, labs in by_family.items():
for x in labs:
c = claims.get(x["repo_id"], [])
if len(c) > 1 and min(c)[2] != key:
keeper = min(c)[2]
x["family"] = False
x["flags"] = x["flags"] + ["other_family"]
x["evidence"] = x["evidence"] + [f"另一个系列({keeper})的证据更强,算在那边"]
moved[x["repo_id"]] = keeper
return moved
def _nsfw_spread(mlabels, g, fam):
"""Adult flags beyond a repo's own name/tags/card. These only decide what the public page
names; every repo is still counted.
- Whole-repo copies and declared children of an adult repo (a GGUF of an adult finetune
rarely says so in its name).
- Every repo of an author with several adult repos ("nsfw_author"), except publishers in
fam.nsfw_author_exempt whose adult repos are a small part of their work.
"""
hidden = lambda rid: bool({"nsfw", "nsfw_author"} & set(mlabels.get(rid, {}).get("flags", [])))
def spread():
for _ in range(4):
for rid, lab in mlabels.items():
if hidden(rid):
continue
ups = ([lab["copy_of"]] if lab.get("copy_of") else []) + [p for _, p in g.get(rid, [])]
if any(hidden(u) for u in ups):
lab["flags"].append("nsfw")
spread()
by_author = {}
for rid, lab in mlabels.items():
if lab["family"]:
by_author.setdefault(rid.split("/")[0], []).append(lab)
for author, labs in by_author.items():
n = sum("nsfw" in x["flags"] for x in labs)
if author in fam.nsfw_author_exempt:
continue
if n >= 3 or (n >= 2 and n / len(labs) >= 0.25) or (n and n / len(labs) >= 0.5):
for x in labs:
if "nsfw" not in x["flags"]:
x["flags"].append("nsfw_author")
spread()
def declared_status(r, lab, g, fam):
decl = declared_member(r["repo_id"], g, fam)
hf_rel = r["hf_parents"][0].split(":")[0] if r["hf_parents"] else None
out = {"declared_lineage": decl, "declared_relation": hf_rel, "declared_status": None,
"proposed_base_model": None, "proposed_relation": None}
if not lab["family"] or lab["relation"] not in DERIVED or lab["lineage"] not in fam.lineages:
return out
base = fam.base_of(lab["lineage"])
if decl is None:
out["declared_status"] = "missing"
elif decl != lab["lineage"]:
out["declared_status"] = "wrong_base"
elif lab["relation"] in HF_RELATIONS and hf_rel and hf_rel != lab["relation"] \
and any(p.split(":", 1)[1] == base for p in r["hf_parents"]):
out["declared_status"] = "wrong_relation"
else:
out["declared_status"] = "ok"
if out["declared_status"] != "ok":
out["proposed_base_model"] = base
# HF only knows four relations; for the rest we set base_model and let HF infer.
out["proposed_relation"] = lab["relation"] if lab["relation"] in HF_RELATIONS else None
return out