Download code/multi-hop/generate_eval_uniform.py from fhyfhy/Implicit-Reasoning-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 6.06 kB
-
https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/generate_eval_uniform.py
- Command line
-
hf download hf://fhyfhy/Implicit-Reasoning-checkpoints/code/multi-hop/generate_eval_uniform.py
-
curl -L -o generate_eval_uniform.py https://huggingface.co/fhyfhy/Implicit-Reasoning-checkpoints/resolve/main/code/multi-hop/generate_eval_uniform.py
6.06 kB
| import argparse | |
| import json | |
| import os | |
| import re | |
| from typing import Dict, Optional, Tuple | |
| import torch | |
| from generate_data import DataGenerator | |
| def load_config(config_path: str) -> Dict: | |
| with open(config_path, "r") as f: | |
| return json.load(f) | |
| def infer_output_dir(config_path: str, config: Dict) -> str: | |
| if config.get("output_dir"): | |
| return config["output_dir"] | |
| num_e = config.get("num_entities", "X") | |
| num_r = config.get("num_relations", "X") | |
| k = config.get("num_hops", "X") | |
| d = config.get("edges_per_entity", "X") | |
| alpha = config.get("sampling_alpha") | |
| if alpha is not None: | |
| dist_str = f"powerlaw_a{alpha}" | |
| else: | |
| dist_str = "uniform" | |
| exp_id = os.path.basename(config_path).replace(".json", "") | |
| return f"archives/E{num_e}_R{num_r}_k{k}_D{d}_{dist_str}/{exp_id}" | |
| def parse_params_from_dir(model_dir: str) -> Dict: | |
| pattern = re.compile(r"E(?P<num_e>\d+)_R(?P<num_r>\d+)_k(?P<num_hops>\d+)_D(?P<edges>\d+)_") | |
| for part in model_dir.split(os.sep): | |
| match = pattern.match(part) | |
| if match: | |
| return { | |
| "num_entities": int(match.group("num_e")), | |
| "num_relations": int(match.group("num_r")), | |
| "num_hops": int(match.group("num_hops")), | |
| "edges_per_entity": int(match.group("edges")), | |
| } | |
| return {} | |
| def _load_seed_from_dir(path: str) -> Optional[int]: | |
| training_args_path = os.path.join(path, "training_args.bin") | |
| if os.path.exists(training_args_path): | |
| try: | |
| training_args = torch.load(training_args_path, map_location="cpu") | |
| seed = getattr(training_args, "seed", None) | |
| if seed is not None: | |
| return int(seed) | |
| except Exception: | |
| pass | |
| trainer_state_path = os.path.join(path, "trainer_state.json") | |
| if os.path.exists(trainer_state_path): | |
| try: | |
| with open(trainer_state_path, "r") as f: | |
| state = json.load(f) | |
| if "seed" in state: | |
| return int(state["seed"]) | |
| except Exception: | |
| pass | |
| return None | |
| def load_seed(model_dir: str) -> Optional[int]: | |
| seed = _load_seed_from_dir(model_dir) | |
| if seed is not None: | |
| return seed | |
| # Try to infer from run directory name, e.g., ..._S42 | |
| match = re.search(r"_S(\d+)(?:$|_)", os.path.basename(model_dir)) | |
| if match: | |
| return int(match.group(1)) | |
| # Fallback: check any checkpoint directory for training args | |
| try: | |
| for name in os.listdir(model_dir): | |
| if name.startswith("checkpoint-"): | |
| seed = _load_seed_from_dir(os.path.join(model_dir, name)) | |
| if seed is not None: | |
| return seed | |
| except Exception: | |
| pass | |
| return None | |
| def unique_output_path(base_dir: str, filename: str) -> str: | |
| path = os.path.join(base_dir, filename) | |
| if not os.path.exists(path): | |
| return path | |
| name, ext = os.path.splitext(filename) | |
| idx = 1 | |
| while True: | |
| candidate = os.path.join(base_dir, f"{name}_{idx}{ext}") | |
| if not os.path.exists(candidate): | |
| return candidate | |
| idx += 1 | |
| def resolve_model_dir(model_dir: Optional[str], config_path: Optional[str]) -> Tuple[str, Optional[Dict]]: | |
| config = None | |
| if config_path: | |
| config = load_config(config_path) | |
| model_dir = infer_output_dir(config_path, config) | |
| if not model_dir: | |
| raise ValueError("Provide --model_dir or --config.") | |
| if os.path.basename(model_dir).startswith("checkpoint-"): | |
| model_dir = os.path.dirname(model_dir) | |
| return model_dir, config | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description="Generate uniform eval JSON for an existing run.") | |
| parser.add_argument("--model_dir", type=str, default=None, help="Training output directory (archives/...)") | |
| parser.add_argument("--config", type=str, default=None, help="Training config (used to infer output dir + params)") | |
| parser.add_argument("--num_examples", type=int, default=4096, help="Number of eval examples to generate") | |
| parser.add_argument("--output_name", type=str, default="eval_test_uniform.json", help="Output filename") | |
| parser.add_argument("--seed", type=int, default=None, help="Override seed (if not provided, auto-detect)") | |
| args = parser.parse_args() | |
| model_dir, config = resolve_model_dir(args.model_dir, args.config) | |
| if not os.path.isdir(model_dir): | |
| raise ValueError(f"Model dir not found: {model_dir}") | |
| params = {} | |
| if config: | |
| params.update({ | |
| "num_entities": config.get("num_entities"), | |
| "num_relations": config.get("num_relations"), | |
| "num_hops": config.get("num_hops"), | |
| "edges_per_entity": config.get("edges_per_entity"), | |
| }) | |
| for k, v in parse_params_from_dir(model_dir).items(): | |
| if not params.get(k): | |
| params[k] = v | |
| missing = [k for k in ["num_entities", "num_relations", "num_hops", "edges_per_entity"] if not params.get(k)] | |
| if missing: | |
| raise ValueError(f"Missing params: {missing}. Provide --config or use a model_dir with E/R/k/D in path.") | |
| seed = args.seed | |
| if seed is None: | |
| seed = load_seed(model_dir) | |
| if seed is None: | |
| raise ValueError("Seed not found. Provide --seed or ensure training_args.bin is present.") | |
| generator = DataGenerator( | |
| num_entities=int(params["num_entities"]), | |
| num_relations=int(params["num_relations"]), | |
| seed=int(seed), | |
| sampling_alpha=None, # force uniform | |
| ) | |
| generator.generate_graph(edges_per_entity=int(params["edges_per_entity"])) | |
| examples = generator.generate_test_examples(num_examples=args.num_examples, num_hops=int(params["num_hops"])) | |
| output_path = unique_output_path(model_dir, args.output_name) | |
| with open(output_path, "w") as f: | |
| json.dump(examples, f, indent=2) | |
| print(f"Saved {len(examples)} examples to {output_path}") | |
| if __name__ == "__main__": | |
| main() | |