Datasets:
Download scripts/build_dataset.py from Kevynf/llm-graph-poisoning-data: direct link, hf CLI and curl.
- Browser
- Download file 18.7 kB
-
https://huggingface.co/datasets/Kevynf/llm-graph-poisoning-data/resolve/main/scripts/build_dataset.py
- Command line
-
hf download hf://datasets/Kevynf/llm-graph-poisoning-data/scripts/build_dataset.py
-
curl -L -o build_dataset.py https://huggingface.co/datasets/Kevynf/llm-graph-poisoning-data/resolve/main/scripts/build_dataset.py
18.7 kB
| #!/usr/bin/env python3 | |
| """Build the Hugging Face dataset export from llm-graph-poisoning-exp outputs.""" | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| import re | |
| import shutil | |
| from pathlib import Path | |
| from typing import Any | |
| import pandas as pd | |
| CONDITION_PATTERN = r"(?:c|[fsb]_r\d+)" | |
| PERSONA_RE = re.compile( | |
| rf"^p(?P<nodes>50|200)_(?:(?P<model>.+)_)?" | |
| rf"(?P<condition>{CONDITION_PATTERN})_w_names_w_interests\.json$" | |
| ) | |
| GRAPH_DIR_RE = re.compile( | |
| rf"^local_(?P<model>.+?)_w_names_w_interests_(?P<condition>{CONDITION_PATTERN})_" | |
| r"p(?P<nodes>50|200)_k(?P<count>\d+)_s(?P<start>\d+)$" | |
| ) | |
| GRAPH_SEED_RE = re.compile(r"_(?P<seed>\d+)\.adj$") | |
| ARRAY_RE = re.compile( | |
| rf"^(?P<kind>embeddings|labels)_(?P<condition>{CONDITION_PATTERN})" | |
| rf"(?P<large>_large)?(?:_(?P<model>(?!trigger_masked\.npy$).+))?\.npy$" | |
| ) | |
| TRIGGER_MASKED_ARRAY_RE = re.compile( | |
| r"^embeddings_(?P<condition>b_r\d+)_trigger_masked\.npy$" | |
| ) | |
| NODE_IDS_RE = re.compile( | |
| rf"^node_ids_(?P<condition>{CONDITION_PATTERN})(?P<large>_large)?" | |
| rf"(?:_(?P<model>.+))?\.json$" | |
| ) | |
| DEFAULT_MODELS = {"p50": "qwen3-max", "p200": "mimo-v2.5-pro"} | |
| METRIC_PREFIXES = { | |
| "backdoor_link_gap", | |
| "backdoor_probability_gap", | |
| "backdoor_targeted", | |
| "feature_metrics", | |
| "gnn_metrics", | |
| "link_pred_metrics", | |
| "structural_metrics", | |
| } | |
| def condition_fields(condition: str) -> tuple[str, float]: | |
| if condition == "c": | |
| return "clean", 0.0 | |
| attack_types = {"f": "feature", "s": "structure", "b": "backdoor"} | |
| prefix, rate = condition.split("_r", 1) | |
| return attack_types[prefix], int(rate) / 100.0 | |
| def file_sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def copy_file(source: Path, destination: Path) -> None: | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copy2(source, destination) | |
| def resolved_model(dataset: str, parsed_model: str | None) -> str: | |
| return parsed_model or DEFAULT_MODELS[dataset] | |
| def published_raw_name(source: Path, dataset: str, model: str) -> str: | |
| """Namespace legacy p200 Mimo artifacts without renaming source data.""" | |
| if dataset != "p200" or model != DEFAULT_MODELS["p200"]: | |
| return source.name | |
| if source.name.startswith("p200_"): | |
| return source.name.replace("p200_", f"p200_{model}_", 1) | |
| stem, suffix = source.stem, source.suffix | |
| return f"{stem}_{model}{suffix}" | |
| def add_manifest_row( | |
| rows: list[dict[str, Any]], | |
| root: Path, | |
| path: Path, | |
| source_path: str, | |
| artifact_type: str, | |
| dataset: str, | |
| condition: str = "", | |
| graph_seed: int | str = "", | |
| model: str = "", | |
| ) -> None: | |
| attack_type, attack_rate = condition_fields(condition) if condition else ("", "") | |
| rows.append( | |
| { | |
| "published_path": path.relative_to(root).as_posix(), | |
| "source_path": source_path, | |
| "artifact_type": artifact_type, | |
| "dataset": dataset, | |
| "condition": condition, | |
| "attack_type": attack_type, | |
| "attack_rate": attack_rate, | |
| "model": model or DEFAULT_MODELS.get(dataset, ""), | |
| "num_nodes": dataset.removeprefix("p") if dataset else "", | |
| "graph_seed": graph_seed, | |
| "bytes": path.stat().st_size, | |
| "sha256": file_sha256(path), | |
| } | |
| ) | |
| def parse_adjacency(path: Path) -> tuple[list[tuple[int, int]], int]: | |
| rows: list[tuple[int, int]] = [] | |
| source = 0 | |
| for raw_line in path.read_text(encoding="utf-8").splitlines(): | |
| line = raw_line.strip() | |
| if not line or line.startswith("#"): | |
| continue | |
| for target in line.split(): | |
| rows.append((source, int(target))) | |
| source += 1 | |
| return rows, source | |
| def write_dataframe( | |
| frame: pd.DataFrame, | |
| path: Path, | |
| manifest_rows: list[dict[str, Any]], | |
| root: Path, | |
| artifact_type: str, | |
| dataset: str, | |
| ) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| frame.to_parquet(path, index=False) | |
| model = "multiple" if dataset == "p200" else DEFAULT_MODELS[dataset] | |
| add_manifest_row( | |
| manifest_rows, | |
| root, | |
| path, | |
| "", | |
| artifact_type, | |
| dataset, | |
| model=model, | |
| ) | |
| def build( | |
| source_root: Path, | |
| output_root: Path, | |
| published_root: Path | None = None, | |
| ) -> None: | |
| text_root = source_root / "text-files" | |
| stats_root = source_root / "stats" | |
| if not text_root.is_dir() or not stats_root.is_dir(): | |
| raise FileNotFoundError("Expected text-files/ and stats/ under the experiment root") | |
| managed_dirs = [output_root / name for name in ("raw", "processed", "metrics", "metadata")] | |
| existing = [path for path in managed_dirs if path.exists()] | |
| if existing: | |
| joined = ", ".join(str(path) for path in existing) | |
| raise FileExistsError(f"Refusing to overwrite existing export directories: {joined}") | |
| manifest_rows: list[dict[str, Any]] = [] | |
| node_rows: dict[str, list[dict[str, Any]]] = {"p50": [], "p200": []} | |
| edge_rows: dict[str, list[dict[str, Any]]] = {"p50": [], "p200": []} | |
| graph_rows: dict[str, list[dict[str, Any]]] = {"p50": [], "p200": []} | |
| for source in sorted(text_root.glob("*.json")): | |
| persona_match = PERSONA_RE.match(source.name) | |
| node_ids_match = NODE_IDS_RE.match(source.name) | |
| if persona_match: | |
| dataset = f"p{persona_match.group('nodes')}" | |
| condition = persona_match.group("condition") | |
| model = resolved_model(dataset, persona_match.group("model")) | |
| destination = ( | |
| output_root | |
| / "raw" | |
| / dataset | |
| / "personas" | |
| / published_raw_name(source, dataset, model) | |
| ) | |
| copy_file(source, destination) | |
| add_manifest_row( | |
| manifest_rows, | |
| output_root, | |
| destination, | |
| source.relative_to(source_root).as_posix(), | |
| "personas", | |
| dataset, | |
| condition, | |
| model=model, | |
| ) | |
| attack_type, attack_rate = condition_fields(condition) | |
| payload = json.loads(source.read_text(encoding="utf-8")) | |
| for node_id, record in payload.items(): | |
| name = record.get("name", []) | |
| if isinstance(name, list): | |
| full_name = " ".join(str(part) for part in name) | |
| else: | |
| full_name = str(name) | |
| interests = str(record.get("interests", "")) | |
| node_rows[dataset].append( | |
| { | |
| "dataset": dataset, | |
| "condition": condition, | |
| "attack_type": attack_type, | |
| "attack_rate": attack_rate, | |
| "model": model, | |
| "node_id": int(node_id), | |
| "gender": record.get("gender"), | |
| "race_ethnicity": record.get("race/ethnicity"), | |
| "age": record.get("age"), | |
| "religion": record.get("religion"), | |
| "political_affiliation": record.get("political affiliation"), | |
| "name": full_name, | |
| "interests": interests, | |
| "contains_backdoor_trigger": "orchid-anchor" in interests.lower(), | |
| } | |
| ) | |
| elif node_ids_match: | |
| dataset = "p200" if node_ids_match.group("large") else "p50" | |
| condition = node_ids_match.group("condition") | |
| model = resolved_model(dataset, node_ids_match.group("model")) | |
| destination = ( | |
| output_root | |
| / "raw" | |
| / dataset | |
| / "node_ids" | |
| / published_raw_name(source, dataset, model) | |
| ) | |
| copy_file(source, destination) | |
| add_manifest_row( | |
| manifest_rows, | |
| output_root, | |
| destination, | |
| source.relative_to(source_root).as_posix(), | |
| "node_ids", | |
| dataset, | |
| condition, | |
| model=model, | |
| ) | |
| array_sources = {source.name: source for source in text_root.glob("*.npy")} | |
| if published_root is not None: | |
| for source in (published_root / "raw" / "p50" / "arrays").glob( | |
| "embeddings_b_r*_trigger_masked.npy" | |
| ): | |
| array_sources.setdefault(source.name, source) | |
| for source in sorted(array_sources.values(), key=lambda path: path.name): | |
| trigger_masked_match = TRIGGER_MASKED_ARRAY_RE.match(source.name) | |
| if trigger_masked_match: | |
| condition = trigger_masked_match.group("condition") | |
| destination = output_root / "raw" / "p50" / "arrays" / source.name | |
| copy_file(source, destination) | |
| add_manifest_row( | |
| manifest_rows, | |
| output_root, | |
| destination, | |
| f"text-files/{source.name}", | |
| "trigger_masked_embeddings", | |
| "p50", | |
| condition, | |
| model=DEFAULT_MODELS["p50"], | |
| ) | |
| continue | |
| match = ARRAY_RE.match(source.name) | |
| if not match: | |
| continue | |
| dataset = "p200" if match.group("large") else "p50" | |
| condition = match.group("condition") | |
| model = resolved_model(dataset, match.group("model")) | |
| destination = ( | |
| output_root | |
| / "raw" | |
| / dataset | |
| / "arrays" | |
| / published_raw_name(source, dataset, model) | |
| ) | |
| copy_file(source, destination) | |
| add_manifest_row( | |
| manifest_rows, | |
| output_root, | |
| destination, | |
| source.relative_to(source_root).as_posix(), | |
| match.group("kind"), | |
| dataset, | |
| condition, | |
| model=model, | |
| ) | |
| for source_dir in sorted(path for path in text_root.iterdir() if path.is_dir()): | |
| match = GRAPH_DIR_RE.match(source_dir.name) | |
| if not match: | |
| continue | |
| dataset = f"p{match.group('nodes')}" | |
| condition = match.group("condition") | |
| model = match.group("model") | |
| attack_type, attack_rate = condition_fields(condition) | |
| for source in sorted(source_dir.glob("*.adj")): | |
| seed_match = GRAPH_SEED_RE.search(source.name) | |
| if not seed_match: | |
| raise ValueError(f"Cannot parse graph seed from {source}") | |
| graph_seed = int(seed_match.group("seed")) | |
| destination = output_root / "raw" / dataset / "graphs" / condition / source.name | |
| copy_file(source, destination) | |
| add_manifest_row( | |
| manifest_rows, | |
| output_root, | |
| destination, | |
| source.relative_to(source_root).as_posix(), | |
| "adjacency_list", | |
| dataset, | |
| condition, | |
| graph_seed, | |
| model, | |
| ) | |
| adjacency, num_nodes = parse_adjacency(source) | |
| graph_id = f"{dataset}_{model}_{condition}_seed{graph_seed}" | |
| for source_id, target_id in adjacency: | |
| edge_rows[dataset].append( | |
| { | |
| "dataset": dataset, | |
| "graph_id": graph_id, | |
| "condition": condition, | |
| "attack_type": attack_type, | |
| "attack_rate": attack_rate, | |
| "model": model, | |
| "graph_seed": graph_seed, | |
| "source": source_id, | |
| "target": target_id, | |
| } | |
| ) | |
| graph_rows[dataset].append( | |
| { | |
| "dataset": dataset, | |
| "graph_id": graph_id, | |
| "condition": condition, | |
| "attack_type": attack_type, | |
| "attack_rate": attack_rate, | |
| "model": model, | |
| "graph_seed": graph_seed, | |
| "num_nodes": num_nodes, | |
| "num_directed_edges": len(adjacency), | |
| "raw_path": destination.relative_to(output_root).as_posix(), | |
| } | |
| ) | |
| metric_sources = {source.name: source for source in stats_root.glob("*.csv")} | |
| if published_root is not None: | |
| published_probability_gap = ( | |
| published_root / "metrics" / "p50" / "backdoor_probability_gap.csv" | |
| ) | |
| if published_probability_gap.is_file(): | |
| metric_sources.setdefault( | |
| published_probability_gap.name, | |
| published_probability_gap, | |
| ) | |
| for source in sorted(metric_sources.values(), key=lambda path: path.name): | |
| metric_prefix = next( | |
| (prefix for prefix in METRIC_PREFIXES if source.stem == prefix or source.stem.startswith(f"{prefix}_large")), | |
| None, | |
| ) | |
| if metric_prefix is None or "rerun" in source.stem: | |
| continue | |
| dataset = "p200" if "_large" in source.stem else "p50" | |
| model_suffix = source.stem.partition("_large_")[2] | |
| model = resolved_model(dataset, model_suffix or None) | |
| destination = ( | |
| output_root | |
| / "metrics" | |
| / dataset | |
| / published_raw_name(source, dataset, model) | |
| ) | |
| copy_file(source, destination) | |
| add_manifest_row( | |
| manifest_rows, | |
| output_root, | |
| destination, | |
| f"stats/{source.name}", | |
| "evaluation_metrics", | |
| dataset, | |
| model=model, | |
| ) | |
| for dataset in ("p50", "p200"): | |
| write_dataframe( | |
| pd.DataFrame(node_rows[dataset]).sort_values(["model", "condition", "node_id"]), | |
| output_root / "processed" / dataset / "nodes.parquet", | |
| manifest_rows, | |
| output_root, | |
| "normalized_nodes", | |
| dataset, | |
| ) | |
| write_dataframe( | |
| pd.DataFrame(edge_rows[dataset]).sort_values( | |
| ["model", "condition", "graph_seed", "source", "target"] | |
| ), | |
| output_root / "processed" / dataset / "edges.parquet", | |
| manifest_rows, | |
| output_root, | |
| "normalized_edges", | |
| dataset, | |
| ) | |
| write_dataframe( | |
| pd.DataFrame(graph_rows[dataset]).sort_values(["model", "condition", "graph_seed"]), | |
| output_root / "processed" / dataset / "graphs.parquet", | |
| manifest_rows, | |
| output_root, | |
| "graph_metadata", | |
| dataset, | |
| ) | |
| metadata_dir = output_root / "metadata" | |
| metadata_dir.mkdir(parents=True, exist_ok=True) | |
| config = { | |
| "dataset_title": "Generation-Time Poisoning of LLM-Generated Social Networks", | |
| "license": "CC-BY-4.0", | |
| "variants": { | |
| "p50": {"nodes": 50, "models": ["qwen3-max"], "graph_seeds": 10}, | |
| "p200": { | |
| "nodes": 200, | |
| "models": ["deepseek-v4-flash", "mimo-v2.5-pro"], | |
| "graph_seeds": 3, | |
| }, | |
| }, | |
| "conditions": { | |
| "c": "clean", | |
| "f_rXX": "feature poisoning", | |
| "s_rXX": "structural poisoning; reuses clean personas and embeddings", | |
| "b_rXX": "backdoor poisoning", | |
| }, | |
| "attack_rate_definition": ( | |
| "Global node budget floor(N * attack_rate), capped by the eligible " | |
| "candidate-set size; not the realized fraction of changed graph nodes " | |
| "or edges." | |
| ), | |
| } | |
| config_path = metadata_dir / "generation_config.json" | |
| config_path.write_text(json.dumps(config, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") | |
| add_manifest_row( | |
| manifest_rows, output_root, config_path, "", "generation_config", "" | |
| ) | |
| manifest_path = metadata_dir / "manifest.csv" | |
| fieldnames = [ | |
| "published_path", | |
| "source_path", | |
| "artifact_type", | |
| "dataset", | |
| "condition", | |
| "attack_type", | |
| "attack_rate", | |
| "model", | |
| "num_nodes", | |
| "graph_seed", | |
| "bytes", | |
| "sha256", | |
| ] | |
| with manifest_path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | |
| writer.writeheader() | |
| writer.writerows(sorted(manifest_rows, key=lambda row: row["published_path"])) | |
| checksum_path = metadata_dir / "checksums.sha256" | |
| checksum_entries: list[str] = [] | |
| excluded_parts = {".git", ".venv", "__pycache__", "verification-download"} | |
| for path in sorted(output_root.rglob("*")): | |
| if ( | |
| not path.is_file() | |
| or excluded_parts.intersection(path.parts) | |
| or path.suffix == ".pyc" | |
| ): | |
| continue | |
| if path == checksum_path: | |
| continue | |
| relative = path.relative_to(output_root).as_posix() | |
| checksum_entries.append(f"{file_sha256(path)} {relative}") | |
| checksum_path.write_text("\n".join(checksum_entries) + "\n", encoding="utf-8") | |
| print(f"Built dataset with {len(manifest_rows)} data artifacts") | |
| print(f"Checksummed {len(checksum_entries)} published files") | |
| for dataset in ("p50", "p200"): | |
| print( | |
| f"{dataset}: {len(node_rows[dataset])} persona rows, " | |
| f"{len(edge_rows[dataset])} directed edge rows, " | |
| f"{len(graph_rows[dataset])} graphs" | |
| ) | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--source-root", | |
| type=Path, | |
| default=Path(__file__).resolve().parents[2] / "llm-graph-poisoning-exp", | |
| help="Experiment repository root.", | |
| ) | |
| parser.add_argument( | |
| "--output-root", | |
| type=Path, | |
| default=Path(__file__).resolve().parent.parent, | |
| help="Dataset repository root.", | |
| ) | |
| parser.add_argument( | |
| "--published-root", | |
| type=Path, | |
| default=Path(__file__).resolve().parent.parent, | |
| help="Existing published dataset used to recover release-only artifacts.", | |
| ) | |
| args = parser.parse_args() | |
| build( | |
| args.source_root.resolve(), | |
| args.output_root.resolve(), | |
| args.published_root.resolve(), | |
| ) | |
| if __name__ == "__main__": | |
| main() | |